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