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