##// END OF EJS Templates
Fix latex formatting of docstrings, patch by Stefan van der Walt...
fperez -
Show More

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

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