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