##// END OF EJS Templates
GetoptErrors when invoking magics etc. with wrong args ...
vivainio -
Show More

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

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