##// END OF EJS Templates
- improve support for tab-completion under emacs...
fperez -
Show More

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

@@ -1,2677 +1,2690 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 984 2005-12-31 08:40:31Z fperez $"""
4 $Id: Magic.py 986 2005-12-31 23:07:31Z 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 arguments as strings."""
131 arguments as strings.
132
133 Note that slices can be called with two notations:
134
135 N:M -> standard python form, means including items N...(M-1).
136
137 N-M -> include items N..M (closed endpoint)."""
132 138
133 139 cmds = []
134 140 for chunk in slices:
135 141 if ':' in chunk:
136 142 ini,fin = map(int,chunk.split(':'))
143 elif '-' in chunk:
144 ini,fin = map(int,chunk.split('-'))
145 fin += 1
137 146 else:
138 147 ini = int(chunk)
139 148 fin = ini+1
140 149 cmds.append(self.shell.input_hist[ini:fin])
141 150 return cmds
142 151
143 152 def _ofind(self,oname):
144 153 """Find an object in the available namespaces.
145 154
146 155 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
147 156
148 157 Has special code to detect magic functions.
149 158 """
150 159
151 160 oname = oname.strip()
152 161
153 162 # Namespaces to search in:
154 163 user_ns = self.shell.user_ns
155 164 internal_ns = self.shell.internal_ns
156 165 builtin_ns = __builtin__.__dict__
157 166 alias_ns = self.shell.alias_table
158 167
159 168 # Put them in a list. The order is important so that we find things in
160 169 # the same order that Python finds them.
161 170 namespaces = [ ('Interactive',user_ns),
162 171 ('IPython internal',internal_ns),
163 172 ('Python builtin',builtin_ns),
164 173 ('Alias',alias_ns),
165 174 ]
166 175
167 176 # initialize results to 'null'
168 177 found = 0; obj = None; ospace = None; ds = None;
169 178 ismagic = 0; isalias = 0
170 179
171 180 # Look for the given name by splitting it in parts. If the head is
172 181 # found, then we look for all the remaining parts as members, and only
173 182 # declare success if we can find them all.
174 183 oname_parts = oname.split('.')
175 184 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
176 185 for nsname,ns in namespaces:
177 186 try:
178 187 obj = ns[oname_head]
179 188 except KeyError:
180 189 continue
181 190 else:
182 191 for part in oname_rest:
183 192 try:
184 193 obj = getattr(obj,part)
185 194 except:
186 195 # Blanket except b/c some badly implemented objects
187 196 # allow __getattr__ to raise exceptions other than
188 197 # AttributeError, which then crashes IPython.
189 198 break
190 199 else:
191 200 # If we finish the for loop (no break), we got all members
192 201 found = 1
193 202 ospace = nsname
194 203 if ns == alias_ns:
195 204 isalias = 1
196 205 break # namespace loop
197 206
198 207 # Try to see if it's magic
199 208 if not found:
200 209 if oname.startswith(self.shell.ESC_MAGIC):
201 210 oname = oname[1:]
202 211 obj = getattr(self,'magic_'+oname,None)
203 212 if obj is not None:
204 213 found = 1
205 214 ospace = 'IPython internal'
206 215 ismagic = 1
207 216
208 217 # Last try: special-case some literals like '', [], {}, etc:
209 218 if not found and oname_head in ["''",'""','[]','{}','()']:
210 219 obj = eval(oname_head)
211 220 found = 1
212 221 ospace = 'Interactive'
213 222
214 223 return {'found':found, 'obj':obj, 'namespace':ospace,
215 224 'ismagic':ismagic, 'isalias':isalias}
216 225
217 226 def arg_err(self,func):
218 227 """Print docstring if incorrect arguments were passed"""
219 228 print 'Error in arguments:'
220 229 print OInspect.getdoc(func)
221 230
222 231 def format_latex(self,strng):
223 232 """Format a string for latex inclusion."""
224 233
225 234 # Characters that need to be escaped for latex:
226 235 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
227 236 # Magic command names as headers:
228 237 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
229 238 re.MULTILINE)
230 239 # Magic commands
231 240 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
232 241 re.MULTILINE)
233 242 # Paragraph continue
234 243 par_re = re.compile(r'\\$',re.MULTILINE)
235 244
236 245 # The "\n" symbol
237 246 newline_re = re.compile(r'\\n')
238 247
239 248 # Now build the string for output:
240 249 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
241 250 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
242 251 strng = par_re.sub(r'\\\\',strng)
243 252 strng = escape_re.sub(r'\\\1',strng)
244 253 strng = newline_re.sub(r'\\textbackslash{}n',strng)
245 254 return strng
246 255
247 256 def format_screen(self,strng):
248 257 """Format a string for screen printing.
249 258
250 259 This removes some latex-type format codes."""
251 260 # Paragraph continue
252 261 par_re = re.compile(r'\\$',re.MULTILINE)
253 262 strng = par_re.sub('',strng)
254 263 return strng
255 264
256 265 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
257 266 """Parse options passed to an argument string.
258 267
259 268 The interface is similar to that of getopt(), but it returns back a
260 269 Struct with the options as keys and the stripped argument string still
261 270 as a string.
262 271
263 272 arg_str is quoted as a true sys.argv vector by using shlex.split.
264 273 This allows us to easily expand variables, glob files, quote
265 274 arguments, etc.
266 275
267 276 Options:
268 277 -mode: default 'string'. If given as 'list', the argument string is
269 278 returned as a list (split on whitespace) instead of a string.
270 279
271 280 -list_all: put all option values in lists. Normally only options
272 281 appearing more than once are put in a list."""
273 282
274 283 # inject default options at the beginning of the input line
275 284 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
276 285 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
277 286
278 287 mode = kw.get('mode','string')
279 288 if mode not in ['string','list']:
280 289 raise ValueError,'incorrect mode given: %s' % mode
281 290 # Get options
282 291 list_all = kw.get('list_all',0)
283 292
284 293 # Check if we have more than one argument to warrant extra processing:
285 294 odict = {} # Dictionary with options
286 295 args = arg_str.split()
287 296 if len(args) >= 1:
288 297 # If the list of inputs only has 0 or 1 thing in it, there's no
289 298 # need to look for options
290 299 argv = shlex_split(arg_str)
291 300 # Do regular option processing
292 301 opts,args = getopt(argv,opt_str,*long_opts)
293 302 for o,a in opts:
294 303 if o.startswith('--'):
295 304 o = o[2:]
296 305 else:
297 306 o = o[1:]
298 307 try:
299 308 odict[o].append(a)
300 309 except AttributeError:
301 310 odict[o] = [odict[o],a]
302 311 except KeyError:
303 312 if list_all:
304 313 odict[o] = [a]
305 314 else:
306 315 odict[o] = a
307 316
308 317 # Prepare opts,args for return
309 318 opts = Struct(odict)
310 319 if mode == 'string':
311 320 args = ' '.join(args)
312 321
313 322 return opts,args
314 323
315 324 #......................................................................
316 325 # And now the actual magic functions
317 326
318 327 # Functions for IPython shell work (vars,funcs, config, etc)
319 328 def magic_lsmagic(self, parameter_s = ''):
320 329 """List currently available magic functions."""
321 330 mesc = self.shell.ESC_MAGIC
322 331 print 'Available magic functions:\n'+mesc+\
323 332 (' '+mesc).join(self.lsmagic())
324 333 print '\n' + Magic.auto_status[self.shell.rc.automagic]
325 334 return None
326 335
327 336 def magic_magic(self, parameter_s = ''):
328 337 """Print information about the magic function system."""
329 338
330 339 mode = ''
331 340 try:
332 341 if parameter_s.split()[0] == '-latex':
333 342 mode = 'latex'
334 343 except:
335 344 pass
336 345
337 346 magic_docs = []
338 347 for fname in self.lsmagic():
339 348 mname = 'magic_' + fname
340 349 for space in (Magic,self,self.__class__):
341 350 try:
342 351 fn = space.__dict__[mname]
343 352 except KeyError:
344 353 pass
345 354 else:
346 355 break
347 356 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
348 357 fname,fn.__doc__))
349 358 magic_docs = ''.join(magic_docs)
350 359
351 360 if mode == 'latex':
352 361 print self.format_latex(magic_docs)
353 362 return
354 363 else:
355 364 magic_docs = self.format_screen(magic_docs)
356 365
357 366 outmsg = """
358 367 IPython's 'magic' functions
359 368 ===========================
360 369
361 370 The magic function system provides a series of functions which allow you to
362 371 control the behavior of IPython itself, plus a lot of system-type
363 372 features. All these functions are prefixed with a % character, but parameters
364 373 are given without parentheses or quotes.
365 374
366 375 NOTE: If you have 'automagic' enabled (via the command line option or with the
367 376 %automagic function), you don't need to type in the % explicitly. By default,
368 377 IPython ships with automagic on, so you should only rarely need the % escape.
369 378
370 379 Example: typing '%cd mydir' (without the quotes) changes you working directory
371 380 to 'mydir', if it exists.
372 381
373 382 You can define your own magic functions to extend the system. See the supplied
374 383 ipythonrc and example-magic.py files for details (in your ipython
375 384 configuration directory, typically $HOME/.ipython/).
376 385
377 386 You can also define your own aliased names for magic functions. In your
378 387 ipythonrc file, placing a line like:
379 388
380 389 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
381 390
382 391 will define %pf as a new name for %profile.
383 392
384 393 You can also call magics in code using the ipmagic() function, which IPython
385 394 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
386 395
387 396 For a list of the available magic functions, use %lsmagic. For a description
388 397 of any of them, type %magic_name?, e.g. '%cd?'.
389 398
390 399 Currently the magic system has the following functions:\n"""
391 400
392 401 mesc = self.shell.ESC_MAGIC
393 402 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
394 403 "\n\n%s%s\n\n%s" % (outmsg,
395 404 magic_docs,mesc,mesc,
396 405 (' '+mesc).join(self.lsmagic()),
397 406 Magic.auto_status[self.shell.rc.automagic] ) )
398 407
399 408 page(outmsg,screen_lines=self.shell.rc.screen_length)
400 409
401 410 def magic_automagic(self, parameter_s = ''):
402 411 """Make magic functions callable without having to type the initial %.
403 412
404 413 Toggles on/off (when off, you must call it as %automagic, of
405 414 course). Note that magic functions have lowest priority, so if there's
406 415 a variable whose name collides with that of a magic fn, automagic
407 416 won't work for that function (you get the variable instead). However,
408 417 if you delete the variable (del var), the previously shadowed magic
409 418 function becomes visible to automagic again."""
410 419
411 420 rc = self.shell.rc
412 421 rc.automagic = not rc.automagic
413 422 print '\n' + Magic.auto_status[rc.automagic]
414 423
415 424 def magic_autocall(self, parameter_s = ''):
416 425 """Make functions callable without having to type parentheses.
417 426
418 427 This toggles the autocall command line option on and off."""
419 428
420 429 rc = self.shell.rc
421 430 rc.autocall = not rc.autocall
422 431 print "Automatic calling is:",['OFF','ON'][rc.autocall]
423 432
424 433 def magic_autoindent(self, parameter_s = ''):
425 434 """Toggle autoindent on/off (if available)."""
426 435
427 436 self.shell.set_autoindent()
428 437 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
429 438
430 439 def magic_system_verbose(self, parameter_s = ''):
431 440 """Toggle verbose printing of system calls on/off."""
432 441
433 442 self.shell.rc_set_toggle('system_verbose')
434 443 print "System verbose printing is:",\
435 444 ['OFF','ON'][self.shell.rc.system_verbose]
436 445
437 446 def magic_history(self, parameter_s = ''):
438 447 """Print input history (_i<n> variables), with most recent last.
439 448
440 449 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
441 450 %history [-n] n -> print at most n inputs\\
442 451 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
443 452
444 453 Each input's number <n> is shown, and is accessible as the
445 454 automatically generated variable _i<n>. Multi-line statements are
446 455 printed starting at a new line for easy copy/paste.
447 456
448 457 If option -n is used, input numbers are not printed. This is useful if
449 458 you want to get a printout of many lines which can be directly pasted
450 459 into a text editor.
451 460
452 461 This feature is only available if numbered prompts are in use."""
453 462
454 463 shell = self.shell
455 464 if not shell.outputcache.do_full_cache:
456 465 print 'This feature is only available if numbered prompts are in use.'
457 466 return
458 467 opts,args = self.parse_options(parameter_s,'n',mode='list')
459 468
460 469 input_hist = shell.input_hist
461 470 default_length = 40
462 471 if len(args) == 0:
463 472 final = len(input_hist)
464 473 init = max(1,final-default_length)
465 474 elif len(args) == 1:
466 475 final = len(input_hist)
467 476 init = max(1,final-int(args[0]))
468 477 elif len(args) == 2:
469 478 init,final = map(int,args)
470 479 else:
471 480 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
472 481 print self.magic_hist.__doc__
473 482 return
474 483 width = len(str(final))
475 484 line_sep = ['','\n']
476 485 print_nums = not opts.has_key('n')
477 486 for in_num in range(init,final):
478 487 inline = input_hist[in_num]
479 488 multiline = int(inline.count('\n') > 1)
480 489 if print_nums:
481 490 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
482 491 print inline,
483 492
484 493 def magic_hist(self, parameter_s=''):
485 494 """Alternate name for %history."""
486 495 return self.magic_history(parameter_s)
487 496
488 497 def magic_p(self, parameter_s=''):
489 498 """Just a short alias for Python's 'print'."""
490 499 exec 'print ' + parameter_s in self.shell.user_ns
491 500
492 501 def magic_r(self, parameter_s=''):
493 502 """Repeat previous input.
494 503
495 504 If given an argument, repeats the previous command which starts with
496 505 the same string, otherwise it just repeats the previous input.
497 506
498 507 Shell escaped commands (with ! as first character) are not recognized
499 508 by this system, only pure python code and magic commands.
500 509 """
501 510
502 511 start = parameter_s.strip()
503 512 esc_magic = self.shell.ESC_MAGIC
504 513 # Identify magic commands even if automagic is on (which means
505 514 # the in-memory version is different from that typed by the user).
506 515 if self.shell.rc.automagic:
507 516 start_magic = esc_magic+start
508 517 else:
509 518 start_magic = start
510 519 # Look through the input history in reverse
511 520 for n in range(len(self.shell.input_hist)-2,0,-1):
512 521 input = self.shell.input_hist[n]
513 522 # skip plain 'r' lines so we don't recurse to infinity
514 523 if input != 'ipmagic("r")\n' and \
515 524 (input.startswith(start) or input.startswith(start_magic)):
516 525 #print 'match',`input` # dbg
517 526 print 'Executing:',input,
518 527 self.shell.runlines(input)
519 528 return
520 529 print 'No previous input matching `%s` found.' % start
521 530
522 531 def magic_page(self, parameter_s=''):
523 532 """Pretty print the object and display it through a pager.
524 533
525 534 If no parameter is given, use _ (last output)."""
526 535 # After a function contributed by Olivier Aubert, slightly modified.
527 536
528 537 oname = parameter_s and parameter_s or '_'
529 538 info = self._ofind(oname)
530 539 if info['found']:
531 540 page(pformat(info['obj']))
532 541 else:
533 542 print 'Object `%s` not found' % oname
534 543
535 544 def magic_profile(self, parameter_s=''):
536 545 """Print your currently active IPyhton profile."""
537 546 if self.shell.rc.profile:
538 547 printpl('Current IPython profile: $self.shell.rc.profile.')
539 548 else:
540 549 print 'No profile active.'
541 550
542 551 def _inspect(self,meth,oname,**kw):
543 552 """Generic interface to the inspector system.
544 553
545 554 This function is meant to be called by pdef, pdoc & friends."""
546 555
547 556 oname = oname.strip()
548 557 info = Struct(self._ofind(oname))
549 558 if info.found:
550 559 pmethod = getattr(self.shell.inspector,meth)
551 560 formatter = info.ismagic and self.format_screen or None
552 561 if meth == 'pdoc':
553 562 pmethod(info.obj,oname,formatter)
554 563 elif meth == 'pinfo':
555 564 pmethod(info.obj,oname,formatter,info,**kw)
556 565 else:
557 566 pmethod(info.obj,oname)
558 567 else:
559 568 print 'Object `%s` not found.' % oname
560 569 return 'not found' # so callers can take other action
561 570
562 571 def magic_pdef(self, parameter_s=''):
563 572 """Print the definition header for any callable object.
564 573
565 574 If the object is a class, print the constructor information."""
566 575 self._inspect('pdef',parameter_s)
567 576
568 577 def magic_pdoc(self, parameter_s=''):
569 578 """Print the docstring for an object.
570 579
571 580 If the given object is a class, it will print both the class and the
572 581 constructor docstrings."""
573 582 self._inspect('pdoc',parameter_s)
574 583
575 584 def magic_psource(self, parameter_s=''):
576 585 """Print (or run through pager) the source code for an object."""
577 586 self._inspect('psource',parameter_s)
578 587
579 588 def magic_pfile(self, parameter_s=''):
580 589 """Print (or run through pager) the file where an object is defined.
581 590
582 591 The file opens at the line where the object definition begins. IPython
583 592 will honor the environment variable PAGER if set, and otherwise will
584 593 do its best to print the file in a convenient form.
585 594
586 595 If the given argument is not an object currently defined, IPython will
587 596 try to interpret it as a filename (automatically adding a .py extension
588 597 if needed). You can thus use %pfile as a syntax highlighting code
589 598 viewer."""
590 599
591 600 # first interpret argument as an object name
592 601 out = self._inspect('pfile',parameter_s)
593 602 # if not, try the input as a filename
594 603 if out == 'not found':
595 604 try:
596 605 filename = get_py_filename(parameter_s)
597 606 except IOError,msg:
598 607 print msg
599 608 return
600 609 page(self.shell.inspector.format(file(filename).read()))
601 610
602 611 def magic_pinfo(self, parameter_s=''):
603 612 """Provide detailed information about an object.
604 613
605 614 '%pinfo object' is just a synonym for object? or ?object."""
606 615
607 616 #print 'pinfo par: <%s>' % parameter_s # dbg
608 617
609 618 # detail_level: 0 -> obj? , 1 -> obj??
610 619 detail_level = 0
611 620 # We need to detect if we got called as 'pinfo pinfo foo', which can
612 621 # happen if the user types 'pinfo foo?' at the cmd line.
613 622 pinfo,qmark1,oname,qmark2 = \
614 623 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
615 624 if pinfo or qmark1 or qmark2:
616 625 detail_level = 1
617 626 if "*" in oname:
618 627 self.magic_psearch(oname)
619 628 else:
620 629 self._inspect('pinfo',oname,detail_level=detail_level)
621 630
622 631 def magic_psearch(self, parameter_s=''):
623 632 """Search for object in namespaces by wildcard.
624 633
625 634 %psearch [options] PATTERN [OBJECT TYPE]
626 635
627 636 Note: ? can be used as a synonym for %psearch, at the beginning or at
628 637 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
629 638 rest of the command line must be unchanged (options come first), so
630 639 for example the following forms are equivalent
631 640
632 641 %psearch -i a* function
633 642 -i a* function?
634 643 ?-i a* function
635 644
636 645 Arguments:
637 646
638 647 PATTERN
639 648
640 649 where PATTERN is a string containing * as a wildcard similar to its
641 650 use in a shell. The pattern is matched in all namespaces on the
642 651 search path. By default objects starting with a single _ are not
643 652 matched, many IPython generated objects have a single
644 653 underscore. The default is case insensitive matching. Matching is
645 654 also done on the attributes of objects and not only on the objects
646 655 in a module.
647 656
648 657 [OBJECT TYPE]
649 658
650 659 Is the name of a python type from the types module. The name is
651 660 given in lowercase without the ending type, ex. StringType is
652 661 written string. By adding a type here only objects matching the
653 662 given type are matched. Using all here makes the pattern match all
654 663 types (this is the default).
655 664
656 665 Options:
657 666
658 667 -a: makes the pattern match even objects whose names start with a
659 668 single underscore. These names are normally ommitted from the
660 669 search.
661 670
662 671 -i/-c: make the pattern case insensitive/sensitive. If neither of
663 672 these options is given, the default is read from your ipythonrc
664 673 file. The option name which sets this value is
665 674 'wildcards_case_sensitive'. If this option is not specified in your
666 675 ipythonrc file, IPython's internal default is to do a case sensitive
667 676 search.
668 677
669 678 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
670 679 specifiy can be searched in any of the following namespaces:
671 680 'builtin', 'user', 'user_global','internal', 'alias', where
672 681 'builtin' and 'user' are the search defaults. Note that you should
673 682 not use quotes when specifying namespaces.
674 683
675 684 'Builtin' contains the python module builtin, 'user' contains all
676 685 user data, 'alias' only contain the shell aliases and no python
677 686 objects, 'internal' contains objects used by IPython. The
678 687 'user_global' namespace is only used by embedded IPython instances,
679 688 and it contains module-level globals. You can add namespaces to the
680 689 search with -s or exclude them with -e (these options can be given
681 690 more than once).
682 691
683 692 Examples:
684 693
685 694 %psearch a* -> objects beginning with an a
686 695 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
687 696 %psearch a* function -> all functions beginning with an a
688 697 %psearch re.e* -> objects beginning with an e in module re
689 698 %psearch r*.e* -> objects that start with e in modules starting in r
690 699 %psearch r*.* string -> all strings in modules beginning with r
691 700
692 701 Case sensitve search:
693 702
694 703 %psearch -c a* list all object beginning with lower case a
695 704
696 705 Show objects beginning with a single _:
697 706
698 707 %psearch -a _* list objects beginning with a single underscore"""
699 708
700 709 # default namespaces to be searched
701 710 def_search = ['user','builtin']
702 711
703 712 # Process options/args
704 713 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
705 714 opt = opts.get
706 715 shell = self.shell
707 716 psearch = shell.inspector.psearch
708 717
709 718 # select case options
710 719 if opts.has_key('i'):
711 720 ignore_case = True
712 721 elif opts.has_key('c'):
713 722 ignore_case = False
714 723 else:
715 724 ignore_case = not shell.rc.wildcards_case_sensitive
716 725
717 726 # Build list of namespaces to search from user options
718 727 def_search.extend(opt('s',[]))
719 728 ns_exclude = ns_exclude=opt('e',[])
720 729 ns_search = [nm for nm in def_search if nm not in ns_exclude]
721 730
722 731 # Call the actual search
723 732 try:
724 733 psearch(args,shell.ns_table,ns_search,
725 734 show_all=opt('a'),ignore_case=ignore_case)
726 735 except:
727 736 shell.showtraceback()
728 737
729 738 def magic_who_ls(self, parameter_s=''):
730 739 """Return a sorted list of all interactive variables.
731 740
732 741 If arguments are given, only variables of types matching these
733 742 arguments are returned."""
734 743
735 744 user_ns = self.shell.user_ns
736 745 out = []
737 746 typelist = parameter_s.split()
738 747 for i in self.shell.user_ns.keys():
739 748 if not (i.startswith('_') or i.startswith('_i')) \
740 749 and not (self.shell.internal_ns.has_key(i) or
741 750 self.shell.user_config_ns.has_key(i)):
742 751 if typelist:
743 752 if type(user_ns[i]).__name__ in typelist:
744 753 out.append(i)
745 754 else:
746 755 out.append(i)
747 756 out.sort()
748 757 return out
749 758
750 759 def magic_who(self, parameter_s=''):
751 760 """Print all interactive variables, with some minimal formatting.
752 761
753 762 If any arguments are given, only variables whose type matches one of
754 763 these are printed. For example:
755 764
756 765 %who function str
757 766
758 767 will only list functions and strings, excluding all other types of
759 768 variables. To find the proper type names, simply use type(var) at a
760 769 command line to see how python prints type names. For example:
761 770
762 771 In [1]: type('hello')\\
763 772 Out[1]: <type 'str'>
764 773
765 774 indicates that the type name for strings is 'str'.
766 775
767 776 %who always excludes executed names loaded through your configuration
768 777 file and things which are internal to IPython.
769 778
770 779 This is deliberate, as typically you may load many modules and the
771 780 purpose of %who is to show you only what you've manually defined."""
772 781
773 782 varlist = self.magic_who_ls(parameter_s)
774 783 if not varlist:
775 784 print 'Interactive namespace is empty.'
776 785 return
777 786
778 787 # if we have variables, move on...
779 788
780 789 # stupid flushing problem: when prompts have no separators, stdout is
781 790 # getting lost. I'm starting to think this is a python bug. I'm having
782 791 # to force a flush with a print because even a sys.stdout.flush
783 792 # doesn't seem to do anything!
784 793
785 794 count = 0
786 795 for i in varlist:
787 796 print i+'\t',
788 797 count += 1
789 798 if count > 8:
790 799 count = 0
791 800 print
792 801 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
793 802
794 803 print # well, this does force a flush at the expense of an extra \n
795 804
796 805 def magic_whos(self, parameter_s=''):
797 806 """Like %who, but gives some extra information about each variable.
798 807
799 808 The same type filtering of %who can be applied here.
800 809
801 810 For all variables, the type is printed. Additionally it prints:
802 811
803 812 - For {},[],(): their length.
804 813
805 814 - For Numeric arrays, a summary with shape, number of elements,
806 815 typecode and size in memory.
807 816
808 817 - Everything else: a string representation, snipping their middle if
809 818 too long."""
810 819
811 820 varnames = self.magic_who_ls(parameter_s)
812 821 if not varnames:
813 822 print 'Interactive namespace is empty.'
814 823 return
815 824
816 825 # if we have variables, move on...
817 826
818 827 # for these types, show len() instead of data:
819 828 seq_types = [types.DictType,types.ListType,types.TupleType]
820 829
821 830 # for Numeric arrays, display summary info
822 831 try:
823 832 import Numeric
824 833 except ImportError:
825 834 array_type = None
826 835 else:
827 836 array_type = Numeric.ArrayType.__name__
828 837
829 838 # Find all variable names and types so we can figure out column sizes
830 839 get_vars = lambda i: self.shell.user_ns[i]
831 840 type_name = lambda v: type(v).__name__
832 841 varlist = map(get_vars,varnames)
833 842
834 843 typelist = []
835 844 for vv in varlist:
836 845 tt = type_name(vv)
837 846 if tt=='instance':
838 847 typelist.append(str(vv.__class__))
839 848 else:
840 849 typelist.append(tt)
841 850
842 851 # column labels and # of spaces as separator
843 852 varlabel = 'Variable'
844 853 typelabel = 'Type'
845 854 datalabel = 'Data/Info'
846 855 colsep = 3
847 856 # variable format strings
848 857 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
849 858 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
850 859 aformat = "%s: %s elems, type `%s`, %s bytes"
851 860 # find the size of the columns to format the output nicely
852 861 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
853 862 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
854 863 # table header
855 864 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
856 865 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
857 866 # and the table itself
858 867 kb = 1024
859 868 Mb = 1048576 # kb**2
860 869 for vname,var,vtype in zip(varnames,varlist,typelist):
861 870 print itpl(vformat),
862 871 if vtype in seq_types:
863 872 print len(var)
864 873 elif vtype==array_type:
865 874 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
866 875 vsize = Numeric.size(var)
867 876 vbytes = vsize*var.itemsize()
868 877 if vbytes < 100000:
869 878 print aformat % (vshape,vsize,var.typecode(),vbytes)
870 879 else:
871 880 print aformat % (vshape,vsize,var.typecode(),vbytes),
872 881 if vbytes < Mb:
873 882 print '(%s kb)' % (vbytes/kb,)
874 883 else:
875 884 print '(%s Mb)' % (vbytes/Mb,)
876 885 else:
877 886 vstr = str(var).replace('\n','\\n')
878 887 if len(vstr) < 50:
879 888 print vstr
880 889 else:
881 890 printpl(vfmt_short)
882 891
883 892 def magic_reset(self, parameter_s=''):
884 893 """Resets the namespace by removing all names defined by the user.
885 894
886 895 Input/Output history are left around in case you need them."""
887 896
888 897 ans = raw_input(
889 898 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
890 899 if not ans.lower() == 'y':
891 900 print 'Nothing done.'
892 901 return
893 902 user_ns = self.shell.user_ns
894 903 for i in self.magic_who_ls():
895 904 del(user_ns[i])
896 905
897 906 def magic_config(self,parameter_s=''):
898 907 """Show IPython's internal configuration."""
899 908
900 909 page('Current configuration structure:\n'+
901 910 pformat(self.shell.rc.dict()))
902 911
903 912 def magic_logstart(self,parameter_s=''):
904 913 """Start logging anywhere in a session.
905 914
906 915 %logstart [-o|-t] [log_name [log_mode]]
907 916
908 917 If no name is given, it defaults to a file named 'ipython_log.py' in your
909 918 current directory, in 'rotate' mode (see below).
910 919
911 920 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
912 921 history up to that point and then continues logging.
913 922
914 923 %logstart takes a second optional parameter: logging mode. This can be one
915 924 of (note that the modes are given unquoted):\\
916 925 append: well, that says it.\\
917 926 backup: rename (if exists) to name~ and start name.\\
918 927 global: single logfile in your home dir, appended to.\\
919 928 over : overwrite existing log.\\
920 929 rotate: create rotating logs name.1~, name.2~, etc.
921 930
922 931 Options:
923 932
924 933 -o: log also IPython's output. In this mode, all commands which
925 934 generate an Out[NN] prompt are recorded to the logfile, right after
926 935 their corresponding input line. The output lines are always
927 936 prepended with a '#[Out]# ' marker, so that the log remains valid
928 937 Python code.
929 938
930 939 Since this marker is always the same, filtering only the output from
931 940 a log is very easy, using for example a simple awk call:
932 941
933 942 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
934 943
935 944 -t: put timestamps before each input line logged (these are put in
936 945 comments)."""
937 946
938 947 opts,par = self.parse_options(parameter_s,'ot')
939 948 log_output = 'o' in opts
940 949 timestamp = 't' in opts
941 950
942 951 rc = self.shell.rc
943 952 logger = self.shell.logger
944 953
945 954 # if no args are given, the defaults set in the logger constructor by
946 955 # ipytohn remain valid
947 956 if par:
948 957 try:
949 958 logfname,logmode = par.split()
950 959 except:
951 960 logfname = par
952 961 logmode = 'backup'
953 962 else:
954 963 logfname = logger.logfname
955 964 logmode = logger.logmode
956 965 # put logfname into rc struct as if it had been called on the command
957 966 # line, so it ends up saved in the log header Save it in case we need
958 967 # to restore it...
959 968 old_logfile = rc.opts.get('logfile','')
960 969 if logfname:
961 970 logfname = os.path.expanduser(logfname)
962 971 rc.opts.logfile = logfname
963 972 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
964 973 try:
965 974 started = logger.logstart(logfname,loghead,logmode,
966 975 log_output,timestamp)
967 976 except:
968 977 rc.opts.logfile = old_logfile
969 978 warn("Couldn't start log: %s" % sys.exc_info()[1])
970 979 else:
971 980 # log input history up to this point, optionally interleaving
972 981 # output if requested
973 982
974 983 if timestamp:
975 984 # disable timestamping for the previous history, since we've
976 985 # lost those already (no time machine here).
977 986 logger.timestamp = False
978 987 if log_output:
979 988 log_write = logger.log_write
980 989 input_hist = self.shell.input_hist
981 990 output_hist = self.shell.output_hist
982 991 for n in range(1,len(input_hist)-1):
983 992 log_write(input_hist[n].rstrip())
984 993 if n in output_hist:
985 994 log_write(repr(output_hist[n]),'output')
986 995 else:
987 996 logger.log_write(self.shell.input_hist[1:])
988 997 if timestamp:
989 998 # re-enable timestamping
990 999 logger.timestamp = True
991 1000
992 1001 print ('Activating auto-logging. '
993 1002 'Current session state plus future input saved.')
994 1003 logger.logstate()
995 1004
996 1005 def magic_logoff(self,parameter_s=''):
997 1006 """Temporarily stop logging.
998 1007
999 1008 You must have previously started logging."""
1000 1009 self.shell.logger.switch_log(0)
1001 1010
1002 1011 def magic_logon(self,parameter_s=''):
1003 1012 """Restart logging.
1004 1013
1005 1014 This function is for restarting logging which you've temporarily
1006 1015 stopped with %logoff. For starting logging for the first time, you
1007 1016 must use the %logstart function, which allows you to specify an
1008 1017 optional log filename."""
1009 1018
1010 1019 self.shell.logger.switch_log(1)
1011 1020
1012 1021 def magic_logstate(self,parameter_s=''):
1013 1022 """Print the status of the logging system."""
1014 1023
1015 1024 self.shell.logger.logstate()
1016 1025
1017 1026 def magic_pdb(self, parameter_s=''):
1018 1027 """Control the calling of the pdb interactive debugger.
1019 1028
1020 1029 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1021 1030 argument it works as a toggle.
1022 1031
1023 1032 When an exception is triggered, IPython can optionally call the
1024 1033 interactive pdb debugger after the traceback printout. %pdb toggles
1025 1034 this feature on and off."""
1026 1035
1027 1036 par = parameter_s.strip().lower()
1028 1037
1029 1038 if par:
1030 1039 try:
1031 1040 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1032 1041 except KeyError:
1033 1042 print ('Incorrect argument. Use on/1, off/0, '
1034 1043 'or nothing for a toggle.')
1035 1044 return
1036 1045 else:
1037 1046 # toggle
1038 1047 new_pdb = not self.shell.InteractiveTB.call_pdb
1039 1048
1040 1049 # set on the shell
1041 1050 self.shell.call_pdb = new_pdb
1042 1051 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1043 1052
1044 1053 def magic_prun(self, parameter_s ='',user_mode=1,
1045 1054 opts=None,arg_lst=None,prog_ns=None):
1046 1055
1047 1056 """Run a statement through the python code profiler.
1048 1057
1049 1058 Usage:\\
1050 1059 %prun [options] statement
1051 1060
1052 1061 The given statement (which doesn't require quote marks) is run via the
1053 1062 python profiler in a manner similar to the profile.run() function.
1054 1063 Namespaces are internally managed to work correctly; profile.run
1055 1064 cannot be used in IPython because it makes certain assumptions about
1056 1065 namespaces which do not hold under IPython.
1057 1066
1058 1067 Options:
1059 1068
1060 1069 -l <limit>: you can place restrictions on what or how much of the
1061 1070 profile gets printed. The limit value can be:
1062 1071
1063 1072 * A string: only information for function names containing this string
1064 1073 is printed.
1065 1074
1066 1075 * An integer: only these many lines are printed.
1067 1076
1068 1077 * A float (between 0 and 1): this fraction of the report is printed
1069 1078 (for example, use a limit of 0.4 to see the topmost 40% only).
1070 1079
1071 1080 You can combine several limits with repeated use of the option. For
1072 1081 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1073 1082 information about class constructors.
1074 1083
1075 1084 -r: return the pstats.Stats object generated by the profiling. This
1076 1085 object has all the information about the profile in it, and you can
1077 1086 later use it for further analysis or in other functions.
1078 1087
1079 1088 Since magic functions have a particular form of calling which prevents
1080 1089 you from writing something like:\\
1081 1090 In [1]: p = %prun -r print 4 # invalid!\\
1082 1091 you must instead use IPython's automatic variables to assign this:\\
1083 1092 In [1]: %prun -r print 4 \\
1084 1093 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1085 1094 In [2]: stats = _
1086 1095
1087 1096 If you really need to assign this value via an explicit function call,
1088 1097 you can always tap directly into the true name of the magic function
1089 1098 by using the ipmagic function (which IPython automatically adds to the
1090 1099 builtins):\\
1091 1100 In [3]: stats = ipmagic('prun','-r print 4')
1092 1101
1093 1102 You can type ipmagic? for more details on ipmagic.
1094 1103
1095 1104 -s <key>: sort profile by given key. You can provide more than one key
1096 1105 by using the option several times: '-s key1 -s key2 -s key3...'. The
1097 1106 default sorting key is 'time'.
1098 1107
1099 1108 The following is copied verbatim from the profile documentation
1100 1109 referenced below:
1101 1110
1102 1111 When more than one key is provided, additional keys are used as
1103 1112 secondary criteria when the there is equality in all keys selected
1104 1113 before them.
1105 1114
1106 1115 Abbreviations can be used for any key names, as long as the
1107 1116 abbreviation is unambiguous. The following are the keys currently
1108 1117 defined:
1109 1118
1110 1119 Valid Arg Meaning\\
1111 1120 "calls" call count\\
1112 1121 "cumulative" cumulative time\\
1113 1122 "file" file name\\
1114 1123 "module" file name\\
1115 1124 "pcalls" primitive call count\\
1116 1125 "line" line number\\
1117 1126 "name" function name\\
1118 1127 "nfl" name/file/line\\
1119 1128 "stdname" standard name\\
1120 1129 "time" internal time
1121 1130
1122 1131 Note that all sorts on statistics are in descending order (placing
1123 1132 most time consuming items first), where as name, file, and line number
1124 1133 searches are in ascending order (i.e., alphabetical). The subtle
1125 1134 distinction between "nfl" and "stdname" is that the standard name is a
1126 1135 sort of the name as printed, which means that the embedded line
1127 1136 numbers get compared in an odd way. For example, lines 3, 20, and 40
1128 1137 would (if the file names were the same) appear in the string order
1129 1138 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1130 1139 line numbers. In fact, sort_stats("nfl") is the same as
1131 1140 sort_stats("name", "file", "line").
1132 1141
1133 1142 -T <filename>: save profile results as shown on screen to a text
1134 1143 file. The profile is still shown on screen.
1135 1144
1136 1145 -D <filename>: save (via dump_stats) profile statistics to given
1137 1146 filename. This data is in a format understod by the pstats module, and
1138 1147 is generated by a call to the dump_stats() method of profile
1139 1148 objects. The profile is still shown on screen.
1140 1149
1141 1150 If you want to run complete programs under the profiler's control, use
1142 1151 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1143 1152 contains profiler specific options as described here.
1144 1153
1145 1154 You can read the complete documentation for the profile module with:\\
1146 1155 In [1]: import profile; profile.help() """
1147 1156
1148 1157 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1149 1158 # protect user quote marks
1150 1159 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1151 1160
1152 1161 if user_mode: # regular user call
1153 1162 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1154 1163 list_all=1)
1155 1164 namespace = self.shell.user_ns
1156 1165 else: # called to run a program by %run -p
1157 1166 try:
1158 1167 filename = get_py_filename(arg_lst[0])
1159 1168 except IOError,msg:
1160 1169 error(msg)
1161 1170 return
1162 1171
1163 1172 arg_str = 'execfile(filename,prog_ns)'
1164 1173 namespace = locals()
1165 1174
1166 1175 opts.merge(opts_def)
1167 1176
1168 1177 prof = profile.Profile()
1169 1178 try:
1170 1179 prof = prof.runctx(arg_str,namespace,namespace)
1171 1180 sys_exit = ''
1172 1181 except SystemExit:
1173 1182 sys_exit = """*** SystemExit exception caught in code being profiled."""
1174 1183
1175 1184 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1176 1185
1177 1186 lims = opts.l
1178 1187 if lims:
1179 1188 lims = [] # rebuild lims with ints/floats/strings
1180 1189 for lim in opts.l:
1181 1190 try:
1182 1191 lims.append(int(lim))
1183 1192 except ValueError:
1184 1193 try:
1185 1194 lims.append(float(lim))
1186 1195 except ValueError:
1187 1196 lims.append(lim)
1188 1197
1189 1198 # trap output
1190 1199 sys_stdout = sys.stdout
1191 1200 stdout_trap = StringIO()
1192 1201 try:
1193 1202 sys.stdout = stdout_trap
1194 1203 stats.print_stats(*lims)
1195 1204 finally:
1196 1205 sys.stdout = sys_stdout
1197 1206 output = stdout_trap.getvalue()
1198 1207 output = output.rstrip()
1199 1208
1200 1209 page(output,screen_lines=self.shell.rc.screen_length)
1201 1210 print sys_exit,
1202 1211
1203 1212 dump_file = opts.D[0]
1204 1213 text_file = opts.T[0]
1205 1214 if dump_file:
1206 1215 prof.dump_stats(dump_file)
1207 1216 print '\n*** Profile stats marshalled to file',\
1208 1217 `dump_file`+'.',sys_exit
1209 1218 if text_file:
1210 1219 file(text_file,'w').write(output)
1211 1220 print '\n*** Profile printout saved to text file',\
1212 1221 `text_file`+'.',sys_exit
1213 1222
1214 1223 if opts.has_key('r'):
1215 1224 return stats
1216 1225 else:
1217 1226 return None
1218 1227
1219 1228 def magic_run(self, parameter_s ='',runner=None):
1220 1229 """Run the named file inside IPython as a program.
1221 1230
1222 1231 Usage:\\
1223 1232 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1224 1233
1225 1234 Parameters after the filename are passed as command-line arguments to
1226 1235 the program (put in sys.argv). Then, control returns to IPython's
1227 1236 prompt.
1228 1237
1229 1238 This is similar to running at a system prompt:\\
1230 1239 $ python file args\\
1231 1240 but with the advantage of giving you IPython's tracebacks, and of
1232 1241 loading all variables into your interactive namespace for further use
1233 1242 (unless -p is used, see below).
1234 1243
1235 1244 The file is executed in a namespace initially consisting only of
1236 1245 __name__=='__main__' and sys.argv constructed as indicated. It thus
1237 1246 sees its environment as if it were being run as a stand-alone
1238 1247 program. But after execution, the IPython interactive namespace gets
1239 1248 updated with all variables defined in the program (except for __name__
1240 1249 and sys.argv). This allows for very convenient loading of code for
1241 1250 interactive work, while giving each program a 'clean sheet' to run in.
1242 1251
1243 1252 Options:
1244 1253
1245 1254 -n: __name__ is NOT set to '__main__', but to the running file's name
1246 1255 without extension (as python does under import). This allows running
1247 1256 scripts and reloading the definitions in them without calling code
1248 1257 protected by an ' if __name__ == "__main__" ' clause.
1249 1258
1250 1259 -i: run the file in IPython's namespace instead of an empty one. This
1251 1260 is useful if you are experimenting with code written in a text editor
1252 1261 which depends on variables defined interactively.
1253 1262
1254 1263 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1255 1264 being run. This is particularly useful if IPython is being used to
1256 1265 run unittests, which always exit with a sys.exit() call. In such
1257 1266 cases you are interested in the output of the test results, not in
1258 1267 seeing a traceback of the unittest module.
1259 1268
1260 1269 -t: print timing information at the end of the run. IPython will give
1261 1270 you an estimated CPU time consumption for your script, which under
1262 1271 Unix uses the resource module to avoid the wraparound problems of
1263 1272 time.clock(). Under Unix, an estimate of time spent on system tasks
1264 1273 is also given (for Windows platforms this is reported as 0.0).
1265 1274
1266 1275 If -t is given, an additional -N<N> option can be given, where <N>
1267 1276 must be an integer indicating how many times you want the script to
1268 1277 run. The final timing report will include total and per run results.
1269 1278
1270 1279 For example (testing the script uniq_stable.py):
1271 1280
1272 1281 In [1]: run -t uniq_stable
1273 1282
1274 1283 IPython CPU timings (estimated):\\
1275 1284 User : 0.19597 s.\\
1276 1285 System: 0.0 s.\\
1277 1286
1278 1287 In [2]: run -t -N5 uniq_stable
1279 1288
1280 1289 IPython CPU timings (estimated):\\
1281 1290 Total runs performed: 5\\
1282 1291 Times : Total Per run\\
1283 1292 User : 0.910862 s, 0.1821724 s.\\
1284 1293 System: 0.0 s, 0.0 s.
1285 1294
1286 1295 -d: run your program under the control of pdb, the Python debugger.
1287 1296 This allows you to execute your program step by step, watch variables,
1288 1297 etc. Internally, what IPython does is similar to calling:
1289 1298
1290 1299 pdb.run('execfile("YOURFILENAME")')
1291 1300
1292 1301 with a breakpoint set on line 1 of your file. You can change the line
1293 1302 number for this automatic breakpoint to be <N> by using the -bN option
1294 1303 (where N must be an integer). For example:
1295 1304
1296 1305 %run -d -b40 myscript
1297 1306
1298 1307 will set the first breakpoint at line 40 in myscript.py. Note that
1299 1308 the first breakpoint must be set on a line which actually does
1300 1309 something (not a comment or docstring) for it to stop execution.
1301 1310
1302 1311 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1303 1312 first enter 'c' (without qoutes) to start execution up to the first
1304 1313 breakpoint.
1305 1314
1306 1315 Entering 'help' gives information about the use of the debugger. You
1307 1316 can easily see pdb's full documentation with "import pdb;pdb.help()"
1308 1317 at a prompt.
1309 1318
1310 1319 -p: run program under the control of the Python profiler module (which
1311 1320 prints a detailed report of execution times, function calls, etc).
1312 1321
1313 1322 You can pass other options after -p which affect the behavior of the
1314 1323 profiler itself. See the docs for %prun for details.
1315 1324
1316 1325 In this mode, the program's variables do NOT propagate back to the
1317 1326 IPython interactive namespace (because they remain in the namespace
1318 1327 where the profiler executes them).
1319 1328
1320 1329 Internally this triggers a call to %prun, see its documentation for
1321 1330 details on the options available specifically for profiling."""
1322 1331
1323 1332 # get arguments and set sys.argv for program to be run.
1324 1333 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1325 1334 mode='list',list_all=1)
1326 1335
1327 1336 try:
1328 1337 filename = get_py_filename(arg_lst[0])
1329 1338 except IndexError:
1330 1339 warn('you must provide at least a filename.')
1331 1340 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1332 1341 return
1333 1342 except IOError,msg:
1334 1343 error(msg)
1335 1344 return
1336 1345
1337 1346 # Control the response to exit() calls made by the script being run
1338 1347 exit_ignore = opts.has_key('e')
1339 1348
1340 1349 # Make sure that the running script gets a proper sys.argv as if it
1341 1350 # were run from a system shell.
1342 1351 save_argv = sys.argv # save it for later restoring
1343 1352 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1344 1353
1345 1354 if opts.has_key('i'):
1346 1355 prog_ns = self.shell.user_ns
1347 1356 __name__save = self.shell.user_ns['__name__']
1348 1357 prog_ns['__name__'] = '__main__'
1349 1358 else:
1350 1359 if opts.has_key('n'):
1351 1360 name = os.path.splitext(os.path.basename(filename))[0]
1352 1361 else:
1353 1362 name = '__main__'
1354 1363 prog_ns = {'__name__':name}
1355 1364
1356 1365 # pickle fix. See iplib for an explanation. But we need to make sure
1357 1366 # that, if we overwrite __main__, we replace it at the end
1358 1367 if prog_ns['__name__'] == '__main__':
1359 1368 restore_main = sys.modules['__main__']
1360 1369 else:
1361 1370 restore_main = False
1362 1371
1363 1372 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1364 1373
1365 1374 stats = None
1366 1375 try:
1367 1376 if opts.has_key('p'):
1368 1377 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1369 1378 else:
1370 1379 if opts.has_key('d'):
1371 1380 deb = Debugger.Pdb(self.shell.rc.colors)
1372 1381 # reset Breakpoint state, which is moronically kept
1373 1382 # in a class
1374 1383 bdb.Breakpoint.next = 1
1375 1384 bdb.Breakpoint.bplist = {}
1376 1385 bdb.Breakpoint.bpbynumber = [None]
1377 1386 # Set an initial breakpoint to stop execution
1378 1387 maxtries = 10
1379 1388 bp = int(opts.get('b',[1])[0])
1380 1389 checkline = deb.checkline(filename,bp)
1381 1390 if not checkline:
1382 1391 for bp in range(bp+1,bp+maxtries+1):
1383 1392 if deb.checkline(filename,bp):
1384 1393 break
1385 1394 else:
1386 1395 msg = ("\nI failed to find a valid line to set "
1387 1396 "a breakpoint\n"
1388 1397 "after trying up to line: %s.\n"
1389 1398 "Please set a valid breakpoint manually "
1390 1399 "with the -b option." % bp)
1391 1400 error(msg)
1392 1401 return
1393 1402 # if we find a good linenumber, set the breakpoint
1394 1403 deb.do_break('%s:%s' % (filename,bp))
1395 1404 # Start file run
1396 1405 print "NOTE: Enter 'c' at the",
1397 1406 print "ipdb> prompt to start your script."
1398 1407 try:
1399 1408 deb.run('execfile("%s")' % filename,prog_ns)
1400 1409 except:
1401 1410 etype, value, tb = sys.exc_info()
1402 1411 # Skip three frames in the traceback: the %run one,
1403 1412 # one inside bdb.py, and the command-line typed by the
1404 1413 # user (run by exec in pdb itself).
1405 1414 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1406 1415 else:
1407 1416 if runner is None:
1408 1417 runner = self.shell.safe_execfile
1409 1418 if opts.has_key('t'):
1410 1419 try:
1411 1420 nruns = int(opts['N'][0])
1412 1421 if nruns < 1:
1413 1422 error('Number of runs must be >=1')
1414 1423 return
1415 1424 except (KeyError):
1416 1425 nruns = 1
1417 1426 if nruns == 1:
1418 1427 t0 = clock2()
1419 1428 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1420 1429 t1 = clock2()
1421 1430 t_usr = t1[0]-t0[0]
1422 1431 t_sys = t1[1]-t1[1]
1423 1432 print "\nIPython CPU timings (estimated):"
1424 1433 print " User : %10s s." % t_usr
1425 1434 print " System: %10s s." % t_sys
1426 1435 else:
1427 1436 runs = range(nruns)
1428 1437 t0 = clock2()
1429 1438 for nr in runs:
1430 1439 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1431 1440 t1 = clock2()
1432 1441 t_usr = t1[0]-t0[0]
1433 1442 t_sys = t1[1]-t1[1]
1434 1443 print "\nIPython CPU timings (estimated):"
1435 1444 print "Total runs performed:",nruns
1436 1445 print " Times : %10s %10s" % ('Total','Per run')
1437 1446 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1438 1447 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1439 1448
1440 1449 else:
1441 1450 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1442 1451 if opts.has_key('i'):
1443 1452 self.shell.user_ns['__name__'] = __name__save
1444 1453 else:
1445 1454 # update IPython interactive namespace
1446 1455 del prog_ns['__name__']
1447 1456 self.shell.user_ns.update(prog_ns)
1448 1457 finally:
1449 1458 sys.argv = save_argv
1450 1459 if restore_main:
1451 1460 sys.modules['__main__'] = restore_main
1452 1461 return stats
1453 1462
1454 1463 def magic_runlog(self, parameter_s =''):
1455 1464 """Run files as logs.
1456 1465
1457 1466 Usage:\\
1458 1467 %runlog file1 file2 ...
1459 1468
1460 1469 Run the named files (treating them as log files) in sequence inside
1461 1470 the interpreter, and return to the prompt. This is much slower than
1462 1471 %run because each line is executed in a try/except block, but it
1463 1472 allows running files with syntax errors in them.
1464 1473
1465 1474 Normally IPython will guess when a file is one of its own logfiles, so
1466 1475 you can typically use %run even for logs. This shorthand allows you to
1467 1476 force any file to be treated as a log file."""
1468 1477
1469 1478 for f in parameter_s.split():
1470 1479 self.shell.safe_execfile(f,self.shell.user_ns,
1471 1480 self.shell.user_ns,islog=1)
1472 1481
1473 1482 def magic_time(self,parameter_s = ''):
1474 1483 """Time execution of a Python statement or expression.
1475 1484
1476 1485 The CPU and wall clock times are printed, and the value of the
1477 1486 expression (if any) is returned. Note that under Win32, system time
1478 1487 is always reported as 0, since it can not be measured.
1479 1488
1480 1489 This function provides very basic timing functionality. In Python
1481 1490 2.3, the timeit module offers more control and sophistication, but for
1482 1491 now IPython supports Python 2.2, so we can not rely on timeit being
1483 1492 present.
1484 1493
1485 1494 Some examples:
1486 1495
1487 1496 In [1]: time 2**128
1488 1497 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1489 1498 Wall time: 0.00
1490 1499 Out[1]: 340282366920938463463374607431768211456L
1491 1500
1492 1501 In [2]: n = 1000000
1493 1502
1494 1503 In [3]: time sum(range(n))
1495 1504 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1496 1505 Wall time: 1.37
1497 1506 Out[3]: 499999500000L
1498 1507
1499 1508 In [4]: time print 'hello world'
1500 1509 hello world
1501 1510 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1502 1511 Wall time: 0.00
1503 1512 """
1504 1513
1505 1514 # fail immediately if the given expression can't be compiled
1506 1515 try:
1507 1516 mode = 'eval'
1508 1517 code = compile(parameter_s,'<timed eval>',mode)
1509 1518 except SyntaxError:
1510 1519 mode = 'exec'
1511 1520 code = compile(parameter_s,'<timed exec>',mode)
1512 1521 # skew measurement as little as possible
1513 1522 glob = self.shell.user_ns
1514 1523 clk = clock2
1515 1524 wtime = time.time
1516 1525 # time execution
1517 1526 wall_st = wtime()
1518 1527 if mode=='eval':
1519 1528 st = clk()
1520 1529 out = eval(code,glob)
1521 1530 end = clk()
1522 1531 else:
1523 1532 st = clk()
1524 1533 exec code in glob
1525 1534 end = clk()
1526 1535 out = None
1527 1536 wall_end = wtime()
1528 1537 # Compute actual times and report
1529 1538 wall_time = wall_end-wall_st
1530 1539 cpu_user = end[0]-st[0]
1531 1540 cpu_sys = end[1]-st[1]
1532 1541 cpu_tot = cpu_user+cpu_sys
1533 1542 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1534 1543 (cpu_user,cpu_sys,cpu_tot)
1535 1544 print "Wall time: %.2f" % wall_time
1536 1545 return out
1537 1546
1538 1547 def magic_macro(self,parameter_s = ''):
1539 1548 """Define a set of input lines as a macro for future re-execution.
1540 1549
1541 1550 Usage:\\
1542 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1551 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1543 1552
1544 1553 This will define a global variable called `name` which is a string
1545 1554 made of joining the slices and lines you specify (n1,n2,... numbers
1546 1555 above) from your input history into a single string. This variable
1547 1556 acts like an automatic function which re-executes those lines as if
1548 1557 you had typed them. You just type 'name' at the prompt and the code
1549 1558 executes.
1550 1559
1551 Note that the slices use the standard Python slicing notation (5:8
1552 means include lines numbered 5,6,7).
1560 The notation for indicating number ranges is: n1-n2 means 'use line
1561 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1562 using the lines numbered 5,6 and 7.
1563
1564 Note: as a 'hidden' feature, you can also use traditional python slice
1565 notation, where N:M means numbers N through M-1.
1553 1566
1554 1567 For example, if your history contains (%hist prints it):
1555 1568
1556 1569 44: x=1\\
1557 1570 45: y=3\\
1558 1571 46: z=x+y\\
1559 1572 47: print x\\
1560 1573 48: a=5\\
1561 1574 49: print 'x',x,'y',y\\
1562 1575
1563 1576 you can create a macro with lines 44 through 47 (included) and line 49
1564 1577 called my_macro with:
1565 1578
1566 In [51]: %macro my_macro 44:48 49
1579 In [51]: %macro my_macro 44-47 49
1567 1580
1568 1581 Now, typing `my_macro` (without quotes) will re-execute all this code
1569 1582 in one pass.
1570 1583
1571 1584 You don't need to give the line-numbers in order, and any given line
1572 1585 number can appear multiple times. You can assemble macros with any
1573 1586 lines from your input history in any order.
1574 1587
1575 1588 The macro is a simple object which holds its value in an attribute,
1576 1589 but IPython's display system checks for macros and executes them as
1577 1590 code instead of printing them when you type their name.
1578 1591
1579 1592 You can view a macro's contents by explicitly printing it with:
1580 1593
1581 1594 'print macro_name'.
1582 1595
1583 1596 For one-off cases which DON'T contain magic function calls in them you
1584 1597 can obtain similar results by explicitly executing slices from your
1585 1598 input history with:
1586 1599
1587 1600 In [60]: exec In[44:48]+In[49]"""
1588 1601
1589 1602 args = parameter_s.split()
1590 1603 name,ranges = args[0], args[1:]
1591 1604 #print 'rng',ranges # dbg
1592 1605 lines = self.extract_input_slices(ranges)
1593 1606 macro = Macro(lines)
1594 1607 self.shell.user_ns.update({name:macro})
1595 1608 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1596 1609 print 'Macro contents:'
1597 1610 print macro,
1598 1611
1599 1612 def magic_save(self,parameter_s = ''):
1600 1613 """Save a set of lines to a given filename.
1601 1614
1602 1615 Usage:\\
1603 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1616 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1604 1617
1605 1618 This function uses the same syntax as %macro for line extraction, but
1606 1619 instead of creating a macro it saves the resulting string to the
1607 1620 filename you specify.
1608 1621
1609 1622 It adds a '.py' extension to the file if you don't do so yourself, and
1610 1623 it asks for confirmation before overwriting existing files."""
1611 1624
1612 1625 args = parameter_s.split()
1613 1626 fname,ranges = args[0], args[1:]
1614 1627 if not fname.endswith('.py'):
1615 1628 fname += '.py'
1616 1629 if os.path.isfile(fname):
1617 1630 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1618 1631 if ans.lower() not in ['y','yes']:
1619 1632 print 'Operation cancelled.'
1620 1633 return
1621 1634 cmds = ''.join(self.extract_input_slices(ranges))
1622 1635 f = file(fname,'w')
1623 1636 f.write(cmds)
1624 1637 f.close()
1625 1638 print 'The following commands were written to file `%s`:' % fname
1626 1639 print cmds
1627 1640
1628 1641 def magic_ed(self,parameter_s = ''):
1629 1642 """Alias to %edit."""
1630 1643 return self.magic_edit(parameter_s)
1631 1644
1632 1645 def magic_edit(self,parameter_s = '',last_call=['','']):
1633 1646 """Bring up an editor and execute the resulting code.
1634 1647
1635 1648 Usage:
1636 1649 %edit [options] [args]
1637 1650
1638 1651 %edit runs IPython's editor hook. The default version of this hook is
1639 1652 set to call the __IPYTHON__.rc.editor command. This is read from your
1640 1653 environment variable $EDITOR. If this isn't found, it will default to
1641 1654 vi under Linux/Unix and to notepad under Windows. See the end of this
1642 1655 docstring for how to change the editor hook.
1643 1656
1644 1657 You can also set the value of this editor via the command line option
1645 1658 '-editor' or in your ipythonrc file. This is useful if you wish to use
1646 1659 specifically for IPython an editor different from your typical default
1647 1660 (and for Windows users who typically don't set environment variables).
1648 1661
1649 1662 This command allows you to conveniently edit multi-line code right in
1650 1663 your IPython session.
1651 1664
1652 1665 If called without arguments, %edit opens up an empty editor with a
1653 1666 temporary file and will execute the contents of this file when you
1654 1667 close it (don't forget to save it!).
1655 1668
1656 1669 Options:
1657 1670
1658 1671 -p: this will call the editor with the same data as the previous time
1659 1672 it was used, regardless of how long ago (in your current session) it
1660 1673 was.
1661 1674
1662 1675 -x: do not execute the edited code immediately upon exit. This is
1663 1676 mainly useful if you are editing programs which need to be called with
1664 1677 command line arguments, which you can then do using %run.
1665 1678
1666 1679 Arguments:
1667 1680
1668 1681 If arguments are given, the following possibilites exist:
1669 1682
1670 1683 - The arguments are numbers or pairs of colon-separated numbers (like
1671 1684 1 4:8 9). These are interpreted as lines of previous input to be
1672 1685 loaded into the editor. The syntax is the same of the %macro command.
1673 1686
1674 1687 - If the argument doesn't start with a number, it is evaluated as a
1675 1688 variable and its contents loaded into the editor. You can thus edit
1676 1689 any string which contains python code (including the result of
1677 1690 previous edits).
1678 1691
1679 1692 - If the argument is the name of an object (other than a string),
1680 1693 IPython will try to locate the file where it was defined and open the
1681 1694 editor at the point where it is defined. You can use `%edit function`
1682 1695 to load an editor exactly at the point where 'function' is defined,
1683 1696 edit it and have the file be executed automatically.
1684 1697
1685 1698 Note: opening at an exact line is only supported under Unix, and some
1686 1699 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1687 1700 '+NUMBER' parameter necessary for this feature. Good editors like
1688 1701 (X)Emacs, vi, jed, pico and joe all do.
1689 1702
1690 1703 - If the argument is not found as a variable, IPython will look for a
1691 1704 file with that name (adding .py if necessary) and load it into the
1692 1705 editor. It will execute its contents with execfile() when you exit,
1693 1706 loading any code in the file into your interactive namespace.
1694 1707
1695 1708 After executing your code, %edit will return as output the code you
1696 1709 typed in the editor (except when it was an existing file). This way
1697 1710 you can reload the code in further invocations of %edit as a variable,
1698 1711 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1699 1712 the output.
1700 1713
1701 1714 Note that %edit is also available through the alias %ed.
1702 1715
1703 1716 This is an example of creating a simple function inside the editor and
1704 1717 then modifying it. First, start up the editor:
1705 1718
1706 1719 In [1]: ed\\
1707 1720 Editing... done. Executing edited code...\\
1708 1721 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1709 1722
1710 1723 We can then call the function foo():
1711 1724
1712 1725 In [2]: foo()\\
1713 1726 foo() was defined in an editing session
1714 1727
1715 1728 Now we edit foo. IPython automatically loads the editor with the
1716 1729 (temporary) file where foo() was previously defined:
1717 1730
1718 1731 In [3]: ed foo\\
1719 1732 Editing... done. Executing edited code...
1720 1733
1721 1734 And if we call foo() again we get the modified version:
1722 1735
1723 1736 In [4]: foo()\\
1724 1737 foo() has now been changed!
1725 1738
1726 1739 Here is an example of how to edit a code snippet successive
1727 1740 times. First we call the editor:
1728 1741
1729 1742 In [8]: ed\\
1730 1743 Editing... done. Executing edited code...\\
1731 1744 hello\\
1732 1745 Out[8]: "print 'hello'\\n"
1733 1746
1734 1747 Now we call it again with the previous output (stored in _):
1735 1748
1736 1749 In [9]: ed _\\
1737 1750 Editing... done. Executing edited code...\\
1738 1751 hello world\\
1739 1752 Out[9]: "print 'hello world'\\n"
1740 1753
1741 1754 Now we call it with the output #8 (stored in _8, also as Out[8]):
1742 1755
1743 1756 In [10]: ed _8\\
1744 1757 Editing... done. Executing edited code...\\
1745 1758 hello again\\
1746 1759 Out[10]: "print 'hello again'\\n"
1747 1760
1748 1761
1749 1762 Changing the default editor hook:
1750 1763
1751 1764 If you wish to write your own editor hook, you can put it in a
1752 1765 configuration file which you load at startup time. The default hook
1753 1766 is defined in the IPython.hooks module, and you can use that as a
1754 1767 starting example for further modifications. That file also has
1755 1768 general instructions on how to set a new hook for use once you've
1756 1769 defined it."""
1757 1770
1758 1771 # FIXME: This function has become a convoluted mess. It needs a
1759 1772 # ground-up rewrite with clean, simple logic.
1760 1773
1761 1774 def make_filename(arg):
1762 1775 "Make a filename from the given args"
1763 1776 try:
1764 1777 filename = get_py_filename(arg)
1765 1778 except IOError:
1766 1779 if args.endswith('.py'):
1767 1780 filename = arg
1768 1781 else:
1769 1782 filename = None
1770 1783 return filename
1771 1784
1772 1785 # custom exceptions
1773 1786 class DataIsObject(Exception): pass
1774 1787
1775 1788 opts,args = self.parse_options(parameter_s,'px')
1776 1789
1777 1790 # Default line number value
1778 1791 lineno = None
1779 1792 if opts.has_key('p'):
1780 1793 args = '_%s' % last_call[0]
1781 1794 if not self.shell.user_ns.has_key(args):
1782 1795 args = last_call[1]
1783 1796
1784 1797 # use last_call to remember the state of the previous call, but don't
1785 1798 # let it be clobbered by successive '-p' calls.
1786 1799 try:
1787 1800 last_call[0] = self.shell.outputcache.prompt_count
1788 1801 if not opts.has_key('p'):
1789 1802 last_call[1] = parameter_s
1790 1803 except:
1791 1804 pass
1792 1805
1793 1806 # by default this is done with temp files, except when the given
1794 1807 # arg is a filename
1795 1808 use_temp = 1
1796 1809
1797 1810 if re.match(r'\d',args):
1798 1811 # Mode where user specifies ranges of lines, like in %macro.
1799 1812 # This means that you can't edit files whose names begin with
1800 1813 # numbers this way. Tough.
1801 1814 ranges = args.split()
1802 1815 data = ''.join(self.extract_input_slices(ranges))
1803 1816 elif args.endswith('.py'):
1804 1817 filename = make_filename(args)
1805 1818 data = ''
1806 1819 use_temp = 0
1807 1820 elif args:
1808 1821 try:
1809 1822 # Load the parameter given as a variable. If not a string,
1810 1823 # process it as an object instead (below)
1811 1824
1812 1825 #print '*** args',args,'type',type(args) # dbg
1813 1826 data = eval(args,self.shell.user_ns)
1814 1827 if not type(data) in StringTypes:
1815 1828 raise DataIsObject
1816 1829 except (NameError,SyntaxError):
1817 1830 # given argument is not a variable, try as a filename
1818 1831 filename = make_filename(args)
1819 1832 if filename is None:
1820 1833 warn("Argument given (%s) can't be found as a variable "
1821 1834 "or as a filename." % args)
1822 1835 return
1823 1836 data = ''
1824 1837 use_temp = 0
1825 1838 except DataIsObject:
1826 1839 # For objects, try to edit the file where they are defined
1827 1840 try:
1828 1841 filename = inspect.getabsfile(data)
1829 1842 datafile = 1
1830 1843 except TypeError:
1831 1844 filename = make_filename(args)
1832 1845 datafile = 1
1833 1846 warn('Could not find file where `%s` is defined.\n'
1834 1847 'Opening a file named `%s`' % (args,filename))
1835 1848 # Now, make sure we can actually read the source (if it was in
1836 1849 # a temp file it's gone by now).
1837 1850 if datafile:
1838 1851 try:
1839 1852 lineno = inspect.getsourcelines(data)[1]
1840 1853 except IOError:
1841 1854 filename = make_filename(args)
1842 1855 if filename is None:
1843 1856 warn('The file `%s` where `%s` was defined cannot '
1844 1857 'be read.' % (filename,data))
1845 1858 return
1846 1859 use_temp = 0
1847 1860 else:
1848 1861 data = ''
1849 1862
1850 1863 if use_temp:
1851 1864 filename = tempfile.mktemp('.py')
1852 1865 self.shell.tempfiles.append(filename)
1853 1866
1854 1867 if data and use_temp:
1855 1868 tmp_file = open(filename,'w')
1856 1869 tmp_file.write(data)
1857 1870 tmp_file.close()
1858 1871
1859 1872 # do actual editing here
1860 1873 print 'Editing...',
1861 1874 sys.stdout.flush()
1862 1875 self.shell.hooks.editor(filename,lineno)
1863 1876 if opts.has_key('x'): # -x prevents actual execution
1864 1877 print
1865 1878 else:
1866 1879 print 'done. Executing edited code...'
1867 1880 try:
1868 1881 self.shell.safe_execfile(filename,self.shell.user_ns)
1869 1882 except IOError,msg:
1870 1883 if msg.filename == filename:
1871 1884 warn('File not found. Did you forget to save?')
1872 1885 return
1873 1886 else:
1874 1887 self.shell.showtraceback()
1875 1888 except:
1876 1889 self.shell.showtraceback()
1877 1890 if use_temp:
1878 1891 contents = open(filename).read()
1879 1892 return contents
1880 1893
1881 1894 def magic_xmode(self,parameter_s = ''):
1882 1895 """Switch modes for the exception handlers.
1883 1896
1884 1897 Valid modes: Plain, Context and Verbose.
1885 1898
1886 1899 If called without arguments, acts as a toggle."""
1887 1900
1888 1901 def xmode_switch_err(name):
1889 1902 warn('Error changing %s exception modes.\n%s' %
1890 1903 (name,sys.exc_info()[1]))
1891 1904
1892 1905 shell = self.shell
1893 1906 new_mode = parameter_s.strip().capitalize()
1894 1907 try:
1895 1908 shell.InteractiveTB.set_mode(mode=new_mode)
1896 1909 print 'Exception reporting mode:',shell.InteractiveTB.mode
1897 1910 except:
1898 1911 xmode_switch_err('user')
1899 1912
1900 1913 # threaded shells use a special handler in sys.excepthook
1901 1914 if shell.isthreaded:
1902 1915 try:
1903 1916 shell.sys_excepthook.set_mode(mode=new_mode)
1904 1917 except:
1905 1918 xmode_switch_err('threaded')
1906 1919
1907 1920 def magic_colors(self,parameter_s = ''):
1908 1921 """Switch color scheme for prompts, info system and exception handlers.
1909 1922
1910 1923 Currently implemented schemes: NoColor, Linux, LightBG.
1911 1924
1912 1925 Color scheme names are not case-sensitive."""
1913 1926
1914 1927 def color_switch_err(name):
1915 1928 warn('Error changing %s color schemes.\n%s' %
1916 1929 (name,sys.exc_info()[1]))
1917 1930
1918 1931
1919 1932 new_scheme = parameter_s.strip()
1920 1933 if not new_scheme:
1921 1934 print 'You must specify a color scheme.'
1922 1935 return
1923 1936 # Under Windows, check for Gary Bishop's readline, which is necessary
1924 1937 # for ANSI coloring
1925 1938 if os.name in ['nt','dos']:
1926 1939 try:
1927 1940 import readline
1928 1941 except ImportError:
1929 1942 has_readline = 0
1930 1943 else:
1931 1944 try:
1932 1945 readline.GetOutputFile()
1933 1946 except AttributeError:
1934 1947 has_readline = 0
1935 1948 else:
1936 1949 has_readline = 1
1937 1950 if not has_readline:
1938 1951 msg = """\
1939 1952 Proper color support under MS Windows requires Gary Bishop's readline library.
1940 1953 You can find it at:
1941 1954 http://sourceforge.net/projects/uncpythontools
1942 1955 Gary's readline needs the ctypes module, from:
1943 1956 http://starship.python.net/crew/theller/ctypes
1944 1957
1945 1958 Defaulting color scheme to 'NoColor'"""
1946 1959 new_scheme = 'NoColor'
1947 1960 warn(msg)
1948 1961 # local shortcut
1949 1962 shell = self.shell
1950 1963
1951 1964 # Set prompt colors
1952 1965 try:
1953 1966 shell.outputcache.set_colors(new_scheme)
1954 1967 except:
1955 1968 color_switch_err('prompt')
1956 1969 else:
1957 1970 shell.rc.colors = \
1958 1971 shell.outputcache.color_table.active_scheme_name
1959 1972 # Set exception colors
1960 1973 try:
1961 1974 shell.InteractiveTB.set_colors(scheme = new_scheme)
1962 1975 shell.SyntaxTB.set_colors(scheme = new_scheme)
1963 1976 except:
1964 1977 color_switch_err('exception')
1965 1978
1966 1979 # threaded shells use a verbose traceback in sys.excepthook
1967 1980 if shell.isthreaded:
1968 1981 try:
1969 1982 shell.sys_excepthook.set_colors(scheme=new_scheme)
1970 1983 except:
1971 1984 color_switch_err('system exception handler')
1972 1985
1973 1986 # Set info (for 'object?') colors
1974 1987 if shell.rc.color_info:
1975 1988 try:
1976 1989 shell.inspector.set_active_scheme(new_scheme)
1977 1990 except:
1978 1991 color_switch_err('object inspector')
1979 1992 else:
1980 1993 shell.inspector.set_active_scheme('NoColor')
1981 1994
1982 1995 def magic_color_info(self,parameter_s = ''):
1983 1996 """Toggle color_info.
1984 1997
1985 1998 The color_info configuration parameter controls whether colors are
1986 1999 used for displaying object details (by things like %psource, %pfile or
1987 2000 the '?' system). This function toggles this value with each call.
1988 2001
1989 2002 Note that unless you have a fairly recent pager (less works better
1990 2003 than more) in your system, using colored object information displays
1991 2004 will not work properly. Test it and see."""
1992 2005
1993 2006 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1994 2007 self.magic_colors(self.shell.rc.colors)
1995 2008 print 'Object introspection functions have now coloring:',
1996 2009 print ['OFF','ON'][self.shell.rc.color_info]
1997 2010
1998 2011 def magic_Pprint(self, parameter_s=''):
1999 2012 """Toggle pretty printing on/off."""
2000 2013
2001 2014 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2002 2015 print 'Pretty printing has been turned', \
2003 2016 ['OFF','ON'][self.shell.outputcache.Pprint]
2004 2017
2005 2018 def magic_exit(self, parameter_s=''):
2006 2019 """Exit IPython, confirming if configured to do so.
2007 2020
2008 2021 You can configure whether IPython asks for confirmation upon exit by
2009 2022 setting the confirm_exit flag in the ipythonrc file."""
2010 2023
2011 2024 self.shell.exit()
2012 2025
2013 2026 def magic_quit(self, parameter_s=''):
2014 2027 """Exit IPython, confirming if configured to do so (like %exit)"""
2015 2028
2016 2029 self.shell.exit()
2017 2030
2018 2031 def magic_Exit(self, parameter_s=''):
2019 2032 """Exit IPython without confirmation."""
2020 2033
2021 2034 self.shell.exit_now = True
2022 2035
2023 2036 def magic_Quit(self, parameter_s=''):
2024 2037 """Exit IPython without confirmation (like %Exit)."""
2025 2038
2026 2039 self.shell.exit_now = True
2027 2040
2028 2041 #......................................................................
2029 2042 # Functions to implement unix shell-type things
2030 2043
2031 2044 def magic_alias(self, parameter_s = ''):
2032 2045 """Define an alias for a system command.
2033 2046
2034 2047 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2035 2048
2036 2049 Then, typing 'alias_name params' will execute the system command 'cmd
2037 2050 params' (from your underlying operating system).
2038 2051
2039 2052 Aliases have lower precedence than magic functions and Python normal
2040 2053 variables, so if 'foo' is both a Python variable and an alias, the
2041 2054 alias can not be executed until 'del foo' removes the Python variable.
2042 2055
2043 2056 You can use the %l specifier in an alias definition to represent the
2044 2057 whole line when the alias is called. For example:
2045 2058
2046 2059 In [2]: alias all echo "Input in brackets: <%l>"\\
2047 2060 In [3]: all hello world\\
2048 2061 Input in brackets: <hello world>
2049 2062
2050 2063 You can also define aliases with parameters using %s specifiers (one
2051 2064 per parameter):
2052 2065
2053 2066 In [1]: alias parts echo first %s second %s\\
2054 2067 In [2]: %parts A B\\
2055 2068 first A second B\\
2056 2069 In [3]: %parts A\\
2057 2070 Incorrect number of arguments: 2 expected.\\
2058 2071 parts is an alias to: 'echo first %s second %s'
2059 2072
2060 2073 Note that %l and %s are mutually exclusive. You can only use one or
2061 2074 the other in your aliases.
2062 2075
2063 2076 Aliases expand Python variables just like system calls using ! or !!
2064 2077 do: all expressions prefixed with '$' get expanded. For details of
2065 2078 the semantic rules, see PEP-215:
2066 2079 http://www.python.org/peps/pep-0215.html. This is the library used by
2067 2080 IPython for variable expansion. If you want to access a true shell
2068 2081 variable, an extra $ is necessary to prevent its expansion by IPython:
2069 2082
2070 2083 In [6]: alias show echo\\
2071 2084 In [7]: PATH='A Python string'\\
2072 2085 In [8]: show $PATH\\
2073 2086 A Python string\\
2074 2087 In [9]: show $$PATH\\
2075 2088 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2076 2089
2077 2090 You can use the alias facility to acess all of $PATH. See the %rehash
2078 2091 and %rehashx functions, which automatically create aliases for the
2079 2092 contents of your $PATH.
2080 2093
2081 2094 If called with no parameters, %alias prints the current alias table."""
2082 2095
2083 2096 par = parameter_s.strip()
2084 2097 if not par:
2085 2098 if self.shell.rc.automagic:
2086 2099 prechar = ''
2087 2100 else:
2088 2101 prechar = self.shell.ESC_MAGIC
2089 2102 print 'Alias\t\tSystem Command\n'+'-'*30
2090 2103 atab = self.shell.alias_table
2091 2104 aliases = atab.keys()
2092 2105 aliases.sort()
2093 2106 for alias in aliases:
2094 2107 print prechar+alias+'\t\t'+atab[alias][1]
2095 2108 print '-'*30+'\nTotal number of aliases:',len(aliases)
2096 2109 return
2097 2110 try:
2098 2111 alias,cmd = par.split(None,1)
2099 2112 except:
2100 2113 print OInspect.getdoc(self.magic_alias)
2101 2114 else:
2102 2115 nargs = cmd.count('%s')
2103 2116 if nargs>0 and cmd.find('%l')>=0:
2104 2117 error('The %s and %l specifiers are mutually exclusive '
2105 2118 'in alias definitions.')
2106 2119 else: # all looks OK
2107 2120 self.shell.alias_table[alias] = (nargs,cmd)
2108 2121 self.shell.alias_table_validate(verbose=1)
2109 2122 # end magic_alias
2110 2123
2111 2124 def magic_unalias(self, parameter_s = ''):
2112 2125 """Remove an alias"""
2113 2126
2114 2127 aname = parameter_s.strip()
2115 2128 if aname in self.shell.alias_table:
2116 2129 del self.shell.alias_table[aname]
2117 2130
2118 2131 def magic_rehash(self, parameter_s = ''):
2119 2132 """Update the alias table with all entries in $PATH.
2120 2133
2121 2134 This version does no checks on execute permissions or whether the
2122 2135 contents of $PATH are truly files (instead of directories or something
2123 2136 else). For such a safer (but slower) version, use %rehashx."""
2124 2137
2125 2138 # This function (and rehashx) manipulate the alias_table directly
2126 2139 # rather than calling magic_alias, for speed reasons. A rehash on a
2127 2140 # typical Linux box involves several thousand entries, so efficiency
2128 2141 # here is a top concern.
2129 2142
2130 2143 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2131 2144 alias_table = self.shell.alias_table
2132 2145 for pdir in path:
2133 2146 for ff in os.listdir(pdir):
2134 2147 # each entry in the alias table must be (N,name), where
2135 2148 # N is the number of positional arguments of the alias.
2136 2149 alias_table[ff] = (0,ff)
2137 2150 # Make sure the alias table doesn't contain keywords or builtins
2138 2151 self.shell.alias_table_validate()
2139 2152 # Call again init_auto_alias() so we get 'rm -i' and other modified
2140 2153 # aliases since %rehash will probably clobber them
2141 2154 self.shell.init_auto_alias()
2142 2155
2143 2156 def magic_rehashx(self, parameter_s = ''):
2144 2157 """Update the alias table with all executable files in $PATH.
2145 2158
2146 2159 This version explicitly checks that every entry in $PATH is a file
2147 2160 with execute access (os.X_OK), so it is much slower than %rehash.
2148 2161
2149 2162 Under Windows, it checks executability as a match agains a
2150 2163 '|'-separated string of extensions, stored in the IPython config
2151 2164 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2152 2165
2153 2166 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2154 2167 alias_table = self.shell.alias_table
2155 2168
2156 2169 if os.name == 'posix':
2157 2170 isexec = lambda fname:os.path.isfile(fname) and \
2158 2171 os.access(fname,os.X_OK)
2159 2172 else:
2160 2173
2161 2174 try:
2162 2175 winext = os.environ['pathext'].replace(';','|').replace('.','')
2163 2176 except KeyError:
2164 2177 winext = 'exe|com|bat'
2165 2178
2166 2179 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2167 2180 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2168 2181 savedir = os.getcwd()
2169 2182 try:
2170 2183 # write the whole loop for posix/Windows so we don't have an if in
2171 2184 # the innermost part
2172 2185 if os.name == 'posix':
2173 2186 for pdir in path:
2174 2187 os.chdir(pdir)
2175 2188 for ff in os.listdir(pdir):
2176 2189 if isexec(ff):
2177 2190 # each entry in the alias table must be (N,name),
2178 2191 # where N is the number of positional arguments of the
2179 2192 # alias.
2180 2193 alias_table[ff] = (0,ff)
2181 2194 else:
2182 2195 for pdir in path:
2183 2196 os.chdir(pdir)
2184 2197 for ff in os.listdir(pdir):
2185 2198 if isexec(ff):
2186 2199 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2187 2200 # Make sure the alias table doesn't contain keywords or builtins
2188 2201 self.shell.alias_table_validate()
2189 2202 # Call again init_auto_alias() so we get 'rm -i' and other
2190 2203 # modified aliases since %rehashx will probably clobber them
2191 2204 self.shell.init_auto_alias()
2192 2205 finally:
2193 2206 os.chdir(savedir)
2194 2207
2195 2208 def magic_pwd(self, parameter_s = ''):
2196 2209 """Return the current working directory path."""
2197 2210 return os.getcwd()
2198 2211
2199 2212 def magic_cd(self, parameter_s=''):
2200 2213 """Change the current working directory.
2201 2214
2202 2215 This command automatically maintains an internal list of directories
2203 2216 you visit during your IPython session, in the variable _dh. The
2204 2217 command %dhist shows this history nicely formatted.
2205 2218
2206 2219 Usage:
2207 2220
2208 2221 cd 'dir': changes to directory 'dir'.
2209 2222
2210 2223 cd -: changes to the last visited directory.
2211 2224
2212 2225 cd -<n>: changes to the n-th directory in the directory history.
2213 2226
2214 2227 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2215 2228 (note: cd <bookmark_name> is enough if there is no
2216 2229 directory <bookmark_name>, but a bookmark with the name exists.)
2217 2230
2218 2231 Options:
2219 2232
2220 2233 -q: quiet. Do not print the working directory after the cd command is
2221 2234 executed. By default IPython's cd command does print this directory,
2222 2235 since the default prompts do not display path information.
2223 2236
2224 2237 Note that !cd doesn't work for this purpose because the shell where
2225 2238 !command runs is immediately discarded after executing 'command'."""
2226 2239
2227 2240 parameter_s = parameter_s.strip()
2228 2241 bkms = self.shell.persist.get("bookmarks",{})
2229 2242
2230 2243 numcd = re.match(r'(-)(\d+)$',parameter_s)
2231 2244 # jump in directory history by number
2232 2245 if numcd:
2233 2246 nn = int(numcd.group(2))
2234 2247 try:
2235 2248 ps = self.shell.user_ns['_dh'][nn]
2236 2249 except IndexError:
2237 2250 print 'The requested directory does not exist in history.'
2238 2251 return
2239 2252 else:
2240 2253 opts = {}
2241 2254 else:
2242 2255 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2243 2256 # jump to previous
2244 2257 if ps == '-':
2245 2258 try:
2246 2259 ps = self.shell.user_ns['_dh'][-2]
2247 2260 except IndexError:
2248 2261 print 'No previous directory to change to.'
2249 2262 return
2250 2263 # jump to bookmark
2251 2264 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2252 2265 if bkms.has_key(ps):
2253 2266 target = bkms[ps]
2254 2267 print '(bookmark:%s) -> %s' % (ps,target)
2255 2268 ps = target
2256 2269 else:
2257 2270 if bkms:
2258 2271 error("Bookmark '%s' not found. "
2259 2272 "Use '%bookmark -l' to see your bookmarks." % ps)
2260 2273 else:
2261 2274 print "Bookmarks not set - use %bookmark <bookmarkname>"
2262 2275 return
2263 2276
2264 2277 # at this point ps should point to the target dir
2265 2278 if ps:
2266 2279 try:
2267 2280 os.chdir(os.path.expanduser(ps))
2268 2281 except OSError:
2269 2282 print sys.exc_info()[1]
2270 2283 else:
2271 2284 self.shell.user_ns['_dh'].append(os.getcwd())
2272 2285 else:
2273 2286 os.chdir(self.shell.home_dir)
2274 2287 self.shell.user_ns['_dh'].append(os.getcwd())
2275 2288 if not 'q' in opts:
2276 2289 print self.shell.user_ns['_dh'][-1]
2277 2290
2278 2291 def magic_dhist(self, parameter_s=''):
2279 2292 """Print your history of visited directories.
2280 2293
2281 2294 %dhist -> print full history\\
2282 2295 %dhist n -> print last n entries only\\
2283 2296 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2284 2297
2285 2298 This history is automatically maintained by the %cd command, and
2286 2299 always available as the global list variable _dh. You can use %cd -<n>
2287 2300 to go to directory number <n>."""
2288 2301
2289 2302 dh = self.shell.user_ns['_dh']
2290 2303 if parameter_s:
2291 2304 try:
2292 2305 args = map(int,parameter_s.split())
2293 2306 except:
2294 2307 self.arg_err(Magic.magic_dhist)
2295 2308 return
2296 2309 if len(args) == 1:
2297 2310 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2298 2311 elif len(args) == 2:
2299 2312 ini,fin = args
2300 2313 else:
2301 2314 self.arg_err(Magic.magic_dhist)
2302 2315 return
2303 2316 else:
2304 2317 ini,fin = 0,len(dh)
2305 2318 nlprint(dh,
2306 2319 header = 'Directory history (kept in _dh)',
2307 2320 start=ini,stop=fin)
2308 2321
2309 2322 def magic_env(self, parameter_s=''):
2310 2323 """List environment variables."""
2311 2324
2312 2325 return os.environ.data
2313 2326
2314 2327 def magic_pushd(self, parameter_s=''):
2315 2328 """Place the current dir on stack and change directory.
2316 2329
2317 2330 Usage:\\
2318 2331 %pushd ['dirname']
2319 2332
2320 2333 %pushd with no arguments does a %pushd to your home directory.
2321 2334 """
2322 2335 if parameter_s == '': parameter_s = '~'
2323 2336 dir_s = self.shell.dir_stack
2324 2337 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2325 2338 os.path.expanduser(self.shell.dir_stack[0]):
2326 2339 try:
2327 2340 self.magic_cd(parameter_s)
2328 2341 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2329 2342 self.magic_dirs()
2330 2343 except:
2331 2344 print 'Invalid directory'
2332 2345 else:
2333 2346 print 'You are already there!'
2334 2347
2335 2348 def magic_popd(self, parameter_s=''):
2336 2349 """Change to directory popped off the top of the stack.
2337 2350 """
2338 2351 if len (self.shell.dir_stack) > 1:
2339 2352 self.shell.dir_stack.pop(0)
2340 2353 self.magic_cd(self.shell.dir_stack[0])
2341 2354 print self.shell.dir_stack[0]
2342 2355 else:
2343 2356 print "You can't remove the starting directory from the stack:",\
2344 2357 self.shell.dir_stack
2345 2358
2346 2359 def magic_dirs(self, parameter_s=''):
2347 2360 """Return the current directory stack."""
2348 2361
2349 2362 return self.shell.dir_stack[:]
2350 2363
2351 2364 def magic_sc(self, parameter_s=''):
2352 2365 """Shell capture - execute a shell command and capture its output.
2353 2366
2354 2367 %sc [options] varname=command
2355 2368
2356 2369 IPython will run the given command using commands.getoutput(), and
2357 2370 will then update the user's interactive namespace with a variable
2358 2371 called varname, containing the value of the call. Your command can
2359 2372 contain shell wildcards, pipes, etc.
2360 2373
2361 2374 The '=' sign in the syntax is mandatory, and the variable name you
2362 2375 supply must follow Python's standard conventions for valid names.
2363 2376
2364 2377 Options:
2365 2378
2366 2379 -l: list output. Split the output on newlines into a list before
2367 2380 assigning it to the given variable. By default the output is stored
2368 2381 as a single string.
2369 2382
2370 2383 -v: verbose. Print the contents of the variable.
2371 2384
2372 2385 In most cases you should not need to split as a list, because the
2373 2386 returned value is a special type of string which can automatically
2374 2387 provide its contents either as a list (split on newlines) or as a
2375 2388 space-separated string. These are convenient, respectively, either
2376 2389 for sequential processing or to be passed to a shell command.
2377 2390
2378 2391 For example:
2379 2392
2380 2393 # Capture into variable a
2381 2394 In [9]: sc a=ls *py
2382 2395
2383 2396 # a is a string with embedded newlines
2384 2397 In [10]: a
2385 2398 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2386 2399
2387 2400 # which can be seen as a list:
2388 2401 In [11]: a.l
2389 2402 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2390 2403
2391 2404 # or as a whitespace-separated string:
2392 2405 In [12]: a.s
2393 2406 Out[12]: 'setup.py win32_manual_post_install.py'
2394 2407
2395 2408 # a.s is useful to pass as a single command line:
2396 2409 In [13]: !wc -l $a.s
2397 2410 146 setup.py
2398 2411 130 win32_manual_post_install.py
2399 2412 276 total
2400 2413
2401 2414 # while the list form is useful to loop over:
2402 2415 In [14]: for f in a.l:
2403 2416 ....: !wc -l $f
2404 2417 ....:
2405 2418 146 setup.py
2406 2419 130 win32_manual_post_install.py
2407 2420
2408 2421 Similiarly, the lists returned by the -l option are also special, in
2409 2422 the sense that you can equally invoke the .s attribute on them to
2410 2423 automatically get a whitespace-separated string from their contents:
2411 2424
2412 2425 In [1]: sc -l b=ls *py
2413 2426
2414 2427 In [2]: b
2415 2428 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2416 2429
2417 2430 In [3]: b.s
2418 2431 Out[3]: 'setup.py win32_manual_post_install.py'
2419 2432
2420 2433 In summary, both the lists and strings used for ouptut capture have
2421 2434 the following special attributes:
2422 2435
2423 2436 .l (or .list) : value as list.
2424 2437 .n (or .nlstr): value as newline-separated string.
2425 2438 .s (or .spstr): value as space-separated string.
2426 2439 """
2427 2440
2428 2441 opts,args = self.parse_options(parameter_s,'lv')
2429 2442 # Try to get a variable name and command to run
2430 2443 try:
2431 2444 # the variable name must be obtained from the parse_options
2432 2445 # output, which uses shlex.split to strip options out.
2433 2446 var,_ = args.split('=',1)
2434 2447 var = var.strip()
2435 2448 # But the the command has to be extracted from the original input
2436 2449 # parameter_s, not on what parse_options returns, to avoid the
2437 2450 # quote stripping which shlex.split performs on it.
2438 2451 _,cmd = parameter_s.split('=',1)
2439 2452 except ValueError:
2440 2453 var,cmd = '',''
2441 2454 if not var:
2442 2455 error('you must specify a variable to assign the command to.')
2443 2456 return
2444 2457 # If all looks ok, proceed
2445 2458 out,err = self.shell.getoutputerror(cmd)
2446 2459 if err:
2447 2460 print >> Term.cerr,err
2448 2461 if opts.has_key('l'):
2449 2462 out = SList(out.split('\n'))
2450 2463 else:
2451 2464 out = LSString(out)
2452 2465 if opts.has_key('v'):
2453 2466 print '%s ==\n%s' % (var,pformat(out))
2454 2467 self.shell.user_ns.update({var:out})
2455 2468
2456 2469 def magic_sx(self, parameter_s=''):
2457 2470 """Shell execute - run a shell command and capture its output.
2458 2471
2459 2472 %sx command
2460 2473
2461 2474 IPython will run the given command using commands.getoutput(), and
2462 2475 return the result formatted as a list (split on '\\n'). Since the
2463 2476 output is _returned_, it will be stored in ipython's regular output
2464 2477 cache Out[N] and in the '_N' automatic variables.
2465 2478
2466 2479 Notes:
2467 2480
2468 2481 1) If an input line begins with '!!', then %sx is automatically
2469 2482 invoked. That is, while:
2470 2483 !ls
2471 2484 causes ipython to simply issue system('ls'), typing
2472 2485 !!ls
2473 2486 is a shorthand equivalent to:
2474 2487 %sx ls
2475 2488
2476 2489 2) %sx differs from %sc in that %sx automatically splits into a list,
2477 2490 like '%sc -l'. The reason for this is to make it as easy as possible
2478 2491 to process line-oriented shell output via further python commands.
2479 2492 %sc is meant to provide much finer control, but requires more
2480 2493 typing.
2481 2494
2482 2495 3) Just like %sc -l, this is a list with special attributes:
2483 2496
2484 2497 .l (or .list) : value as list.
2485 2498 .n (or .nlstr): value as newline-separated string.
2486 2499 .s (or .spstr): value as whitespace-separated string.
2487 2500
2488 2501 This is very useful when trying to use such lists as arguments to
2489 2502 system commands."""
2490 2503
2491 2504 if parameter_s:
2492 2505 out,err = self.shell.getoutputerror(parameter_s)
2493 2506 if err:
2494 2507 print >> Term.cerr,err
2495 2508 return SList(out.split('\n'))
2496 2509
2497 2510 def magic_bg(self, parameter_s=''):
2498 2511 """Run a job in the background, in a separate thread.
2499 2512
2500 2513 For example,
2501 2514
2502 2515 %bg myfunc(x,y,z=1)
2503 2516
2504 2517 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2505 2518 execution starts, a message will be printed indicating the job
2506 2519 number. If your job number is 5, you can use
2507 2520
2508 2521 myvar = jobs.result(5) or myvar = jobs[5].result
2509 2522
2510 2523 to assign this result to variable 'myvar'.
2511 2524
2512 2525 IPython has a job manager, accessible via the 'jobs' object. You can
2513 2526 type jobs? to get more information about it, and use jobs.<TAB> to see
2514 2527 its attributes. All attributes not starting with an underscore are
2515 2528 meant for public use.
2516 2529
2517 2530 In particular, look at the jobs.new() method, which is used to create
2518 2531 new jobs. This magic %bg function is just a convenience wrapper
2519 2532 around jobs.new(), for expression-based jobs. If you want to create a
2520 2533 new job with an explicit function object and arguments, you must call
2521 2534 jobs.new() directly.
2522 2535
2523 2536 The jobs.new docstring also describes in detail several important
2524 2537 caveats associated with a thread-based model for background job
2525 2538 execution. Type jobs.new? for details.
2526 2539
2527 2540 You can check the status of all jobs with jobs.status().
2528 2541
2529 2542 The jobs variable is set by IPython into the Python builtin namespace.
2530 2543 If you ever declare a variable named 'jobs', you will shadow this
2531 2544 name. You can either delete your global jobs variable to regain
2532 2545 access to the job manager, or make a new name and assign it manually
2533 2546 to the manager (stored in IPython's namespace). For example, to
2534 2547 assign the job manager to the Jobs name, use:
2535 2548
2536 2549 Jobs = __builtins__.jobs"""
2537 2550
2538 2551 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2539 2552
2540 2553 def magic_store(self, parameter_s=''):
2541 2554 """Lightweight persistence for python variables.
2542 2555
2543 2556 Example:
2544 2557
2545 2558 ville@badger[~]|1> A = ['hello',10,'world']\\
2546 2559 ville@badger[~]|2> %store A\\
2547 2560 ville@badger[~]|3> Exit
2548 2561
2549 2562 (IPython session is closed and started again...)
2550 2563
2551 2564 ville@badger:~$ ipython -p pysh\\
2552 2565 ville@badger[~]|1> print A
2553 2566
2554 2567 ['hello', 10, 'world']
2555 2568
2556 2569 Usage:
2557 2570
2558 2571 %store - Show list of all variables and their current values\\
2559 2572 %store <var> - Store the *current* value of the variable to disk\\
2560 2573 %store -d - Remove the variable and its value from storage\\
2561 2574 %store -r - Remove all variables from storage
2562 2575
2563 2576 It should be noted that if you change the value of a variable, you
2564 2577 need to %store it again if you want to persist the new value.
2565 2578
2566 2579 Note also that the variables will need to be pickleable; most basic
2567 2580 python types can be safely %stored.
2568 2581 """
2569 2582
2570 2583 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2571 2584 # delete
2572 2585 if opts.has_key('d'):
2573 2586 try:
2574 2587 todel = args[0]
2575 2588 except IndexError:
2576 2589 error('You must provide the variable to forget')
2577 2590 else:
2578 2591 try:
2579 2592 del self.shell.persist['S:' + todel]
2580 2593 except:
2581 2594 error("Can't delete variable '%s'" % todel)
2582 2595 # reset
2583 2596 elif opts.has_key('r'):
2584 2597 for k in self.shell.persist.keys():
2585 2598 if k.startswith('S:'):
2586 2599 del self.shell.persist[k]
2587 2600
2588 2601 # run without arguments -> list variables & values
2589 2602 elif not args:
2590 2603 vars = [v[2:] for v in self.shell.persist.keys()
2591 2604 if v.startswith('S:')]
2592 2605 vars.sort()
2593 2606 if vars:
2594 2607 size = max(map(len,vars))
2595 2608 else:
2596 2609 size = 0
2597 2610
2598 2611 print 'Stored variables and their in-memory values:'
2599 2612 fmt = '%-'+str(size)+'s -> %s'
2600 2613 get = self.shell.user_ns.get
2601 2614 for var in vars:
2602 2615 # print 30 first characters from every var
2603 2616 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2604 2617
2605 2618 # default action - store the variable
2606 2619 else:
2607 2620 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2608 2621 self.shell.persist[ 'S:' + args[0] ] = pickled
2609 2622 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2610 2623
2611 2624 def magic_bookmark(self, parameter_s=''):
2612 2625 """Manage IPython's bookmark system.
2613 2626
2614 2627 %bookmark <name> - set bookmark to current dir
2615 2628 %bookmark <name> <dir> - set bookmark to <dir>
2616 2629 %bookmark -l - list all bookmarks
2617 2630 %bookmark -d <name> - remove bookmark
2618 2631 %bookmark -r - remove all bookmarks
2619 2632
2620 2633 You can later on access a bookmarked folder with:
2621 2634 %cd -b <name>
2622 2635 or simply '%cd <name>' if there is no directory called <name> AND
2623 2636 there is such a bookmark defined.
2624 2637
2625 2638 Your bookmarks persist through IPython sessions, but they are
2626 2639 associated with each profile."""
2627 2640
2628 2641 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2629 2642 if len(args) > 2:
2630 2643 error('You can only give at most two arguments')
2631 2644 return
2632 2645
2633 2646 bkms = self.shell.persist.get('bookmarks',{})
2634 2647
2635 2648 if opts.has_key('d'):
2636 2649 try:
2637 2650 todel = args[0]
2638 2651 except IndexError:
2639 2652 error('You must provide a bookmark to delete')
2640 2653 else:
2641 2654 try:
2642 2655 del bkms[todel]
2643 2656 except:
2644 2657 error("Can't delete bookmark '%s'" % todel)
2645 2658 elif opts.has_key('r'):
2646 2659 bkms = {}
2647 2660 elif opts.has_key('l'):
2648 2661 bks = bkms.keys()
2649 2662 bks.sort()
2650 2663 if bks:
2651 2664 size = max(map(len,bks))
2652 2665 else:
2653 2666 size = 0
2654 2667 fmt = '%-'+str(size)+'s -> %s'
2655 2668 print 'Current bookmarks:'
2656 2669 for bk in bks:
2657 2670 print fmt % (bk,bkms[bk])
2658 2671 else:
2659 2672 if not args:
2660 2673 error("You must specify the bookmark name")
2661 2674 elif len(args)==1:
2662 2675 bkms[args[0]] = os.getcwd()
2663 2676 elif len(args)==2:
2664 2677 bkms[args[0]] = args[1]
2665 2678 self.shell.persist['bookmarks'] = bkms
2666 2679
2667 2680 def magic_pycat(self, parameter_s=''):
2668 2681 """Show a syntax-highlighted file through a pager.
2669 2682
2670 2683 This magic is similar to the cat utility, but it will assume the file
2671 2684 to be Python source and will show it with syntax highlighting. """
2672 2685
2673 2686 filename = get_py_filename(parameter_s)
2674 2687 page(self.shell.colorize(file_read(filename)),
2675 2688 screen_lines=self.shell.rc.screen_length)
2676 2689
2677 2690 # end Magic
@@ -1,76 +1,76 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Release data for the IPython project.
3 3
4 $Id: Release.py 984 2005-12-31 08:40:31Z fperez $"""
4 $Id: Release.py 986 2005-12-31 23:07:31Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
8 8 #
9 9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
10 10 # <n8gray@caltech.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 # Name of the package for release purposes. This is the name which labels
17 17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
18 18 name = 'ipython'
19 19
20 20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
21 21 # the new substring. We have to avoid using either dashes or underscores,
22 22 # because bdist_rpm does not accept dashes (an RPM) convention, and
23 23 # bdist_deb does not accept underscores (a Debian convention).
24 24
25 version = '0.7.0.rc4'
25 version = '0.7.0.rc5'
26 26
27 revision = '$Revision: 984 $'
27 revision = '$Revision: 986 $'
28 28
29 29 description = "An enhanced interactive Python shell."
30 30
31 31 long_description = \
32 32 """
33 33 IPython provides a replacement for the interactive Python interpreter with
34 34 extra functionality.
35 35
36 36 Main features:
37 37
38 38 * Comprehensive object introspection.
39 39
40 40 * Input history, persistent across sessions.
41 41
42 42 * Caching of output results during a session with automatically generated
43 43 references.
44 44
45 45 * Readline based name completion.
46 46
47 47 * Extensible system of 'magic' commands for controlling the environment and
48 48 performing many tasks related either to IPython or the operating system.
49 49
50 50 * Configuration system with easy switching between different setups (simpler
51 51 than changing $PYTHONSTARTUP environment variables every time).
52 52
53 53 * Session logging and reloading.
54 54
55 55 * Extensible syntax processing for special purpose situations.
56 56
57 57 * Access to the system shell with user-extensible alias system.
58 58
59 59 * Easily embeddable in other Python programs.
60 60
61 61 * Integrated access to the pdb debugger and the Python profiler. """
62 62
63 63 license = 'BSD'
64 64
65 65 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
66 66 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
67 67 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu')
68 68 }
69 69
70 70 url = 'http://ipython.scipy.org'
71 71
72 72 download_url = 'http://ipython.scipy.org/dist'
73 73
74 74 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
75 75
76 76 keywords = ['Interactive','Interpreter','Shell']
@@ -1,534 +1,543 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 76 from IPython.genutils import shlex_split
77 77
78 78 __all__ = ['Completer','IPCompleter']
79 79
80 80 def get_class_members(cls):
81 81 ret = dir(cls)
82 82 if hasattr(cls,'__bases__'):
83 83 for base in cls.__bases__:
84 84 ret.extend(get_class_members(base))
85 85 return ret
86 86
87 87 class Completer:
88 88 def __init__(self,namespace=None,global_namespace=None):
89 89 """Create a new completer for the command line.
90 90
91 91 Completer([namespace,global_namespace]) -> completer instance.
92 92
93 93 If unspecified, the default namespace where completions are performed
94 94 is __main__ (technically, __main__.__dict__). Namespaces should be
95 95 given as dictionaries.
96 96
97 97 An optional second namespace can be given. This allows the completer
98 98 to handle cases where both the local and global scopes need to be
99 99 distinguished.
100 100
101 101 Completer instances should be used as the completion mechanism of
102 102 readline via the set_completer() call:
103 103
104 104 readline.set_completer(Completer(my_namespace).complete)
105 105 """
106 106
107 107 # some minimal strict typechecks. For some core data structures, I
108 108 # want actual basic python types, not just anything that looks like
109 109 # one. This is especially true for namespaces.
110 110 for ns in (namespace,global_namespace):
111 111 if ns is not None and type(ns) != types.DictType:
112 112 raise TypeError,'namespace must be a dictionary'
113 113
114 114 # Don't bind to namespace quite yet, but flag whether the user wants a
115 115 # specific namespace or to use __main__.__dict__. This will allow us
116 116 # to bind to __main__.__dict__ at completion time, not now.
117 117 if namespace is None:
118 118 self.use_main_ns = 1
119 119 else:
120 120 self.use_main_ns = 0
121 121 self.namespace = namespace
122 122
123 123 # The global namespace, if given, can be bound directly
124 124 if global_namespace is None:
125 125 self.global_namespace = {}
126 126 else:
127 127 self.global_namespace = global_namespace
128 128
129 129 def complete(self, text, state):
130 130 """Return the next possible completion for 'text'.
131 131
132 132 This is called successively with state == 0, 1, 2, ... until it
133 133 returns None. The completion should begin with 'text'.
134 134
135 135 """
136 136 if self.use_main_ns:
137 137 self.namespace = __main__.__dict__
138 138
139 139 if state == 0:
140 140 if "." in text:
141 141 self.matches = self.attr_matches(text)
142 142 else:
143 143 self.matches = self.global_matches(text)
144 144 try:
145 145 return self.matches[state]
146 146 except IndexError:
147 147 return None
148 148
149 149 def global_matches(self, text):
150 150 """Compute matches when text is a simple name.
151 151
152 152 Return a list of all keywords, built-in functions and names currently
153 153 defined in self.namespace or self.global_namespace that match.
154 154
155 155 """
156 156 matches = []
157 157 match_append = matches.append
158 158 n = len(text)
159 159 for lst in [keyword.kwlist,
160 160 __builtin__.__dict__.keys(),
161 161 self.namespace.keys(),
162 162 self.global_namespace.keys()]:
163 163 for word in lst:
164 164 if word[:n] == text and word != "__builtins__":
165 165 match_append(word)
166 166 return matches
167 167
168 168 def attr_matches(self, text):
169 169 """Compute matches when text contains a dot.
170 170
171 171 Assuming the text is of the form NAME.NAME....[NAME], and is
172 172 evaluatable in self.namespace or self.global_namespace, it will be
173 173 evaluated and its attributes (as revealed by dir()) are used as
174 174 possible completions. (For class instances, class members are are
175 175 also considered.)
176 176
177 177 WARNING: this can still invoke arbitrary C code, if an object
178 178 with a __getattr__ hook is evaluated.
179 179
180 180 """
181 181 import re
182 182
183 183 # Another option, seems to work great. Catches things like ''.<tab>
184 184 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
185 185
186 186 if not m:
187 187 return []
188 188
189 189 expr, attr = m.group(1, 3)
190 190 try:
191 191 object = eval(expr, self.namespace)
192 192 except:
193 193 object = eval(expr, self.global_namespace)
194 194
195 195 # for modules which define __all__, complete only on those.
196 196 if type(object) == types.ModuleType and hasattr(object, '__all__'):
197 197 words = getattr(object, '__all__')
198 198 else:
199 199 words = dir(object)
200 200 if hasattr(object,'__class__'):
201 201 words.append('__class__')
202 202 words.extend(get_class_members(object.__class__))
203 203
204 204 # filter out non-string attributes which may be stuffed by dir() calls
205 205 # and poor coding in third-party modules
206 206 words = [w for w in words
207 207 if isinstance(w, basestring) and w != "__builtins__"]
208 208 # Build match list to return
209 209 n = len(attr)
210 210 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
211 211
212 212 class IPCompleter(Completer):
213 213 """Extension of the completer class with IPython-specific features"""
214 214
215 215 def __init__(self,shell,namespace=None,global_namespace=None,
216 216 omit__names=0,alias_table=None):
217 217 """IPCompleter() -> completer
218 218
219 219 Return a completer object suitable for use by the readline library
220 220 via readline.set_completer().
221 221
222 222 Inputs:
223 223
224 224 - shell: a pointer to the ipython shell itself. This is needed
225 225 because this completer knows about magic functions, and those can
226 226 only be accessed via the ipython instance.
227 227
228 228 - namespace: an optional dict where completions are performed.
229 229
230 230 - global_namespace: secondary optional dict for completions, to
231 231 handle cases (such as IPython embedded inside functions) where
232 232 both Python scopes are visible.
233 233
234 234 - The optional omit__names parameter sets the completer to omit the
235 235 'magic' names (__magicname__) for python objects unless the text
236 236 to be completed explicitly starts with one or more underscores.
237 237
238 238 - If alias_table is supplied, it should be a dictionary of aliases
239 239 to complete. """
240 240
241 241 Completer.__init__(self,namespace,global_namespace)
242 242 self.magic_prefix = shell.name+'.magic_'
243 243 self.magic_escape = shell.ESC_MAGIC
244 244 self.readline = readline
245 245 delims = self.readline.get_completer_delims()
246 246 delims = delims.replace(self.magic_escape,'')
247 247 self.readline.set_completer_delims(delims)
248 248 self.get_line_buffer = self.readline.get_line_buffer
249 249 self.omit__names = omit__names
250 250 self.merge_completions = shell.rc.readline_merge_completions
251 251
252 252 if alias_table is None:
253 253 alias_table = {}
254 254 self.alias_table = alias_table
255 255 # Regexp to split filenames with spaces in them
256 256 self.space_name_re = re.compile(r'([^\\] )')
257 257 # Hold a local ref. to glob.glob for speed
258 258 self.glob = glob.glob
259
260 # Determine if we are running on 'dumb' terminals, like (X)Emacs
261 # buffers, to avoid completion problems.
262 term = os.environ.get('TERM','xterm')
263 self.dumb_terminal = term in ['dumb','emacs']
264
259 265 # Special handling of backslashes needed in win32 platforms
260 266 if sys.platform == "win32":
261 267 self.clean_glob = self._clean_glob_win32
262 268 else:
263 269 self.clean_glob = self._clean_glob
264 270 self.matchers = [self.python_matches,
265 271 self.file_matches,
266 272 self.alias_matches,
267 273 self.python_func_kw_matches]
268 274
269 275 # Code contributed by Alex Schmolck, for ipython/emacs integration
270 276 def all_completions(self, text):
271 277 """Return all possible completions for the benefit of emacs."""
272 278
273 279 completions = []
274 280 comp_append = completions.append
275 281 try:
276 282 for i in xrange(sys.maxint):
277 283 res = self.complete(text, i)
278 284
279 285 if not res: break
280 286
281 287 comp_append(res)
282 288 #XXX workaround for ``notDefined.<tab>``
283 289 except NameError:
284 290 pass
285 291 return completions
286 292 # /end Alex Schmolck code.
287 293
288 294 def _clean_glob(self,text):
289 295 return self.glob("%s*" % text)
290 296
291 297 def _clean_glob_win32(self,text):
292 298 return [f.replace("\\","/")
293 299 for f in self.glob("%s*" % text)]
294 300
295 301 def file_matches(self, text):
296 302 """Match filneames, expanding ~USER type strings.
297 303
298 304 Most of the seemingly convoluted logic in this completer is an
299 305 attempt to handle filenames with spaces in them. And yet it's not
300 306 quite perfect, because Python's readline doesn't expose all of the
301 307 GNU readline details needed for this to be done correctly.
302 308
303 309 For a filename with a space in it, the printed completions will be
304 310 only the parts after what's already been typed (instead of the
305 311 full completions, as is normally done). I don't think with the
306 312 current (as of Python 2.3) Python readline it's possible to do
307 313 better."""
308 314
309 315 #print 'Completer->file_matches: <%s>' % text # dbg
310 316
311 317 # chars that require escaping with backslash - i.e. chars
312 318 # that readline treats incorrectly as delimiters, but we
313 319 # don't want to treat as delimiters in filename matching
314 320 # when escaped with backslash
315 321
316 322 protectables = ' ()[]{}'
317 323
318 324 def protect_filename(s):
319 325 return "".join([(ch in protectables and '\\' + ch or ch)
320 326 for ch in s])
321 327
322 328 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
323 329 open_quotes = 0 # track strings with open quotes
324 330 try:
325 331 lsplit = shlex_split(lbuf)[-1]
326 332 except ValueError:
327 333 # typically an unmatched ", or backslash without escaped char.
328 334 if lbuf.count('"')==1:
329 335 open_quotes = 1
330 336 lsplit = lbuf.split('"')[-1]
331 337 elif lbuf.count("'")==1:
332 338 open_quotes = 1
333 339 lsplit = lbuf.split("'")[-1]
334 340 else:
335 341 return None
336 342 except IndexError:
337 343 # tab pressed on empty line
338 344 lsplit = ""
339 345
340 346 if lsplit != protect_filename(lsplit):
341 347 # if protectables are found, do matching on the whole escaped
342 348 # name
343 349 has_protectables = 1
344 350 text0,text = text,lsplit
345 351 else:
346 352 has_protectables = 0
347 353 text = os.path.expanduser(text)
348 354
349 355 if text == "":
350 356 return [protect_filename(f) for f in self.glob("*")]
351 357
352 358 m0 = self.clean_glob(text.replace('\\',''))
353 359 if has_protectables:
354 360 # If we had protectables, we need to revert our changes to the
355 361 # beginning of filename so that we don't double-write the part
356 362 # of the filename we have so far
357 363 len_lsplit = len(lsplit)
358 364 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
359 365 else:
360 366 if open_quotes:
361 367 # if we have a string with an open quote, we don't need to
362 368 # protect the names at all (and we _shouldn't_, as it
363 369 # would cause bugs when the filesystem call is made).
364 370 matches = m0
365 371 else:
366 372 matches = [protect_filename(f) for f in m0]
367 373 if len(matches) == 1 and os.path.isdir(matches[0]):
368 374 # Takes care of links to directories also. Use '/'
369 375 # explicitly, even under Windows, so that name completions
370 376 # don't end up escaped.
371 377 matches[0] += '/'
372 378 return matches
373 379
374 380 def alias_matches(self, text):
375 381 """Match internal system aliases"""
376 382 #print 'Completer->alias_matches:',text # dbg
377 383 text = os.path.expanduser(text)
378 384 aliases = self.alias_table.keys()
379 385 if text == "":
380 386 return aliases
381 387 else:
382 388 return [alias for alias in aliases if alias.startswith(text)]
383 389
384 390 def python_matches(self,text):
385 391 """Match attributes or global python names"""
386 392 #print 'Completer->python_matches' # dbg
387 393 if "." in text:
388 394 try:
389 395 matches = self.attr_matches(text)
390 396 if text.endswith('.') and self.omit__names:
391 397 if self.omit__names == 1:
392 398 # true if txt is _not_ a __ name, false otherwise:
393 399 no__name = (lambda txt:
394 400 re.match(r'.*\.__.*?__',txt) is None)
395 401 else:
396 402 # true if txt is _not_ a _ name, false otherwise:
397 403 no__name = (lambda txt:
398 404 re.match(r'.*\._.*?',txt) is None)
399 405 matches = filter(no__name, matches)
400 406 except NameError:
401 407 # catches <undefined attributes>.<tab>
402 408 matches = []
403 409 else:
404 410 matches = self.global_matches(text)
405 411 # this is so completion finds magics when automagic is on:
406 412 if matches == [] and not text.startswith(os.sep):
407 413 matches = self.attr_matches(self.magic_prefix+text)
408 414 return matches
409 415
410 416 def _default_arguments(self, obj):
411 417 """Return the list of default arguments of obj if it is callable,
412 418 or empty list otherwise."""
413 419
414 420 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
415 421 # for classes, check for __init__,__new__
416 422 if inspect.isclass(obj):
417 423 obj = (getattr(obj,'__init__',None) or
418 424 getattr(obj,'__new__',None))
419 425 # for all others, check if they are __call__able
420 426 elif hasattr(obj, '__call__'):
421 427 obj = obj.__call__
422 428 # XXX: is there a way to handle the builtins ?
423 429 try:
424 430 args,_,_1,defaults = inspect.getargspec(obj)
425 431 if defaults:
426 432 return args[-len(defaults):]
427 433 except TypeError: pass
428 434 return []
429 435
430 436 def python_func_kw_matches(self,text):
431 437 """Match named parameters (kwargs) of the last open function"""
432 438
433 439 if "." in text: # a parameter cannot be dotted
434 440 return []
435 441 try: regexp = self.__funcParamsRegex
436 442 except AttributeError:
437 443 regexp = self.__funcParamsRegex = re.compile(r'''
438 444 '.*?' | # single quoted strings or
439 445 ".*?" | # double quoted strings or
440 446 \w+ | # identifier
441 447 \S # other characters
442 448 ''', re.VERBOSE | re.DOTALL)
443 449 # 1. find the nearest identifier that comes before an unclosed
444 450 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
445 451 tokens = regexp.findall(self.get_line_buffer())
446 452 tokens.reverse()
447 453 iterTokens = iter(tokens); openPar = 0
448 454 for token in iterTokens:
449 455 if token == ')':
450 456 openPar -= 1
451 457 elif token == '(':
452 458 openPar += 1
453 459 if openPar > 0:
454 460 # found the last unclosed parenthesis
455 461 break
456 462 else:
457 463 return []
458 464 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
459 465 ids = []
460 466 isId = re.compile(r'\w+$').match
461 467 while True:
462 468 try:
463 469 ids.append(iterTokens.next())
464 470 if not isId(ids[-1]):
465 471 ids.pop(); break
466 472 if not iterTokens.next() == '.':
467 473 break
468 474 except StopIteration:
469 475 break
470 476 # lookup the candidate callable matches either using global_matches
471 477 # or attr_matches for dotted names
472 478 if len(ids) == 1:
473 479 callableMatches = self.global_matches(ids[0])
474 480 else:
475 481 callableMatches = self.attr_matches('.'.join(ids[::-1]))
476 482 argMatches = []
477 483 for callableMatch in callableMatches:
478 484 try: namedArgs = self._default_arguments(eval(callableMatch,
479 485 self.namespace))
480 486 except: continue
481 487 for namedArg in namedArgs:
482 488 if namedArg.startswith(text):
483 489 argMatches.append("%s=" %namedArg)
484 490 return argMatches
485 491
486 492 def complete(self, text, state):
487 493 """Return the next possible completion for 'text'.
488 494
489 495 This is called successively with state == 0, 1, 2, ... until it
490 496 returns None. The completion should begin with 'text'. """
491 497
492 498 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
493 499
494 500 # if there is only a tab on a line with only whitespace, instead
495 501 # of the mostly useless 'do you want to see all million
496 502 # completions' message, just do the right thing and give the user
497 503 # his tab! Incidentally, this enables pasting of tabbed text from
498 504 # an editor (as long as autoindent is off).
499 if not self.get_line_buffer().strip():
505
506 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
507 # don't interfere with their own tab-completion mechanism.
508 if not (self.dumb_terminal or self.get_line_buffer().strip()):
500 509 self.readline.insert_text('\t')
501 510 return None
502 511
503 512 magic_escape = self.magic_escape
504 513 magic_prefix = self.magic_prefix
505 514
506 515 try:
507 516 if text.startswith(magic_escape):
508 517 text = text.replace(magic_escape,magic_prefix)
509 518 elif text.startswith('~'):
510 519 text = os.path.expanduser(text)
511 520 if state == 0:
512 521 # Extend the list of completions with the results of each
513 522 # matcher, so we return results to the user from all
514 523 # namespaces.
515 524 if self.merge_completions:
516 525 self.matches = []
517 526 for matcher in self.matchers:
518 527 self.matches.extend(matcher(text))
519 528 else:
520 529 for matcher in self.matchers:
521 530 self.matches = matcher(text)
522 531 if self.matches:
523 532 break
524 533
525 534 try:
526 535 return self.matches[state].replace(magic_prefix,magic_escape)
527 536 except IndexError:
528 537 return None
529 538 except:
530 539 #from IPython.ultraTB import AutoFormattedTB; # dbg
531 540 #tb=AutoFormattedTB('Verbose');tb() #dbg
532 541
533 542 # If completion fails, don't annoy the user.
534 543 return None
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