##// END OF EJS Templates
Added %paste magic
vivainio -
Show More

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

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