##// END OF EJS Templates
result_display can return value. ipapi.is_ipython_session(). %paste -> %cpaste.
vivainio -
Show More

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

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