##// END OF EJS Templates
remove ipconfig and %config
vivainio -
Show More
@@ -1,3075 +1,3027 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 1933 2006-11-26 19:53:32Z vivainio $"""
4 $Id: Magic.py 1934 2006-11-26 20:37:01Z vivainio $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 import textwrap
35 35 from cStringIO import StringIO
36 36 from getopt import getopt,GetoptError
37 37 from pprint import pprint, pformat
38 38
39 39 # cProfile was added in Python2.5
40 40 try:
41 41 import cProfile as profile
42 42 import pstats
43 43 except ImportError:
44 44 # profile isn't bundled by default in Debian for license reasons
45 45 try:
46 46 import profile,pstats
47 47 except ImportError:
48 48 profile = pstats = None
49 49
50 50 # Homebrewed
51 51 import IPython
52 52 from IPython import Debugger, OInspect, wildcard
53 53 from IPython.FakeModule import FakeModule
54 54 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 55 from IPython.PyColorize import Parser
56 56 from IPython.ipstruct import Struct
57 57 from IPython.macro import Macro
58 58 from IPython.genutils import *
59 59 from IPython import platutils
60 60
61 61 #***************************************************************************
62 62 # Utility functions
63 63 def on_off(tag):
64 64 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
65 65 return ['OFF','ON'][tag]
66 66
67 67 class Bunch: pass
68 68
69 69 #***************************************************************************
70 70 # Main class implementing Magic functionality
71 71 class Magic:
72 72 """Magic functions for InteractiveShell.
73 73
74 74 Shell functions which can be reached as %function_name. All magic
75 75 functions should accept a string, which they can parse for their own
76 76 needs. This can make some functions easier to type, eg `%cd ../`
77 77 vs. `%cd("../")`
78 78
79 79 ALL definitions MUST begin with the prefix magic_. The user won't need it
80 80 at the command line, but it is is needed in the definition. """
81 81
82 82 # class globals
83 83 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
84 84 'Automagic is ON, % prefix NOT needed for magic functions.']
85 85
86 86 #......................................................................
87 87 # some utility functions
88 88
89 89 def __init__(self,shell):
90 90
91 91 self.options_table = {}
92 92 if profile is None:
93 93 self.magic_prun = self.profile_missing_notice
94 94 self.shell = shell
95 95
96 96 # namespace for holding state we may need
97 97 self._magic_state = Bunch()
98 98
99 99 def profile_missing_notice(self, *args, **kwargs):
100 100 error("""\
101 101 The profile module could not be found. If you are a Debian user,
102 102 it has been removed from the standard Debian package because of its non-free
103 103 license. To use profiling, please install"python2.3-profiler" from non-free.""")
104 104
105 105 def default_option(self,fn,optstr):
106 106 """Make an entry in the options_table for fn, with value optstr"""
107 107
108 108 if fn not in self.lsmagic():
109 109 error("%s is not a magic function" % fn)
110 110 self.options_table[fn] = optstr
111 111
112 112 def lsmagic(self):
113 113 """Return a list of currently available magic functions.
114 114
115 115 Gives a list of the bare names after mangling (['ls','cd', ...], not
116 116 ['magic_ls','magic_cd',...]"""
117 117
118 118 # FIXME. This needs a cleanup, in the way the magics list is built.
119 119
120 120 # magics in class definition
121 121 class_magic = lambda fn: fn.startswith('magic_') and \
122 122 callable(Magic.__dict__[fn])
123 123 # in instance namespace (run-time user additions)
124 124 inst_magic = lambda fn: fn.startswith('magic_') and \
125 125 callable(self.__dict__[fn])
126 126 # and bound magics by user (so they can access self):
127 127 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
128 128 callable(self.__class__.__dict__[fn])
129 129 magics = filter(class_magic,Magic.__dict__.keys()) + \
130 130 filter(inst_magic,self.__dict__.keys()) + \
131 131 filter(inst_bound_magic,self.__class__.__dict__.keys())
132 132 out = []
133 133 for fn in magics:
134 134 out.append(fn.replace('magic_','',1))
135 135 out.sort()
136 136 return out
137 137
138 138 def extract_input_slices(self,slices,raw=False):
139 139 """Return as a string a set of input history slices.
140 140
141 141 Inputs:
142 142
143 143 - slices: the set of slices is given as a list of strings (like
144 144 ['1','4:8','9'], since this function is for use by magic functions
145 145 which get their arguments as strings.
146 146
147 147 Optional inputs:
148 148
149 149 - raw(False): by default, the processed input is used. If this is
150 150 true, the raw input history is used instead.
151 151
152 152 Note that slices can be called with two notations:
153 153
154 154 N:M -> standard python form, means including items N...(M-1).
155 155
156 156 N-M -> include items N..M (closed endpoint)."""
157 157
158 158 if raw:
159 159 hist = self.shell.input_hist_raw
160 160 else:
161 161 hist = self.shell.input_hist
162 162
163 163 cmds = []
164 164 for chunk in slices:
165 165 if ':' in chunk:
166 166 ini,fin = map(int,chunk.split(':'))
167 167 elif '-' in chunk:
168 168 ini,fin = map(int,chunk.split('-'))
169 169 fin += 1
170 170 else:
171 171 ini = int(chunk)
172 172 fin = ini+1
173 173 cmds.append(hist[ini:fin])
174 174 return cmds
175 175
176 176 def _ofind(self, oname, namespaces=None):
177 177 """Find an object in the available namespaces.
178 178
179 179 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
180 180
181 181 Has special code to detect magic functions.
182 182 """
183 183
184 184 oname = oname.strip()
185 185
186 186 alias_ns = None
187 187 if namespaces is None:
188 188 # Namespaces to search in:
189 189 # Put them in a list. The order is important so that we
190 190 # find things in the same order that Python finds them.
191 191 namespaces = [ ('Interactive', self.shell.user_ns),
192 192 ('IPython internal', self.shell.internal_ns),
193 193 ('Python builtin', __builtin__.__dict__),
194 194 ('Alias', self.shell.alias_table),
195 195 ]
196 196 alias_ns = self.shell.alias_table
197 197
198 198 # initialize results to 'null'
199 199 found = 0; obj = None; ospace = None; ds = None;
200 200 ismagic = 0; isalias = 0; parent = None
201 201
202 202 # Look for the given name by splitting it in parts. If the head is
203 203 # found, then we look for all the remaining parts as members, and only
204 204 # declare success if we can find them all.
205 205 oname_parts = oname.split('.')
206 206 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
207 207 for nsname,ns in namespaces:
208 208 try:
209 209 obj = ns[oname_head]
210 210 except KeyError:
211 211 continue
212 212 else:
213 213 for part in oname_rest:
214 214 try:
215 215 parent = obj
216 216 obj = getattr(obj,part)
217 217 except:
218 218 # Blanket except b/c some badly implemented objects
219 219 # allow __getattr__ to raise exceptions other than
220 220 # AttributeError, which then crashes IPython.
221 221 break
222 222 else:
223 223 # If we finish the for loop (no break), we got all members
224 224 found = 1
225 225 ospace = nsname
226 226 if ns == alias_ns:
227 227 isalias = 1
228 228 break # namespace loop
229 229
230 230 # Try to see if it's magic
231 231 if not found:
232 232 if oname.startswith(self.shell.ESC_MAGIC):
233 233 oname = oname[1:]
234 234 obj = getattr(self,'magic_'+oname,None)
235 235 if obj is not None:
236 236 found = 1
237 237 ospace = 'IPython internal'
238 238 ismagic = 1
239 239
240 240 # Last try: special-case some literals like '', [], {}, etc:
241 241 if not found and oname_head in ["''",'""','[]','{}','()']:
242 242 obj = eval(oname_head)
243 243 found = 1
244 244 ospace = 'Interactive'
245 245
246 246 return {'found':found, 'obj':obj, 'namespace':ospace,
247 247 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
248 248
249 249 def arg_err(self,func):
250 250 """Print docstring if incorrect arguments were passed"""
251 251 print 'Error in arguments:'
252 252 print OInspect.getdoc(func)
253 253
254 254 def format_latex(self,strng):
255 255 """Format a string for latex inclusion."""
256 256
257 257 # Characters that need to be escaped for latex:
258 258 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
259 259 # Magic command names as headers:
260 260 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
261 261 re.MULTILINE)
262 262 # Magic commands
263 263 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
264 264 re.MULTILINE)
265 265 # Paragraph continue
266 266 par_re = re.compile(r'\\$',re.MULTILINE)
267 267
268 268 # The "\n" symbol
269 269 newline_re = re.compile(r'\\n')
270 270
271 271 # Now build the string for output:
272 272 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
273 273 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
274 274 strng)
275 275 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
276 276 strng = par_re.sub(r'\\\\',strng)
277 277 strng = escape_re.sub(r'\\\1',strng)
278 278 strng = newline_re.sub(r'\\textbackslash{}n',strng)
279 279 return strng
280 280
281 281 def format_screen(self,strng):
282 282 """Format a string for screen printing.
283 283
284 284 This removes some latex-type format codes."""
285 285 # Paragraph continue
286 286 par_re = re.compile(r'\\$',re.MULTILINE)
287 287 strng = par_re.sub('',strng)
288 288 return strng
289 289
290 290 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
291 291 """Parse options passed to an argument string.
292 292
293 293 The interface is similar to that of getopt(), but it returns back a
294 294 Struct with the options as keys and the stripped argument string still
295 295 as a string.
296 296
297 297 arg_str is quoted as a true sys.argv vector by using shlex.split.
298 298 This allows us to easily expand variables, glob files, quote
299 299 arguments, etc.
300 300
301 301 Options:
302 302 -mode: default 'string'. If given as 'list', the argument string is
303 303 returned as a list (split on whitespace) instead of a string.
304 304
305 305 -list_all: put all option values in lists. Normally only options
306 306 appearing more than once are put in a list.
307 307
308 308 -posix (True): whether to split the input line in POSIX mode or not,
309 309 as per the conventions outlined in the shlex module from the
310 310 standard library."""
311 311
312 312 # inject default options at the beginning of the input line
313 313 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
314 314 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
315 315
316 316 mode = kw.get('mode','string')
317 317 if mode not in ['string','list']:
318 318 raise ValueError,'incorrect mode given: %s' % mode
319 319 # Get options
320 320 list_all = kw.get('list_all',0)
321 321 posix = kw.get('posix',True)
322 322
323 323 # Check if we have more than one argument to warrant extra processing:
324 324 odict = {} # Dictionary with options
325 325 args = arg_str.split()
326 326 if len(args) >= 1:
327 327 # If the list of inputs only has 0 or 1 thing in it, there's no
328 328 # need to look for options
329 329 argv = arg_split(arg_str,posix)
330 330 # Do regular option processing
331 331 try:
332 332 opts,args = getopt(argv,opt_str,*long_opts)
333 333 except GetoptError,e:
334 334 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
335 335 " ".join(long_opts)))
336 336 for o,a in opts:
337 337 if o.startswith('--'):
338 338 o = o[2:]
339 339 else:
340 340 o = o[1:]
341 341 try:
342 342 odict[o].append(a)
343 343 except AttributeError:
344 344 odict[o] = [odict[o],a]
345 345 except KeyError:
346 346 if list_all:
347 347 odict[o] = [a]
348 348 else:
349 349 odict[o] = a
350 350
351 351 # Prepare opts,args for return
352 352 opts = Struct(odict)
353 353 if mode == 'string':
354 354 args = ' '.join(args)
355 355
356 356 return opts,args
357 357
358 358 #......................................................................
359 359 # And now the actual magic functions
360 360
361 361 # Functions for IPython shell work (vars,funcs, config, etc)
362 362 def magic_lsmagic(self, parameter_s = ''):
363 363 """List currently available magic functions."""
364 364 mesc = self.shell.ESC_MAGIC
365 365 print 'Available magic functions:\n'+mesc+\
366 366 (' '+mesc).join(self.lsmagic())
367 367 print '\n' + Magic.auto_status[self.shell.rc.automagic]
368 368 return None
369 369
370 370 def magic_magic(self, parameter_s = ''):
371 371 """Print information about the magic function system."""
372 372
373 373 mode = ''
374 374 try:
375 375 if parameter_s.split()[0] == '-latex':
376 376 mode = 'latex'
377 377 if parameter_s.split()[0] == '-brief':
378 378 mode = 'brief'
379 379 except:
380 380 pass
381 381
382 382 magic_docs = []
383 383 for fname in self.lsmagic():
384 384 mname = 'magic_' + fname
385 385 for space in (Magic,self,self.__class__):
386 386 try:
387 387 fn = space.__dict__[mname]
388 388 except KeyError:
389 389 pass
390 390 else:
391 391 break
392 392 if mode == 'brief':
393 393 # only first line
394 394 fndoc = fn.__doc__.split('\n',1)[0]
395 395 else:
396 396 fndoc = fn.__doc__
397 397
398 398 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
399 399 fname,fndoc))
400 400 magic_docs = ''.join(magic_docs)
401 401
402 402 if mode == 'latex':
403 403 print self.format_latex(magic_docs)
404 404 return
405 405 else:
406 406 magic_docs = self.format_screen(magic_docs)
407 407 if mode == 'brief':
408 408 return magic_docs
409 409
410 410 outmsg = """
411 411 IPython's 'magic' functions
412 412 ===========================
413 413
414 414 The magic function system provides a series of functions which allow you to
415 415 control the behavior of IPython itself, plus a lot of system-type
416 416 features. All these functions are prefixed with a % character, but parameters
417 417 are given without parentheses or quotes.
418 418
419 419 NOTE: If you have 'automagic' enabled (via the command line option or with the
420 420 %automagic function), you don't need to type in the % explicitly. By default,
421 421 IPython ships with automagic on, so you should only rarely need the % escape.
422 422
423 423 Example: typing '%cd mydir' (without the quotes) changes you working directory
424 424 to 'mydir', if it exists.
425 425
426 426 You can define your own magic functions to extend the system. See the supplied
427 427 ipythonrc and example-magic.py files for details (in your ipython
428 428 configuration directory, typically $HOME/.ipython/).
429 429
430 430 You can also define your own aliased names for magic functions. In your
431 431 ipythonrc file, placing a line like:
432 432
433 433 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
434 434
435 435 will define %pf as a new name for %profile.
436 436
437 437 You can also call magics in code using the ipmagic() function, which IPython
438 438 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
439 439
440 440 For a list of the available magic functions, use %lsmagic. For a description
441 441 of any of them, type %magic_name?, e.g. '%cd?'.
442 442
443 443 Currently the magic system has the following functions:\n"""
444 444
445 445 mesc = self.shell.ESC_MAGIC
446 446 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
447 447 "\n\n%s%s\n\n%s" % (outmsg,
448 448 magic_docs,mesc,mesc,
449 449 (' '+mesc).join(self.lsmagic()),
450 450 Magic.auto_status[self.shell.rc.automagic] ) )
451 451
452 452 page(outmsg,screen_lines=self.shell.rc.screen_length)
453 453
454 454 def magic_automagic(self, parameter_s = ''):
455 455 """Make magic functions callable without having to type the initial %.
456 456
457 457 Toggles on/off (when off, you must call it as %automagic, of
458 458 course). Note that magic functions have lowest priority, so if there's
459 459 a variable whose name collides with that of a magic fn, automagic
460 460 won't work for that function (you get the variable instead). However,
461 461 if you delete the variable (del var), the previously shadowed magic
462 462 function becomes visible to automagic again."""
463 463
464 464 rc = self.shell.rc
465 465 rc.automagic = not rc.automagic
466 466 print '\n' + Magic.auto_status[rc.automagic]
467 467
468 468 def magic_autocall(self, parameter_s = ''):
469 469 """Make functions callable without having to type parentheses.
470 470
471 471 Usage:
472 472
473 473 %autocall [mode]
474 474
475 475 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
476 476 value is toggled on and off (remembering the previous state)."""
477 477
478 478 rc = self.shell.rc
479 479
480 480 if parameter_s:
481 481 arg = int(parameter_s)
482 482 else:
483 483 arg = 'toggle'
484 484
485 485 if not arg in (0,1,2,'toggle'):
486 486 error('Valid modes: (0->Off, 1->Smart, 2->Full')
487 487 return
488 488
489 489 if arg in (0,1,2):
490 490 rc.autocall = arg
491 491 else: # toggle
492 492 if rc.autocall:
493 493 self._magic_state.autocall_save = rc.autocall
494 494 rc.autocall = 0
495 495 else:
496 496 try:
497 497 rc.autocall = self._magic_state.autocall_save
498 498 except AttributeError:
499 499 rc.autocall = self._magic_state.autocall_save = 1
500 500
501 501 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
502 502
503 503 def magic_autoindent(self, parameter_s = ''):
504 504 """Toggle autoindent on/off (if available)."""
505 505
506 506 self.shell.set_autoindent()
507 507 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
508 508
509 509 def magic_system_verbose(self, parameter_s = ''):
510 510 """Set verbose printing of system calls.
511 511
512 512 If called without an argument, act as a toggle"""
513 513
514 514 if parameter_s:
515 515 val = bool(eval(parameter_s))
516 516 else:
517 517 val = None
518 518
519 519 self.shell.rc_set_toggle('system_verbose',val)
520 520 print "System verbose printing is:",\
521 521 ['OFF','ON'][self.shell.rc.system_verbose]
522 522
523 523 def magic_history(self, parameter_s = ''):
524 524 """Print input history (_i<n> variables), with most recent last.
525 525
526 526 %history -> print at most 40 inputs (some may be multi-line)\\
527 527 %history n -> print at most n inputs\\
528 528 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
529 529
530 530 Each input's number <n> is shown, and is accessible as the
531 531 automatically generated variable _i<n>. Multi-line statements are
532 532 printed starting at a new line for easy copy/paste.
533 533
534 534
535 535 Options:
536 536
537 537 -n: do NOT print line numbers. This is useful if you want to get a
538 538 printout of many lines which can be directly pasted into a text
539 539 editor.
540 540
541 541 This feature is only available if numbered prompts are in use.
542 542
543 543 -r: print the 'raw' history. IPython filters your input and
544 544 converts it all into valid Python source before executing it (things
545 545 like magics or aliases are turned into function calls, for
546 546 example). With this option, you'll see the unfiltered history
547 547 instead of the filtered version: '%cd /' will be seen as '%cd /'
548 548 instead of '_ip.magic("%cd /")'.
549 549 """
550 550
551 551 shell = self.shell
552 552 if not shell.outputcache.do_full_cache:
553 553 print 'This feature is only available if numbered prompts are in use.'
554 554 return
555 555 opts,args = self.parse_options(parameter_s,'nr',mode='list')
556 556
557 557 if opts.has_key('r'):
558 558 input_hist = shell.input_hist_raw
559 559 else:
560 560 input_hist = shell.input_hist
561 561
562 562 default_length = 40
563 563 if len(args) == 0:
564 564 final = len(input_hist)
565 565 init = max(1,final-default_length)
566 566 elif len(args) == 1:
567 567 final = len(input_hist)
568 568 init = max(1,final-int(args[0]))
569 569 elif len(args) == 2:
570 570 init,final = map(int,args)
571 571 else:
572 572 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
573 573 print self.magic_hist.__doc__
574 574 return
575 575 width = len(str(final))
576 576 line_sep = ['','\n']
577 577 print_nums = not opts.has_key('n')
578 578 for in_num in range(init,final):
579 579 inline = input_hist[in_num]
580 580 multiline = int(inline.count('\n') > 1)
581 581 if print_nums:
582 582 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
583 583 print inline,
584 584
585 585 def magic_hist(self, parameter_s=''):
586 586 """Alternate name for %history."""
587 587 return self.magic_history(parameter_s)
588 588
589 589 def magic_p(self, parameter_s=''):
590 590 """Just a short alias for Python's 'print'."""
591 591 exec 'print ' + parameter_s in self.shell.user_ns
592 592
593 593 def magic_r(self, parameter_s=''):
594 594 """Repeat previous input.
595 595
596 596 If given an argument, repeats the previous command which starts with
597 597 the same string, otherwise it just repeats the previous input.
598 598
599 599 Shell escaped commands (with ! as first character) are not recognized
600 600 by this system, only pure python code and magic commands.
601 601 """
602 602
603 603 start = parameter_s.strip()
604 604 esc_magic = self.shell.ESC_MAGIC
605 605 # Identify magic commands even if automagic is on (which means
606 606 # the in-memory version is different from that typed by the user).
607 607 if self.shell.rc.automagic:
608 608 start_magic = esc_magic+start
609 609 else:
610 610 start_magic = start
611 611 # Look through the input history in reverse
612 612 for n in range(len(self.shell.input_hist)-2,0,-1):
613 613 input = self.shell.input_hist[n]
614 614 # skip plain 'r' lines so we don't recurse to infinity
615 615 if input != '_ip.magic("r")\n' and \
616 616 (input.startswith(start) or input.startswith(start_magic)):
617 617 #print 'match',`input` # dbg
618 618 print 'Executing:',input,
619 619 self.shell.runlines(input)
620 620 return
621 621 print 'No previous input matching `%s` found.' % start
622 622
623 623 def magic_page(self, parameter_s=''):
624 624 """Pretty print the object and display it through a pager.
625 625
626 626 %page [options] OBJECT
627 627
628 628 If no object is given, use _ (last output).
629 629
630 630 Options:
631 631
632 632 -r: page str(object), don't pretty-print it."""
633 633
634 634 # After a function contributed by Olivier Aubert, slightly modified.
635 635
636 636 # Process options/args
637 637 opts,args = self.parse_options(parameter_s,'r')
638 638 raw = 'r' in opts
639 639
640 640 oname = args and args or '_'
641 641 info = self._ofind(oname)
642 642 if info['found']:
643 643 txt = (raw and str or pformat)( info['obj'] )
644 644 page(txt)
645 645 else:
646 646 print 'Object `%s` not found' % oname
647 647
648 648 def magic_profile(self, parameter_s=''):
649 649 """Print your currently active IPyhton profile."""
650 650 if self.shell.rc.profile:
651 651 printpl('Current IPython profile: $self.shell.rc.profile.')
652 652 else:
653 653 print 'No profile active.'
654 654
655 655 def _inspect(self,meth,oname,namespaces=None,**kw):
656 656 """Generic interface to the inspector system.
657 657
658 658 This function is meant to be called by pdef, pdoc & friends."""
659 659
660 660 oname = oname.strip()
661 661 info = Struct(self._ofind(oname, namespaces))
662 662
663 663 if info.found:
664 664 # Get the docstring of the class property if it exists.
665 665 path = oname.split('.')
666 666 root = '.'.join(path[:-1])
667 667 if info.parent is not None:
668 668 try:
669 669 target = getattr(info.parent, '__class__')
670 670 # The object belongs to a class instance.
671 671 try:
672 672 target = getattr(target, path[-1])
673 673 # The class defines the object.
674 674 if isinstance(target, property):
675 675 oname = root + '.__class__.' + path[-1]
676 676 info = Struct(self._ofind(oname))
677 677 except AttributeError: pass
678 678 except AttributeError: pass
679 679
680 680 pmethod = getattr(self.shell.inspector,meth)
681 681 formatter = info.ismagic and self.format_screen or None
682 682 if meth == 'pdoc':
683 683 pmethod(info.obj,oname,formatter)
684 684 elif meth == 'pinfo':
685 685 pmethod(info.obj,oname,formatter,info,**kw)
686 686 else:
687 687 pmethod(info.obj,oname)
688 688 else:
689 689 print 'Object `%s` not found.' % oname
690 690 return 'not found' # so callers can take other action
691 691
692 692 def magic_pdef(self, parameter_s='', namespaces=None):
693 693 """Print the definition header for any callable object.
694 694
695 695 If the object is a class, print the constructor information."""
696 696 print "+++"
697 697 self._inspect('pdef',parameter_s, namespaces)
698 698
699 699 def magic_pdoc(self, parameter_s='', namespaces=None):
700 700 """Print the docstring for an object.
701 701
702 702 If the given object is a class, it will print both the class and the
703 703 constructor docstrings."""
704 704 self._inspect('pdoc',parameter_s, namespaces)
705 705
706 706 def magic_psource(self, parameter_s='', namespaces=None):
707 707 """Print (or run through pager) the source code for an object."""
708 708 self._inspect('psource',parameter_s, namespaces)
709 709
710 710 def magic_pfile(self, parameter_s=''):
711 711 """Print (or run through pager) the file where an object is defined.
712 712
713 713 The file opens at the line where the object definition begins. IPython
714 714 will honor the environment variable PAGER if set, and otherwise will
715 715 do its best to print the file in a convenient form.
716 716
717 717 If the given argument is not an object currently defined, IPython will
718 718 try to interpret it as a filename (automatically adding a .py extension
719 719 if needed). You can thus use %pfile as a syntax highlighting code
720 720 viewer."""
721 721
722 722 # first interpret argument as an object name
723 723 out = self._inspect('pfile',parameter_s)
724 724 # if not, try the input as a filename
725 725 if out == 'not found':
726 726 try:
727 727 filename = get_py_filename(parameter_s)
728 728 except IOError,msg:
729 729 print msg
730 730 return
731 731 page(self.shell.inspector.format(file(filename).read()))
732 732
733 733 def magic_pinfo(self, parameter_s='', namespaces=None):
734 734 """Provide detailed information about an object.
735 735
736 736 '%pinfo object' is just a synonym for object? or ?object."""
737 737
738 738 #print 'pinfo par: <%s>' % parameter_s # dbg
739 739
740 740 # detail_level: 0 -> obj? , 1 -> obj??
741 741 detail_level = 0
742 742 # We need to detect if we got called as 'pinfo pinfo foo', which can
743 743 # happen if the user types 'pinfo foo?' at the cmd line.
744 744 pinfo,qmark1,oname,qmark2 = \
745 745 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
746 746 if pinfo or qmark1 or qmark2:
747 747 detail_level = 1
748 748 if "*" in oname:
749 749 self.magic_psearch(oname)
750 750 else:
751 751 self._inspect('pinfo', oname, detail_level=detail_level,
752 752 namespaces=namespaces)
753 753
754 754 def magic_psearch(self, parameter_s=''):
755 755 """Search for object in namespaces by wildcard.
756 756
757 757 %psearch [options] PATTERN [OBJECT TYPE]
758 758
759 759 Note: ? can be used as a synonym for %psearch, at the beginning or at
760 760 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
761 761 rest of the command line must be unchanged (options come first), so
762 762 for example the following forms are equivalent
763 763
764 764 %psearch -i a* function
765 765 -i a* function?
766 766 ?-i a* function
767 767
768 768 Arguments:
769 769
770 770 PATTERN
771 771
772 772 where PATTERN is a string containing * as a wildcard similar to its
773 773 use in a shell. The pattern is matched in all namespaces on the
774 774 search path. By default objects starting with a single _ are not
775 775 matched, many IPython generated objects have a single
776 776 underscore. The default is case insensitive matching. Matching is
777 777 also done on the attributes of objects and not only on the objects
778 778 in a module.
779 779
780 780 [OBJECT TYPE]
781 781
782 782 Is the name of a python type from the types module. The name is
783 783 given in lowercase without the ending type, ex. StringType is
784 784 written string. By adding a type here only objects matching the
785 785 given type are matched. Using all here makes the pattern match all
786 786 types (this is the default).
787 787
788 788 Options:
789 789
790 790 -a: makes the pattern match even objects whose names start with a
791 791 single underscore. These names are normally ommitted from the
792 792 search.
793 793
794 794 -i/-c: make the pattern case insensitive/sensitive. If neither of
795 795 these options is given, the default is read from your ipythonrc
796 796 file. The option name which sets this value is
797 797 'wildcards_case_sensitive'. If this option is not specified in your
798 798 ipythonrc file, IPython's internal default is to do a case sensitive
799 799 search.
800 800
801 801 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
802 802 specifiy can be searched in any of the following namespaces:
803 803 'builtin', 'user', 'user_global','internal', 'alias', where
804 804 'builtin' and 'user' are the search defaults. Note that you should
805 805 not use quotes when specifying namespaces.
806 806
807 807 'Builtin' contains the python module builtin, 'user' contains all
808 808 user data, 'alias' only contain the shell aliases and no python
809 809 objects, 'internal' contains objects used by IPython. The
810 810 'user_global' namespace is only used by embedded IPython instances,
811 811 and it contains module-level globals. You can add namespaces to the
812 812 search with -s or exclude them with -e (these options can be given
813 813 more than once).
814 814
815 815 Examples:
816 816
817 817 %psearch a* -> objects beginning with an a
818 818 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
819 819 %psearch a* function -> all functions beginning with an a
820 820 %psearch re.e* -> objects beginning with an e in module re
821 821 %psearch r*.e* -> objects that start with e in modules starting in r
822 822 %psearch r*.* string -> all strings in modules beginning with r
823 823
824 824 Case sensitve search:
825 825
826 826 %psearch -c a* list all object beginning with lower case a
827 827
828 828 Show objects beginning with a single _:
829 829
830 830 %psearch -a _* list objects beginning with a single underscore"""
831 831
832 832 # default namespaces to be searched
833 833 def_search = ['user','builtin']
834 834
835 835 # Process options/args
836 836 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
837 837 opt = opts.get
838 838 shell = self.shell
839 839 psearch = shell.inspector.psearch
840 840
841 841 # select case options
842 842 if opts.has_key('i'):
843 843 ignore_case = True
844 844 elif opts.has_key('c'):
845 845 ignore_case = False
846 846 else:
847 847 ignore_case = not shell.rc.wildcards_case_sensitive
848 848
849 849 # Build list of namespaces to search from user options
850 850 def_search.extend(opt('s',[]))
851 851 ns_exclude = ns_exclude=opt('e',[])
852 852 ns_search = [nm for nm in def_search if nm not in ns_exclude]
853 853
854 854 # Call the actual search
855 855 try:
856 856 psearch(args,shell.ns_table,ns_search,
857 857 show_all=opt('a'),ignore_case=ignore_case)
858 858 except:
859 859 shell.showtraceback()
860 860
861 861 def magic_who_ls(self, parameter_s=''):
862 862 """Return a sorted list of all interactive variables.
863 863
864 864 If arguments are given, only variables of types matching these
865 865 arguments are returned."""
866 866
867 867 user_ns = self.shell.user_ns
868 868 internal_ns = self.shell.internal_ns
869 869 user_config_ns = self.shell.user_config_ns
870 870 out = []
871 871 typelist = parameter_s.split()
872 872
873 873 for i in user_ns:
874 874 if not (i.startswith('_') or i.startswith('_i')) \
875 875 and not (i in internal_ns or i in user_config_ns):
876 876 if typelist:
877 877 if type(user_ns[i]).__name__ in typelist:
878 878 out.append(i)
879 879 else:
880 880 out.append(i)
881 881 out.sort()
882 882 return out
883 883
884 884 def magic_who(self, parameter_s=''):
885 885 """Print all interactive variables, with some minimal formatting.
886 886
887 887 If any arguments are given, only variables whose type matches one of
888 888 these are printed. For example:
889 889
890 890 %who function str
891 891
892 892 will only list functions and strings, excluding all other types of
893 893 variables. To find the proper type names, simply use type(var) at a
894 894 command line to see how python prints type names. For example:
895 895
896 896 In [1]: type('hello')\\
897 897 Out[1]: <type 'str'>
898 898
899 899 indicates that the type name for strings is 'str'.
900 900
901 901 %who always excludes executed names loaded through your configuration
902 902 file and things which are internal to IPython.
903 903
904 904 This is deliberate, as typically you may load many modules and the
905 905 purpose of %who is to show you only what you've manually defined."""
906 906
907 907 varlist = self.magic_who_ls(parameter_s)
908 908 if not varlist:
909 909 print 'Interactive namespace is empty.'
910 910 return
911 911
912 912 # if we have variables, move on...
913 913
914 914 # stupid flushing problem: when prompts have no separators, stdout is
915 915 # getting lost. I'm starting to think this is a python bug. I'm having
916 916 # to force a flush with a print because even a sys.stdout.flush
917 917 # doesn't seem to do anything!
918 918
919 919 count = 0
920 920 for i in varlist:
921 921 print i+'\t',
922 922 count += 1
923 923 if count > 8:
924 924 count = 0
925 925 print
926 926 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
927 927
928 928 print # well, this does force a flush at the expense of an extra \n
929 929
930 930 def magic_whos(self, parameter_s=''):
931 931 """Like %who, but gives some extra information about each variable.
932 932
933 933 The same type filtering of %who can be applied here.
934 934
935 935 For all variables, the type is printed. Additionally it prints:
936 936
937 937 - For {},[],(): their length.
938 938
939 939 - For Numeric arrays, a summary with shape, number of elements,
940 940 typecode and size in memory.
941 941
942 942 - Everything else: a string representation, snipping their middle if
943 943 too long."""
944 944
945 945 varnames = self.magic_who_ls(parameter_s)
946 946 if not varnames:
947 947 print 'Interactive namespace is empty.'
948 948 return
949 949
950 950 # if we have variables, move on...
951 951
952 952 # for these types, show len() instead of data:
953 953 seq_types = [types.DictType,types.ListType,types.TupleType]
954 954
955 955 # for Numeric arrays, display summary info
956 956 try:
957 957 import Numeric
958 958 except ImportError:
959 959 array_type = None
960 960 else:
961 961 array_type = Numeric.ArrayType.__name__
962 962
963 963 # Find all variable names and types so we can figure out column sizes
964 964 get_vars = lambda i: self.shell.user_ns[i]
965 965 type_name = lambda v: type(v).__name__
966 966 varlist = map(get_vars,varnames)
967 967
968 968 typelist = []
969 969 for vv in varlist:
970 970 tt = type_name(vv)
971 971 if tt=='instance':
972 972 typelist.append(str(vv.__class__))
973 973 else:
974 974 typelist.append(tt)
975 975
976 976 # column labels and # of spaces as separator
977 977 varlabel = 'Variable'
978 978 typelabel = 'Type'
979 979 datalabel = 'Data/Info'
980 980 colsep = 3
981 981 # variable format strings
982 982 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
983 983 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
984 984 aformat = "%s: %s elems, type `%s`, %s bytes"
985 985 # find the size of the columns to format the output nicely
986 986 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
987 987 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
988 988 # table header
989 989 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
990 990 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
991 991 # and the table itself
992 992 kb = 1024
993 993 Mb = 1048576 # kb**2
994 994 for vname,var,vtype in zip(varnames,varlist,typelist):
995 995 print itpl(vformat),
996 996 if vtype in seq_types:
997 997 print len(var)
998 998 elif vtype==array_type:
999 999 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1000 1000 vsize = Numeric.size(var)
1001 1001 vbytes = vsize*var.itemsize()
1002 1002 if vbytes < 100000:
1003 1003 print aformat % (vshape,vsize,var.typecode(),vbytes)
1004 1004 else:
1005 1005 print aformat % (vshape,vsize,var.typecode(),vbytes),
1006 1006 if vbytes < Mb:
1007 1007 print '(%s kb)' % (vbytes/kb,)
1008 1008 else:
1009 1009 print '(%s Mb)' % (vbytes/Mb,)
1010 1010 else:
1011 1011 vstr = str(var).replace('\n','\\n')
1012 1012 if len(vstr) < 50:
1013 1013 print vstr
1014 1014 else:
1015 1015 printpl(vfmt_short)
1016 1016
1017 1017 def magic_reset(self, parameter_s=''):
1018 1018 """Resets the namespace by removing all names defined by the user.
1019 1019
1020 1020 Input/Output history are left around in case you need them."""
1021 1021
1022 1022 ans = self.shell.ask_yes_no(
1023 1023 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1024 1024 if not ans:
1025 1025 print 'Nothing done.'
1026 1026 return
1027 1027 user_ns = self.shell.user_ns
1028 1028 for i in self.magic_who_ls():
1029 1029 del(user_ns[i])
1030 1030
1031 def magic_config(self,parameter_s=''):
1032 """Handle IPython's internal configuration.
1033
1034 If called without arguments, it will print IPython's complete internal
1035 configuration.
1036
1037 If called with one argument, it will print the value of that key in
1038 the configuration.
1039
1040 If called with more than one argument, the first is interpreted as a
1041 key and the rest as a Python expression which gets eval()'d.
1042
1043 Examples:
1044
1045 In [1]: s='A Python string'
1046
1047 In [2]: !echo $s
1048 A Python string
1049
1050 In [3]: config system_verbose True
1051
1052 In [4]: !echo $s
1053 IPython system call: echo A Python string
1054 A Python string
1055
1056 In [5]: %config system_header 'sys> '
1057
1058 In [6]: !echo $s
1059 sys> echo A Python string
1060 A Python string
1061
1062 # Notice the extra quotes to protect the string after interpolation:
1063 In [7]: header = "'sys2> '"
1064
1065 In [8]: %config system_header $header
1066
1067 In [9]: !echo $s
1068 sys2> echo A Python string
1069 A Python string
1070 """
1071
1072 args = parameter_s.split(None,1)
1073 key = args[0]
1074 if len(args)==1:
1075 self.shell.ipconfig(key)
1076 else:
1077 self.shell.ipconfig(key,eval(args[1]))
1078
1079 1031 def magic_logstart(self,parameter_s=''):
1080 1032 """Start logging anywhere in a session.
1081 1033
1082 1034 %logstart [-o|-r|-t] [log_name [log_mode]]
1083 1035
1084 1036 If no name is given, it defaults to a file named 'ipython_log.py' in your
1085 1037 current directory, in 'rotate' mode (see below).
1086 1038
1087 1039 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1088 1040 history up to that point and then continues logging.
1089 1041
1090 1042 %logstart takes a second optional parameter: logging mode. This can be one
1091 1043 of (note that the modes are given unquoted):\\
1092 1044 append: well, that says it.\\
1093 1045 backup: rename (if exists) to name~ and start name.\\
1094 1046 global: single logfile in your home dir, appended to.\\
1095 1047 over : overwrite existing log.\\
1096 1048 rotate: create rotating logs name.1~, name.2~, etc.
1097 1049
1098 1050 Options:
1099 1051
1100 1052 -o: log also IPython's output. In this mode, all commands which
1101 1053 generate an Out[NN] prompt are recorded to the logfile, right after
1102 1054 their corresponding input line. The output lines are always
1103 1055 prepended with a '#[Out]# ' marker, so that the log remains valid
1104 1056 Python code.
1105 1057
1106 1058 Since this marker is always the same, filtering only the output from
1107 1059 a log is very easy, using for example a simple awk call:
1108 1060
1109 1061 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1110 1062
1111 1063 -r: log 'raw' input. Normally, IPython's logs contain the processed
1112 1064 input, so that user lines are logged in their final form, converted
1113 1065 into valid Python. For example, %Exit is logged as
1114 1066 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1115 1067 exactly as typed, with no transformations applied.
1116 1068
1117 1069 -t: put timestamps before each input line logged (these are put in
1118 1070 comments)."""
1119 1071
1120 1072 opts,par = self.parse_options(parameter_s,'ort')
1121 1073 log_output = 'o' in opts
1122 1074 log_raw_input = 'r' in opts
1123 1075 timestamp = 't' in opts
1124 1076
1125 1077 rc = self.shell.rc
1126 1078 logger = self.shell.logger
1127 1079
1128 1080 # if no args are given, the defaults set in the logger constructor by
1129 1081 # ipytohn remain valid
1130 1082 if par:
1131 1083 try:
1132 1084 logfname,logmode = par.split()
1133 1085 except:
1134 1086 logfname = par
1135 1087 logmode = 'backup'
1136 1088 else:
1137 1089 logfname = logger.logfname
1138 1090 logmode = logger.logmode
1139 1091 # put logfname into rc struct as if it had been called on the command
1140 1092 # line, so it ends up saved in the log header Save it in case we need
1141 1093 # to restore it...
1142 1094 old_logfile = rc.opts.get('logfile','')
1143 1095 if logfname:
1144 1096 logfname = os.path.expanduser(logfname)
1145 1097 rc.opts.logfile = logfname
1146 1098 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1147 1099 try:
1148 1100 started = logger.logstart(logfname,loghead,logmode,
1149 1101 log_output,timestamp,log_raw_input)
1150 1102 except:
1151 1103 rc.opts.logfile = old_logfile
1152 1104 warn("Couldn't start log: %s" % sys.exc_info()[1])
1153 1105 else:
1154 1106 # log input history up to this point, optionally interleaving
1155 1107 # output if requested
1156 1108
1157 1109 if timestamp:
1158 1110 # disable timestamping for the previous history, since we've
1159 1111 # lost those already (no time machine here).
1160 1112 logger.timestamp = False
1161 1113
1162 1114 if log_raw_input:
1163 1115 input_hist = self.shell.input_hist_raw
1164 1116 else:
1165 1117 input_hist = self.shell.input_hist
1166 1118
1167 1119 if log_output:
1168 1120 log_write = logger.log_write
1169 1121 output_hist = self.shell.output_hist
1170 1122 for n in range(1,len(input_hist)-1):
1171 1123 log_write(input_hist[n].rstrip())
1172 1124 if n in output_hist:
1173 1125 log_write(repr(output_hist[n]),'output')
1174 1126 else:
1175 1127 logger.log_write(input_hist[1:])
1176 1128 if timestamp:
1177 1129 # re-enable timestamping
1178 1130 logger.timestamp = True
1179 1131
1180 1132 print ('Activating auto-logging. '
1181 1133 'Current session state plus future input saved.')
1182 1134 logger.logstate()
1183 1135
1184 1136 def magic_logoff(self,parameter_s=''):
1185 1137 """Temporarily stop logging.
1186 1138
1187 1139 You must have previously started logging."""
1188 1140 self.shell.logger.switch_log(0)
1189 1141
1190 1142 def magic_logon(self,parameter_s=''):
1191 1143 """Restart logging.
1192 1144
1193 1145 This function is for restarting logging which you've temporarily
1194 1146 stopped with %logoff. For starting logging for the first time, you
1195 1147 must use the %logstart function, which allows you to specify an
1196 1148 optional log filename."""
1197 1149
1198 1150 self.shell.logger.switch_log(1)
1199 1151
1200 1152 def magic_logstate(self,parameter_s=''):
1201 1153 """Print the status of the logging system."""
1202 1154
1203 1155 self.shell.logger.logstate()
1204 1156
1205 1157 def magic_pdb(self, parameter_s=''):
1206 1158 """Control the calling of the pdb interactive debugger.
1207 1159
1208 1160 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1209 1161 argument it works as a toggle.
1210 1162
1211 1163 When an exception is triggered, IPython can optionally call the
1212 1164 interactive pdb debugger after the traceback printout. %pdb toggles
1213 1165 this feature on and off."""
1214 1166
1215 1167 par = parameter_s.strip().lower()
1216 1168
1217 1169 if par:
1218 1170 try:
1219 1171 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1220 1172 except KeyError:
1221 1173 print ('Incorrect argument. Use on/1, off/0, '
1222 1174 'or nothing for a toggle.')
1223 1175 return
1224 1176 else:
1225 1177 # toggle
1226 1178 new_pdb = not self.shell.InteractiveTB.call_pdb
1227 1179
1228 1180 # set on the shell
1229 1181 self.shell.call_pdb = new_pdb
1230 1182 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1231 1183
1232 1184 def magic_prun(self, parameter_s ='',user_mode=1,
1233 1185 opts=None,arg_lst=None,prog_ns=None):
1234 1186
1235 1187 """Run a statement through the python code profiler.
1236 1188
1237 1189 Usage:\\
1238 1190 %prun [options] statement
1239 1191
1240 1192 The given statement (which doesn't require quote marks) is run via the
1241 1193 python profiler in a manner similar to the profile.run() function.
1242 1194 Namespaces are internally managed to work correctly; profile.run
1243 1195 cannot be used in IPython because it makes certain assumptions about
1244 1196 namespaces which do not hold under IPython.
1245 1197
1246 1198 Options:
1247 1199
1248 1200 -l <limit>: you can place restrictions on what or how much of the
1249 1201 profile gets printed. The limit value can be:
1250 1202
1251 1203 * A string: only information for function names containing this string
1252 1204 is printed.
1253 1205
1254 1206 * An integer: only these many lines are printed.
1255 1207
1256 1208 * A float (between 0 and 1): this fraction of the report is printed
1257 1209 (for example, use a limit of 0.4 to see the topmost 40% only).
1258 1210
1259 1211 You can combine several limits with repeated use of the option. For
1260 1212 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1261 1213 information about class constructors.
1262 1214
1263 1215 -r: return the pstats.Stats object generated by the profiling. This
1264 1216 object has all the information about the profile in it, and you can
1265 1217 later use it for further analysis or in other functions.
1266 1218
1267 1219 -s <key>: sort profile by given key. You can provide more than one key
1268 1220 by using the option several times: '-s key1 -s key2 -s key3...'. The
1269 1221 default sorting key is 'time'.
1270 1222
1271 1223 The following is copied verbatim from the profile documentation
1272 1224 referenced below:
1273 1225
1274 1226 When more than one key is provided, additional keys are used as
1275 1227 secondary criteria when the there is equality in all keys selected
1276 1228 before them.
1277 1229
1278 1230 Abbreviations can be used for any key names, as long as the
1279 1231 abbreviation is unambiguous. The following are the keys currently
1280 1232 defined:
1281 1233
1282 1234 Valid Arg Meaning\\
1283 1235 "calls" call count\\
1284 1236 "cumulative" cumulative time\\
1285 1237 "file" file name\\
1286 1238 "module" file name\\
1287 1239 "pcalls" primitive call count\\
1288 1240 "line" line number\\
1289 1241 "name" function name\\
1290 1242 "nfl" name/file/line\\
1291 1243 "stdname" standard name\\
1292 1244 "time" internal time
1293 1245
1294 1246 Note that all sorts on statistics are in descending order (placing
1295 1247 most time consuming items first), where as name, file, and line number
1296 1248 searches are in ascending order (i.e., alphabetical). The subtle
1297 1249 distinction between "nfl" and "stdname" is that the standard name is a
1298 1250 sort of the name as printed, which means that the embedded line
1299 1251 numbers get compared in an odd way. For example, lines 3, 20, and 40
1300 1252 would (if the file names were the same) appear in the string order
1301 1253 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1302 1254 line numbers. In fact, sort_stats("nfl") is the same as
1303 1255 sort_stats("name", "file", "line").
1304 1256
1305 1257 -T <filename>: save profile results as shown on screen to a text
1306 1258 file. The profile is still shown on screen.
1307 1259
1308 1260 -D <filename>: save (via dump_stats) profile statistics to given
1309 1261 filename. This data is in a format understod by the pstats module, and
1310 1262 is generated by a call to the dump_stats() method of profile
1311 1263 objects. The profile is still shown on screen.
1312 1264
1313 1265 If you want to run complete programs under the profiler's control, use
1314 1266 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1315 1267 contains profiler specific options as described here.
1316 1268
1317 1269 You can read the complete documentation for the profile module with:\\
1318 1270 In [1]: import profile; profile.help() """
1319 1271
1320 1272 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1321 1273 # protect user quote marks
1322 1274 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1323 1275
1324 1276 if user_mode: # regular user call
1325 1277 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1326 1278 list_all=1)
1327 1279 namespace = self.shell.user_ns
1328 1280 else: # called to run a program by %run -p
1329 1281 try:
1330 1282 filename = get_py_filename(arg_lst[0])
1331 1283 except IOError,msg:
1332 1284 error(msg)
1333 1285 return
1334 1286
1335 1287 arg_str = 'execfile(filename,prog_ns)'
1336 1288 namespace = locals()
1337 1289
1338 1290 opts.merge(opts_def)
1339 1291
1340 1292 prof = profile.Profile()
1341 1293 try:
1342 1294 prof = prof.runctx(arg_str,namespace,namespace)
1343 1295 sys_exit = ''
1344 1296 except SystemExit:
1345 1297 sys_exit = """*** SystemExit exception caught in code being profiled."""
1346 1298
1347 1299 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1348 1300
1349 1301 lims = opts.l
1350 1302 if lims:
1351 1303 lims = [] # rebuild lims with ints/floats/strings
1352 1304 for lim in opts.l:
1353 1305 try:
1354 1306 lims.append(int(lim))
1355 1307 except ValueError:
1356 1308 try:
1357 1309 lims.append(float(lim))
1358 1310 except ValueError:
1359 1311 lims.append(lim)
1360 1312
1361 1313 # trap output
1362 1314 sys_stdout = sys.stdout
1363 1315 stdout_trap = StringIO()
1364 1316 try:
1365 1317 sys.stdout = stdout_trap
1366 1318 stats.print_stats(*lims)
1367 1319 finally:
1368 1320 sys.stdout = sys_stdout
1369 1321 output = stdout_trap.getvalue()
1370 1322 output = output.rstrip()
1371 1323
1372 1324 page(output,screen_lines=self.shell.rc.screen_length)
1373 1325 print sys_exit,
1374 1326
1375 1327 dump_file = opts.D[0]
1376 1328 text_file = opts.T[0]
1377 1329 if dump_file:
1378 1330 prof.dump_stats(dump_file)
1379 1331 print '\n*** Profile stats marshalled to file',\
1380 1332 `dump_file`+'.',sys_exit
1381 1333 if text_file:
1382 1334 file(text_file,'w').write(output)
1383 1335 print '\n*** Profile printout saved to text file',\
1384 1336 `text_file`+'.',sys_exit
1385 1337
1386 1338 if opts.has_key('r'):
1387 1339 return stats
1388 1340 else:
1389 1341 return None
1390 1342
1391 1343 def magic_run(self, parameter_s ='',runner=None):
1392 1344 """Run the named file inside IPython as a program.
1393 1345
1394 1346 Usage:\\
1395 1347 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1396 1348
1397 1349 Parameters after the filename are passed as command-line arguments to
1398 1350 the program (put in sys.argv). Then, control returns to IPython's
1399 1351 prompt.
1400 1352
1401 1353 This is similar to running at a system prompt:\\
1402 1354 $ python file args\\
1403 1355 but with the advantage of giving you IPython's tracebacks, and of
1404 1356 loading all variables into your interactive namespace for further use
1405 1357 (unless -p is used, see below).
1406 1358
1407 1359 The file is executed in a namespace initially consisting only of
1408 1360 __name__=='__main__' and sys.argv constructed as indicated. It thus
1409 1361 sees its environment as if it were being run as a stand-alone
1410 1362 program. But after execution, the IPython interactive namespace gets
1411 1363 updated with all variables defined in the program (except for __name__
1412 1364 and sys.argv). This allows for very convenient loading of code for
1413 1365 interactive work, while giving each program a 'clean sheet' to run in.
1414 1366
1415 1367 Options:
1416 1368
1417 1369 -n: __name__ is NOT set to '__main__', but to the running file's name
1418 1370 without extension (as python does under import). This allows running
1419 1371 scripts and reloading the definitions in them without calling code
1420 1372 protected by an ' if __name__ == "__main__" ' clause.
1421 1373
1422 1374 -i: run the file in IPython's namespace instead of an empty one. This
1423 1375 is useful if you are experimenting with code written in a text editor
1424 1376 which depends on variables defined interactively.
1425 1377
1426 1378 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1427 1379 being run. This is particularly useful if IPython is being used to
1428 1380 run unittests, which always exit with a sys.exit() call. In such
1429 1381 cases you are interested in the output of the test results, not in
1430 1382 seeing a traceback of the unittest module.
1431 1383
1432 1384 -t: print timing information at the end of the run. IPython will give
1433 1385 you an estimated CPU time consumption for your script, which under
1434 1386 Unix uses the resource module to avoid the wraparound problems of
1435 1387 time.clock(). Under Unix, an estimate of time spent on system tasks
1436 1388 is also given (for Windows platforms this is reported as 0.0).
1437 1389
1438 1390 If -t is given, an additional -N<N> option can be given, where <N>
1439 1391 must be an integer indicating how many times you want the script to
1440 1392 run. The final timing report will include total and per run results.
1441 1393
1442 1394 For example (testing the script uniq_stable.py):
1443 1395
1444 1396 In [1]: run -t uniq_stable
1445 1397
1446 1398 IPython CPU timings (estimated):\\
1447 1399 User : 0.19597 s.\\
1448 1400 System: 0.0 s.\\
1449 1401
1450 1402 In [2]: run -t -N5 uniq_stable
1451 1403
1452 1404 IPython CPU timings (estimated):\\
1453 1405 Total runs performed: 5\\
1454 1406 Times : Total Per run\\
1455 1407 User : 0.910862 s, 0.1821724 s.\\
1456 1408 System: 0.0 s, 0.0 s.
1457 1409
1458 1410 -d: run your program under the control of pdb, the Python debugger.
1459 1411 This allows you to execute your program step by step, watch variables,
1460 1412 etc. Internally, what IPython does is similar to calling:
1461 1413
1462 1414 pdb.run('execfile("YOURFILENAME")')
1463 1415
1464 1416 with a breakpoint set on line 1 of your file. You can change the line
1465 1417 number for this automatic breakpoint to be <N> by using the -bN option
1466 1418 (where N must be an integer). For example:
1467 1419
1468 1420 %run -d -b40 myscript
1469 1421
1470 1422 will set the first breakpoint at line 40 in myscript.py. Note that
1471 1423 the first breakpoint must be set on a line which actually does
1472 1424 something (not a comment or docstring) for it to stop execution.
1473 1425
1474 1426 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1475 1427 first enter 'c' (without qoutes) to start execution up to the first
1476 1428 breakpoint.
1477 1429
1478 1430 Entering 'help' gives information about the use of the debugger. You
1479 1431 can easily see pdb's full documentation with "import pdb;pdb.help()"
1480 1432 at a prompt.
1481 1433
1482 1434 -p: run program under the control of the Python profiler module (which
1483 1435 prints a detailed report of execution times, function calls, etc).
1484 1436
1485 1437 You can pass other options after -p which affect the behavior of the
1486 1438 profiler itself. See the docs for %prun for details.
1487 1439
1488 1440 In this mode, the program's variables do NOT propagate back to the
1489 1441 IPython interactive namespace (because they remain in the namespace
1490 1442 where the profiler executes them).
1491 1443
1492 1444 Internally this triggers a call to %prun, see its documentation for
1493 1445 details on the options available specifically for profiling."""
1494 1446
1495 1447 # get arguments and set sys.argv for program to be run.
1496 1448 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1497 1449 mode='list',list_all=1)
1498 1450
1499 1451 try:
1500 1452 filename = get_py_filename(arg_lst[0])
1501 1453 except IndexError:
1502 1454 warn('you must provide at least a filename.')
1503 1455 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1504 1456 return
1505 1457 except IOError,msg:
1506 1458 error(msg)
1507 1459 return
1508 1460
1509 1461 # Control the response to exit() calls made by the script being run
1510 1462 exit_ignore = opts.has_key('e')
1511 1463
1512 1464 # Make sure that the running script gets a proper sys.argv as if it
1513 1465 # were run from a system shell.
1514 1466 save_argv = sys.argv # save it for later restoring
1515 1467 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1516 1468
1517 1469 if opts.has_key('i'):
1518 1470 prog_ns = self.shell.user_ns
1519 1471 __name__save = self.shell.user_ns['__name__']
1520 1472 prog_ns['__name__'] = '__main__'
1521 1473 else:
1522 1474 if opts.has_key('n'):
1523 1475 name = os.path.splitext(os.path.basename(filename))[0]
1524 1476 else:
1525 1477 name = '__main__'
1526 1478 prog_ns = {'__name__':name}
1527 1479
1528 1480 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1529 1481 # set the __file__ global in the script's namespace
1530 1482 prog_ns['__file__'] = filename
1531 1483
1532 1484 # pickle fix. See iplib for an explanation. But we need to make sure
1533 1485 # that, if we overwrite __main__, we replace it at the end
1534 1486 if prog_ns['__name__'] == '__main__':
1535 1487 restore_main = sys.modules['__main__']
1536 1488 else:
1537 1489 restore_main = False
1538 1490
1539 1491 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1540 1492
1541 1493 stats = None
1542 1494 try:
1543 1495 if self.shell.has_readline:
1544 1496 self.shell.savehist()
1545 1497
1546 1498 if opts.has_key('p'):
1547 1499 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1548 1500 else:
1549 1501 if opts.has_key('d'):
1550 1502 deb = Debugger.Pdb(self.shell.rc.colors)
1551 1503 # reset Breakpoint state, which is moronically kept
1552 1504 # in a class
1553 1505 bdb.Breakpoint.next = 1
1554 1506 bdb.Breakpoint.bplist = {}
1555 1507 bdb.Breakpoint.bpbynumber = [None]
1556 1508 # Set an initial breakpoint to stop execution
1557 1509 maxtries = 10
1558 1510 bp = int(opts.get('b',[1])[0])
1559 1511 checkline = deb.checkline(filename,bp)
1560 1512 if not checkline:
1561 1513 for bp in range(bp+1,bp+maxtries+1):
1562 1514 if deb.checkline(filename,bp):
1563 1515 break
1564 1516 else:
1565 1517 msg = ("\nI failed to find a valid line to set "
1566 1518 "a breakpoint\n"
1567 1519 "after trying up to line: %s.\n"
1568 1520 "Please set a valid breakpoint manually "
1569 1521 "with the -b option." % bp)
1570 1522 error(msg)
1571 1523 return
1572 1524 # if we find a good linenumber, set the breakpoint
1573 1525 deb.do_break('%s:%s' % (filename,bp))
1574 1526 # Start file run
1575 1527 print "NOTE: Enter 'c' at the",
1576 1528 print "%s prompt to start your script." % deb.prompt
1577 1529 try:
1578 1530 deb.run('execfile("%s")' % filename,prog_ns)
1579 1531
1580 1532 except:
1581 1533 etype, value, tb = sys.exc_info()
1582 1534 # Skip three frames in the traceback: the %run one,
1583 1535 # one inside bdb.py, and the command-line typed by the
1584 1536 # user (run by exec in pdb itself).
1585 1537 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1586 1538 else:
1587 1539 if runner is None:
1588 1540 runner = self.shell.safe_execfile
1589 1541 if opts.has_key('t'):
1590 1542 try:
1591 1543 nruns = int(opts['N'][0])
1592 1544 if nruns < 1:
1593 1545 error('Number of runs must be >=1')
1594 1546 return
1595 1547 except (KeyError):
1596 1548 nruns = 1
1597 1549 if nruns == 1:
1598 1550 t0 = clock2()
1599 1551 runner(filename,prog_ns,prog_ns,
1600 1552 exit_ignore=exit_ignore)
1601 1553 t1 = clock2()
1602 1554 t_usr = t1[0]-t0[0]
1603 1555 t_sys = t1[1]-t1[1]
1604 1556 print "\nIPython CPU timings (estimated):"
1605 1557 print " User : %10s s." % t_usr
1606 1558 print " System: %10s s." % t_sys
1607 1559 else:
1608 1560 runs = range(nruns)
1609 1561 t0 = clock2()
1610 1562 for nr in runs:
1611 1563 runner(filename,prog_ns,prog_ns,
1612 1564 exit_ignore=exit_ignore)
1613 1565 t1 = clock2()
1614 1566 t_usr = t1[0]-t0[0]
1615 1567 t_sys = t1[1]-t1[1]
1616 1568 print "\nIPython CPU timings (estimated):"
1617 1569 print "Total runs performed:",nruns
1618 1570 print " Times : %10s %10s" % ('Total','Per run')
1619 1571 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1620 1572 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1621 1573
1622 1574 else:
1623 1575 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1624 1576 if opts.has_key('i'):
1625 1577 self.shell.user_ns['__name__'] = __name__save
1626 1578 else:
1627 1579 # update IPython interactive namespace
1628 1580 del prog_ns['__name__']
1629 1581 self.shell.user_ns.update(prog_ns)
1630 1582 finally:
1631 1583 sys.argv = save_argv
1632 1584 if restore_main:
1633 1585 sys.modules['__main__'] = restore_main
1634 1586 if self.shell.has_readline:
1635 1587 self.shell.readline.read_history_file(self.shell.histfile)
1636 1588
1637 1589 return stats
1638 1590
1639 1591 def magic_runlog(self, parameter_s =''):
1640 1592 """Run files as logs.
1641 1593
1642 1594 Usage:\\
1643 1595 %runlog file1 file2 ...
1644 1596
1645 1597 Run the named files (treating them as log files) in sequence inside
1646 1598 the interpreter, and return to the prompt. This is much slower than
1647 1599 %run because each line is executed in a try/except block, but it
1648 1600 allows running files with syntax errors in them.
1649 1601
1650 1602 Normally IPython will guess when a file is one of its own logfiles, so
1651 1603 you can typically use %run even for logs. This shorthand allows you to
1652 1604 force any file to be treated as a log file."""
1653 1605
1654 1606 for f in parameter_s.split():
1655 1607 self.shell.safe_execfile(f,self.shell.user_ns,
1656 1608 self.shell.user_ns,islog=1)
1657 1609
1658 1610 def magic_timeit(self, parameter_s =''):
1659 1611 """Time execution of a Python statement or expression
1660 1612
1661 1613 Usage:\\
1662 1614 %timeit [-n<N> -r<R> [-t|-c]] statement
1663 1615
1664 1616 Time execution of a Python statement or expression using the timeit
1665 1617 module.
1666 1618
1667 1619 Options:
1668 1620 -n<N>: execute the given statement <N> times in a loop. If this value
1669 1621 is not given, a fitting value is chosen.
1670 1622
1671 1623 -r<R>: repeat the loop iteration <R> times and take the best result.
1672 1624 Default: 3
1673 1625
1674 1626 -t: use time.time to measure the time, which is the default on Unix.
1675 1627 This function measures wall time.
1676 1628
1677 1629 -c: use time.clock to measure the time, which is the default on
1678 1630 Windows and measures wall time. On Unix, resource.getrusage is used
1679 1631 instead and returns the CPU user time.
1680 1632
1681 1633 -p<P>: use a precision of <P> digits to display the timing result.
1682 1634 Default: 3
1683 1635
1684 1636
1685 1637 Examples:\\
1686 1638 In [1]: %timeit pass
1687 1639 10000000 loops, best of 3: 53.3 ns per loop
1688 1640
1689 1641 In [2]: u = None
1690 1642
1691 1643 In [3]: %timeit u is None
1692 1644 10000000 loops, best of 3: 184 ns per loop
1693 1645
1694 1646 In [4]: %timeit -r 4 u == None
1695 1647 1000000 loops, best of 4: 242 ns per loop
1696 1648
1697 1649 In [5]: import time
1698 1650
1699 1651 In [6]: %timeit -n1 time.sleep(2)
1700 1652 1 loops, best of 3: 2 s per loop
1701 1653
1702 1654
1703 1655 The times reported by %timeit will be slightly higher than those
1704 1656 reported by the timeit.py script when variables are accessed. This is
1705 1657 due to the fact that %timeit executes the statement in the namespace
1706 1658 of the shell, compared with timeit.py, which uses a single setup
1707 1659 statement to import function or create variables. Generally, the bias
1708 1660 does not matter as long as results from timeit.py are not mixed with
1709 1661 those from %timeit."""
1710 1662
1711 1663 import timeit
1712 1664 import math
1713 1665
1714 1666 units = ["s", "ms", "\xc2\xb5s", "ns"]
1715 1667 scaling = [1, 1e3, 1e6, 1e9]
1716 1668
1717 1669 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1718 1670 posix=False)
1719 1671 if stmt == "":
1720 1672 return
1721 1673 timefunc = timeit.default_timer
1722 1674 number = int(getattr(opts, "n", 0))
1723 1675 repeat = int(getattr(opts, "r", timeit.default_repeat))
1724 1676 precision = int(getattr(opts, "p", 3))
1725 1677 if hasattr(opts, "t"):
1726 1678 timefunc = time.time
1727 1679 if hasattr(opts, "c"):
1728 1680 timefunc = clock
1729 1681
1730 1682 timer = timeit.Timer(timer=timefunc)
1731 1683 # this code has tight coupling to the inner workings of timeit.Timer,
1732 1684 # but is there a better way to achieve that the code stmt has access
1733 1685 # to the shell namespace?
1734 1686
1735 1687 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1736 1688 'setup': "pass"}
1737 1689 code = compile(src, "<magic-timeit>", "exec")
1738 1690 ns = {}
1739 1691 exec code in self.shell.user_ns, ns
1740 1692 timer.inner = ns["inner"]
1741 1693
1742 1694 if number == 0:
1743 1695 # determine number so that 0.2 <= total time < 2.0
1744 1696 number = 1
1745 1697 for i in range(1, 10):
1746 1698 number *= 10
1747 1699 if timer.timeit(number) >= 0.2:
1748 1700 break
1749 1701
1750 1702 best = min(timer.repeat(repeat, number)) / number
1751 1703
1752 1704 if best > 0.0:
1753 1705 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1754 1706 else:
1755 1707 order = 3
1756 1708 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1757 1709 precision,
1758 1710 best * scaling[order],
1759 1711 units[order])
1760 1712
1761 1713 def magic_time(self,parameter_s = ''):
1762 1714 """Time execution of a Python statement or expression.
1763 1715
1764 1716 The CPU and wall clock times are printed, and the value of the
1765 1717 expression (if any) is returned. Note that under Win32, system time
1766 1718 is always reported as 0, since it can not be measured.
1767 1719
1768 1720 This function provides very basic timing functionality. In Python
1769 1721 2.3, the timeit module offers more control and sophistication, so this
1770 1722 could be rewritten to use it (patches welcome).
1771 1723
1772 1724 Some examples:
1773 1725
1774 1726 In [1]: time 2**128
1775 1727 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1776 1728 Wall time: 0.00
1777 1729 Out[1]: 340282366920938463463374607431768211456L
1778 1730
1779 1731 In [2]: n = 1000000
1780 1732
1781 1733 In [3]: time sum(range(n))
1782 1734 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1783 1735 Wall time: 1.37
1784 1736 Out[3]: 499999500000L
1785 1737
1786 1738 In [4]: time print 'hello world'
1787 1739 hello world
1788 1740 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1789 1741 Wall time: 0.00
1790 1742 """
1791 1743
1792 1744 # fail immediately if the given expression can't be compiled
1793 1745 try:
1794 1746 mode = 'eval'
1795 1747 code = compile(parameter_s,'<timed eval>',mode)
1796 1748 except SyntaxError:
1797 1749 mode = 'exec'
1798 1750 code = compile(parameter_s,'<timed exec>',mode)
1799 1751 # skew measurement as little as possible
1800 1752 glob = self.shell.user_ns
1801 1753 clk = clock2
1802 1754 wtime = time.time
1803 1755 # time execution
1804 1756 wall_st = wtime()
1805 1757 if mode=='eval':
1806 1758 st = clk()
1807 1759 out = eval(code,glob)
1808 1760 end = clk()
1809 1761 else:
1810 1762 st = clk()
1811 1763 exec code in glob
1812 1764 end = clk()
1813 1765 out = None
1814 1766 wall_end = wtime()
1815 1767 # Compute actual times and report
1816 1768 wall_time = wall_end-wall_st
1817 1769 cpu_user = end[0]-st[0]
1818 1770 cpu_sys = end[1]-st[1]
1819 1771 cpu_tot = cpu_user+cpu_sys
1820 1772 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1821 1773 (cpu_user,cpu_sys,cpu_tot)
1822 1774 print "Wall time: %.2f" % wall_time
1823 1775 return out
1824 1776
1825 1777 def magic_macro(self,parameter_s = ''):
1826 1778 """Define a set of input lines as a macro for future re-execution.
1827 1779
1828 1780 Usage:\\
1829 1781 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1830 1782
1831 1783 Options:
1832 1784
1833 1785 -r: use 'raw' input. By default, the 'processed' history is used,
1834 1786 so that magics are loaded in their transformed version to valid
1835 1787 Python. If this option is given, the raw input as typed as the
1836 1788 command line is used instead.
1837 1789
1838 1790 This will define a global variable called `name` which is a string
1839 1791 made of joining the slices and lines you specify (n1,n2,... numbers
1840 1792 above) from your input history into a single string. This variable
1841 1793 acts like an automatic function which re-executes those lines as if
1842 1794 you had typed them. You just type 'name' at the prompt and the code
1843 1795 executes.
1844 1796
1845 1797 The notation for indicating number ranges is: n1-n2 means 'use line
1846 1798 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1847 1799 using the lines numbered 5,6 and 7.
1848 1800
1849 1801 Note: as a 'hidden' feature, you can also use traditional python slice
1850 1802 notation, where N:M means numbers N through M-1.
1851 1803
1852 1804 For example, if your history contains (%hist prints it):
1853 1805
1854 1806 44: x=1\\
1855 1807 45: y=3\\
1856 1808 46: z=x+y\\
1857 1809 47: print x\\
1858 1810 48: a=5\\
1859 1811 49: print 'x',x,'y',y\\
1860 1812
1861 1813 you can create a macro with lines 44 through 47 (included) and line 49
1862 1814 called my_macro with:
1863 1815
1864 1816 In [51]: %macro my_macro 44-47 49
1865 1817
1866 1818 Now, typing `my_macro` (without quotes) will re-execute all this code
1867 1819 in one pass.
1868 1820
1869 1821 You don't need to give the line-numbers in order, and any given line
1870 1822 number can appear multiple times. You can assemble macros with any
1871 1823 lines from your input history in any order.
1872 1824
1873 1825 The macro is a simple object which holds its value in an attribute,
1874 1826 but IPython's display system checks for macros and executes them as
1875 1827 code instead of printing them when you type their name.
1876 1828
1877 1829 You can view a macro's contents by explicitly printing it with:
1878 1830
1879 1831 'print macro_name'.
1880 1832
1881 1833 For one-off cases which DON'T contain magic function calls in them you
1882 1834 can obtain similar results by explicitly executing slices from your
1883 1835 input history with:
1884 1836
1885 1837 In [60]: exec In[44:48]+In[49]"""
1886 1838
1887 1839 opts,args = self.parse_options(parameter_s,'r',mode='list')
1888 1840 name,ranges = args[0], args[1:]
1889 1841 #print 'rng',ranges # dbg
1890 1842 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1891 1843 macro = Macro(lines)
1892 1844 self.shell.user_ns.update({name:macro})
1893 1845 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1894 1846 print 'Macro contents:'
1895 1847 print macro,
1896 1848
1897 1849 def magic_save(self,parameter_s = ''):
1898 1850 """Save a set of lines to a given filename.
1899 1851
1900 1852 Usage:\\
1901 1853 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1902 1854
1903 1855 Options:
1904 1856
1905 1857 -r: use 'raw' input. By default, the 'processed' history is used,
1906 1858 so that magics are loaded in their transformed version to valid
1907 1859 Python. If this option is given, the raw input as typed as the
1908 1860 command line is used instead.
1909 1861
1910 1862 This function uses the same syntax as %macro for line extraction, but
1911 1863 instead of creating a macro it saves the resulting string to the
1912 1864 filename you specify.
1913 1865
1914 1866 It adds a '.py' extension to the file if you don't do so yourself, and
1915 1867 it asks for confirmation before overwriting existing files."""
1916 1868
1917 1869 opts,args = self.parse_options(parameter_s,'r',mode='list')
1918 1870 fname,ranges = args[0], args[1:]
1919 1871 if not fname.endswith('.py'):
1920 1872 fname += '.py'
1921 1873 if os.path.isfile(fname):
1922 1874 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1923 1875 if ans.lower() not in ['y','yes']:
1924 1876 print 'Operation cancelled.'
1925 1877 return
1926 1878 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1927 1879 f = file(fname,'w')
1928 1880 f.write(cmds)
1929 1881 f.close()
1930 1882 print 'The following commands were written to file `%s`:' % fname
1931 1883 print cmds
1932 1884
1933 1885 def _edit_macro(self,mname,macro):
1934 1886 """open an editor with the macro data in a file"""
1935 1887 filename = self.shell.mktempfile(macro.value)
1936 1888 self.shell.hooks.editor(filename)
1937 1889
1938 1890 # and make a new macro object, to replace the old one
1939 1891 mfile = open(filename)
1940 1892 mvalue = mfile.read()
1941 1893 mfile.close()
1942 1894 self.shell.user_ns[mname] = Macro(mvalue)
1943 1895
1944 1896 def magic_ed(self,parameter_s=''):
1945 1897 """Alias to %edit."""
1946 1898 return self.magic_edit(parameter_s)
1947 1899
1948 1900 def magic_edit(self,parameter_s='',last_call=['','']):
1949 1901 """Bring up an editor and execute the resulting code.
1950 1902
1951 1903 Usage:
1952 1904 %edit [options] [args]
1953 1905
1954 1906 %edit runs IPython's editor hook. The default version of this hook is
1955 1907 set to call the __IPYTHON__.rc.editor command. This is read from your
1956 1908 environment variable $EDITOR. If this isn't found, it will default to
1957 1909 vi under Linux/Unix and to notepad under Windows. See the end of this
1958 1910 docstring for how to change the editor hook.
1959 1911
1960 1912 You can also set the value of this editor via the command line option
1961 1913 '-editor' or in your ipythonrc file. This is useful if you wish to use
1962 1914 specifically for IPython an editor different from your typical default
1963 1915 (and for Windows users who typically don't set environment variables).
1964 1916
1965 1917 This command allows you to conveniently edit multi-line code right in
1966 1918 your IPython session.
1967 1919
1968 1920 If called without arguments, %edit opens up an empty editor with a
1969 1921 temporary file and will execute the contents of this file when you
1970 1922 close it (don't forget to save it!).
1971 1923
1972 1924
1973 1925 Options:
1974 1926
1975 1927 -n <number>: open the editor at a specified line number. By default,
1976 1928 the IPython editor hook uses the unix syntax 'editor +N filename', but
1977 1929 you can configure this by providing your own modified hook if your
1978 1930 favorite editor supports line-number specifications with a different
1979 1931 syntax.
1980 1932
1981 1933 -p: this will call the editor with the same data as the previous time
1982 1934 it was used, regardless of how long ago (in your current session) it
1983 1935 was.
1984 1936
1985 1937 -r: use 'raw' input. This option only applies to input taken from the
1986 1938 user's history. By default, the 'processed' history is used, so that
1987 1939 magics are loaded in their transformed version to valid Python. If
1988 1940 this option is given, the raw input as typed as the command line is
1989 1941 used instead. When you exit the editor, it will be executed by
1990 1942 IPython's own processor.
1991 1943
1992 1944 -x: do not execute the edited code immediately upon exit. This is
1993 1945 mainly useful if you are editing programs which need to be called with
1994 1946 command line arguments, which you can then do using %run.
1995 1947
1996 1948
1997 1949 Arguments:
1998 1950
1999 1951 If arguments are given, the following possibilites exist:
2000 1952
2001 1953 - The arguments are numbers or pairs of colon-separated numbers (like
2002 1954 1 4:8 9). These are interpreted as lines of previous input to be
2003 1955 loaded into the editor. The syntax is the same of the %macro command.
2004 1956
2005 1957 - If the argument doesn't start with a number, it is evaluated as a
2006 1958 variable and its contents loaded into the editor. You can thus edit
2007 1959 any string which contains python code (including the result of
2008 1960 previous edits).
2009 1961
2010 1962 - If the argument is the name of an object (other than a string),
2011 1963 IPython will try to locate the file where it was defined and open the
2012 1964 editor at the point where it is defined. You can use `%edit function`
2013 1965 to load an editor exactly at the point where 'function' is defined,
2014 1966 edit it and have the file be executed automatically.
2015 1967
2016 1968 If the object is a macro (see %macro for details), this opens up your
2017 1969 specified editor with a temporary file containing the macro's data.
2018 1970 Upon exit, the macro is reloaded with the contents of the file.
2019 1971
2020 1972 Note: opening at an exact line is only supported under Unix, and some
2021 1973 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2022 1974 '+NUMBER' parameter necessary for this feature. Good editors like
2023 1975 (X)Emacs, vi, jed, pico and joe all do.
2024 1976
2025 1977 - If the argument is not found as a variable, IPython will look for a
2026 1978 file with that name (adding .py if necessary) and load it into the
2027 1979 editor. It will execute its contents with execfile() when you exit,
2028 1980 loading any code in the file into your interactive namespace.
2029 1981
2030 1982 After executing your code, %edit will return as output the code you
2031 1983 typed in the editor (except when it was an existing file). This way
2032 1984 you can reload the code in further invocations of %edit as a variable,
2033 1985 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2034 1986 the output.
2035 1987
2036 1988 Note that %edit is also available through the alias %ed.
2037 1989
2038 1990 This is an example of creating a simple function inside the editor and
2039 1991 then modifying it. First, start up the editor:
2040 1992
2041 1993 In [1]: ed\\
2042 1994 Editing... done. Executing edited code...\\
2043 1995 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2044 1996
2045 1997 We can then call the function foo():
2046 1998
2047 1999 In [2]: foo()\\
2048 2000 foo() was defined in an editing session
2049 2001
2050 2002 Now we edit foo. IPython automatically loads the editor with the
2051 2003 (temporary) file where foo() was previously defined:
2052 2004
2053 2005 In [3]: ed foo\\
2054 2006 Editing... done. Executing edited code...
2055 2007
2056 2008 And if we call foo() again we get the modified version:
2057 2009
2058 2010 In [4]: foo()\\
2059 2011 foo() has now been changed!
2060 2012
2061 2013 Here is an example of how to edit a code snippet successive
2062 2014 times. First we call the editor:
2063 2015
2064 2016 In [8]: ed\\
2065 2017 Editing... done. Executing edited code...\\
2066 2018 hello\\
2067 2019 Out[8]: "print 'hello'\\n"
2068 2020
2069 2021 Now we call it again with the previous output (stored in _):
2070 2022
2071 2023 In [9]: ed _\\
2072 2024 Editing... done. Executing edited code...\\
2073 2025 hello world\\
2074 2026 Out[9]: "print 'hello world'\\n"
2075 2027
2076 2028 Now we call it with the output #8 (stored in _8, also as Out[8]):
2077 2029
2078 2030 In [10]: ed _8\\
2079 2031 Editing... done. Executing edited code...\\
2080 2032 hello again\\
2081 2033 Out[10]: "print 'hello again'\\n"
2082 2034
2083 2035
2084 2036 Changing the default editor hook:
2085 2037
2086 2038 If you wish to write your own editor hook, you can put it in a
2087 2039 configuration file which you load at startup time. The default hook
2088 2040 is defined in the IPython.hooks module, and you can use that as a
2089 2041 starting example for further modifications. That file also has
2090 2042 general instructions on how to set a new hook for use once you've
2091 2043 defined it."""
2092 2044
2093 2045 # FIXME: This function has become a convoluted mess. It needs a
2094 2046 # ground-up rewrite with clean, simple logic.
2095 2047
2096 2048 def make_filename(arg):
2097 2049 "Make a filename from the given args"
2098 2050 try:
2099 2051 filename = get_py_filename(arg)
2100 2052 except IOError:
2101 2053 if args.endswith('.py'):
2102 2054 filename = arg
2103 2055 else:
2104 2056 filename = None
2105 2057 return filename
2106 2058
2107 2059 # custom exceptions
2108 2060 class DataIsObject(Exception): pass
2109 2061
2110 2062 opts,args = self.parse_options(parameter_s,'prxn:')
2111 2063 # Set a few locals from the options for convenience:
2112 2064 opts_p = opts.has_key('p')
2113 2065 opts_r = opts.has_key('r')
2114 2066
2115 2067 # Default line number value
2116 2068 lineno = opts.get('n',None)
2117 2069
2118 2070 if opts_p:
2119 2071 args = '_%s' % last_call[0]
2120 2072 if not self.shell.user_ns.has_key(args):
2121 2073 args = last_call[1]
2122 2074
2123 2075 # use last_call to remember the state of the previous call, but don't
2124 2076 # let it be clobbered by successive '-p' calls.
2125 2077 try:
2126 2078 last_call[0] = self.shell.outputcache.prompt_count
2127 2079 if not opts_p:
2128 2080 last_call[1] = parameter_s
2129 2081 except:
2130 2082 pass
2131 2083
2132 2084 # by default this is done with temp files, except when the given
2133 2085 # arg is a filename
2134 2086 use_temp = 1
2135 2087
2136 2088 if re.match(r'\d',args):
2137 2089 # Mode where user specifies ranges of lines, like in %macro.
2138 2090 # This means that you can't edit files whose names begin with
2139 2091 # numbers this way. Tough.
2140 2092 ranges = args.split()
2141 2093 data = ''.join(self.extract_input_slices(ranges,opts_r))
2142 2094 elif args.endswith('.py'):
2143 2095 filename = make_filename(args)
2144 2096 data = ''
2145 2097 use_temp = 0
2146 2098 elif args:
2147 2099 try:
2148 2100 # Load the parameter given as a variable. If not a string,
2149 2101 # process it as an object instead (below)
2150 2102
2151 2103 #print '*** args',args,'type',type(args) # dbg
2152 2104 data = eval(args,self.shell.user_ns)
2153 2105 if not type(data) in StringTypes:
2154 2106 raise DataIsObject
2155 2107
2156 2108 except (NameError,SyntaxError):
2157 2109 # given argument is not a variable, try as a filename
2158 2110 filename = make_filename(args)
2159 2111 if filename is None:
2160 2112 warn("Argument given (%s) can't be found as a variable "
2161 2113 "or as a filename." % args)
2162 2114 return
2163 2115
2164 2116 data = ''
2165 2117 use_temp = 0
2166 2118 except DataIsObject:
2167 2119
2168 2120 # macros have a special edit function
2169 2121 if isinstance(data,Macro):
2170 2122 self._edit_macro(args,data)
2171 2123 return
2172 2124
2173 2125 # For objects, try to edit the file where they are defined
2174 2126 try:
2175 2127 filename = inspect.getabsfile(data)
2176 2128 datafile = 1
2177 2129 except TypeError:
2178 2130 filename = make_filename(args)
2179 2131 datafile = 1
2180 2132 warn('Could not find file where `%s` is defined.\n'
2181 2133 'Opening a file named `%s`' % (args,filename))
2182 2134 # Now, make sure we can actually read the source (if it was in
2183 2135 # a temp file it's gone by now).
2184 2136 if datafile:
2185 2137 try:
2186 2138 if lineno is None:
2187 2139 lineno = inspect.getsourcelines(data)[1]
2188 2140 except IOError:
2189 2141 filename = make_filename(args)
2190 2142 if filename is None:
2191 2143 warn('The file `%s` where `%s` was defined cannot '
2192 2144 'be read.' % (filename,data))
2193 2145 return
2194 2146 use_temp = 0
2195 2147 else:
2196 2148 data = ''
2197 2149
2198 2150 if use_temp:
2199 2151 filename = self.shell.mktempfile(data)
2200 2152 print 'IPython will make a temporary file named:',filename
2201 2153
2202 2154 # do actual editing here
2203 2155 print 'Editing...',
2204 2156 sys.stdout.flush()
2205 2157 self.shell.hooks.editor(filename,lineno)
2206 2158 if opts.has_key('x'): # -x prevents actual execution
2207 2159 print
2208 2160 else:
2209 2161 print 'done. Executing edited code...'
2210 2162 if opts_r:
2211 2163 self.shell.runlines(file_read(filename))
2212 2164 else:
2213 2165 self.shell.safe_execfile(filename,self.shell.user_ns)
2214 2166 if use_temp:
2215 2167 try:
2216 2168 return open(filename).read()
2217 2169 except IOError,msg:
2218 2170 if msg.filename == filename:
2219 2171 warn('File not found. Did you forget to save?')
2220 2172 return
2221 2173 else:
2222 2174 self.shell.showtraceback()
2223 2175
2224 2176 def magic_xmode(self,parameter_s = ''):
2225 2177 """Switch modes for the exception handlers.
2226 2178
2227 2179 Valid modes: Plain, Context and Verbose.
2228 2180
2229 2181 If called without arguments, acts as a toggle."""
2230 2182
2231 2183 def xmode_switch_err(name):
2232 2184 warn('Error changing %s exception modes.\n%s' %
2233 2185 (name,sys.exc_info()[1]))
2234 2186
2235 2187 shell = self.shell
2236 2188 new_mode = parameter_s.strip().capitalize()
2237 2189 try:
2238 2190 shell.InteractiveTB.set_mode(mode=new_mode)
2239 2191 print 'Exception reporting mode:',shell.InteractiveTB.mode
2240 2192 except:
2241 2193 xmode_switch_err('user')
2242 2194
2243 2195 # threaded shells use a special handler in sys.excepthook
2244 2196 if shell.isthreaded:
2245 2197 try:
2246 2198 shell.sys_excepthook.set_mode(mode=new_mode)
2247 2199 except:
2248 2200 xmode_switch_err('threaded')
2249 2201
2250 2202 def magic_colors(self,parameter_s = ''):
2251 2203 """Switch color scheme for prompts, info system and exception handlers.
2252 2204
2253 2205 Currently implemented schemes: NoColor, Linux, LightBG.
2254 2206
2255 2207 Color scheme names are not case-sensitive."""
2256 2208
2257 2209 def color_switch_err(name):
2258 2210 warn('Error changing %s color schemes.\n%s' %
2259 2211 (name,sys.exc_info()[1]))
2260 2212
2261 2213
2262 2214 new_scheme = parameter_s.strip()
2263 2215 if not new_scheme:
2264 2216 print 'You must specify a color scheme.'
2265 2217 return
2266 2218 import IPython.rlineimpl as readline
2267 2219 if not readline.have_readline:
2268 2220 msg = """\
2269 2221 Proper color support under MS Windows requires the pyreadline library.
2270 2222 You can find it at:
2271 2223 http://ipython.scipy.org/moin/PyReadline/Intro
2272 2224 Gary's readline needs the ctypes module, from:
2273 2225 http://starship.python.net/crew/theller/ctypes
2274 2226 (Note that ctypes is already part of Python versions 2.5 and newer).
2275 2227
2276 2228 Defaulting color scheme to 'NoColor'"""
2277 2229 new_scheme = 'NoColor'
2278 2230 warn(msg)
2279 2231 # local shortcut
2280 2232 shell = self.shell
2281 2233
2282 2234 # Set prompt colors
2283 2235 try:
2284 2236 shell.outputcache.set_colors(new_scheme)
2285 2237 except:
2286 2238 color_switch_err('prompt')
2287 2239 else:
2288 2240 shell.rc.colors = \
2289 2241 shell.outputcache.color_table.active_scheme_name
2290 2242 # Set exception colors
2291 2243 try:
2292 2244 shell.InteractiveTB.set_colors(scheme = new_scheme)
2293 2245 shell.SyntaxTB.set_colors(scheme = new_scheme)
2294 2246 except:
2295 2247 color_switch_err('exception')
2296 2248
2297 2249 # threaded shells use a verbose traceback in sys.excepthook
2298 2250 if shell.isthreaded:
2299 2251 try:
2300 2252 shell.sys_excepthook.set_colors(scheme=new_scheme)
2301 2253 except:
2302 2254 color_switch_err('system exception handler')
2303 2255
2304 2256 # Set info (for 'object?') colors
2305 2257 if shell.rc.color_info:
2306 2258 try:
2307 2259 shell.inspector.set_active_scheme(new_scheme)
2308 2260 except:
2309 2261 color_switch_err('object inspector')
2310 2262 else:
2311 2263 shell.inspector.set_active_scheme('NoColor')
2312 2264
2313 2265 def magic_color_info(self,parameter_s = ''):
2314 2266 """Toggle color_info.
2315 2267
2316 2268 The color_info configuration parameter controls whether colors are
2317 2269 used for displaying object details (by things like %psource, %pfile or
2318 2270 the '?' system). This function toggles this value with each call.
2319 2271
2320 2272 Note that unless you have a fairly recent pager (less works better
2321 2273 than more) in your system, using colored object information displays
2322 2274 will not work properly. Test it and see."""
2323 2275
2324 2276 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2325 2277 self.magic_colors(self.shell.rc.colors)
2326 2278 print 'Object introspection functions have now coloring:',
2327 2279 print ['OFF','ON'][self.shell.rc.color_info]
2328 2280
2329 2281 def magic_Pprint(self, parameter_s=''):
2330 2282 """Toggle pretty printing on/off."""
2331 2283
2332 2284 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2333 2285 print 'Pretty printing has been turned', \
2334 2286 ['OFF','ON'][self.shell.rc.pprint]
2335 2287
2336 2288 def magic_exit(self, parameter_s=''):
2337 2289 """Exit IPython, confirming if configured to do so.
2338 2290
2339 2291 You can configure whether IPython asks for confirmation upon exit by
2340 2292 setting the confirm_exit flag in the ipythonrc file."""
2341 2293
2342 2294 self.shell.exit()
2343 2295
2344 2296 def magic_quit(self, parameter_s=''):
2345 2297 """Exit IPython, confirming if configured to do so (like %exit)"""
2346 2298
2347 2299 self.shell.exit()
2348 2300
2349 2301 def magic_Exit(self, parameter_s=''):
2350 2302 """Exit IPython without confirmation."""
2351 2303
2352 2304 self.shell.exit_now = True
2353 2305
2354 2306 def magic_Quit(self, parameter_s=''):
2355 2307 """Exit IPython without confirmation (like %Exit)."""
2356 2308
2357 2309 self.shell.exit_now = True
2358 2310
2359 2311 #......................................................................
2360 2312 # Functions to implement unix shell-type things
2361 2313
2362 2314 def magic_alias(self, parameter_s = ''):
2363 2315 """Define an alias for a system command.
2364 2316
2365 2317 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2366 2318
2367 2319 Then, typing 'alias_name params' will execute the system command 'cmd
2368 2320 params' (from your underlying operating system).
2369 2321
2370 2322 Aliases have lower precedence than magic functions and Python normal
2371 2323 variables, so if 'foo' is both a Python variable and an alias, the
2372 2324 alias can not be executed until 'del foo' removes the Python variable.
2373 2325
2374 2326 You can use the %l specifier in an alias definition to represent the
2375 2327 whole line when the alias is called. For example:
2376 2328
2377 2329 In [2]: alias all echo "Input in brackets: <%l>"\\
2378 2330 In [3]: all hello world\\
2379 2331 Input in brackets: <hello world>
2380 2332
2381 2333 You can also define aliases with parameters using %s specifiers (one
2382 2334 per parameter):
2383 2335
2384 2336 In [1]: alias parts echo first %s second %s\\
2385 2337 In [2]: %parts A B\\
2386 2338 first A second B\\
2387 2339 In [3]: %parts A\\
2388 2340 Incorrect number of arguments: 2 expected.\\
2389 2341 parts is an alias to: 'echo first %s second %s'
2390 2342
2391 2343 Note that %l and %s are mutually exclusive. You can only use one or
2392 2344 the other in your aliases.
2393 2345
2394 2346 Aliases expand Python variables just like system calls using ! or !!
2395 2347 do: all expressions prefixed with '$' get expanded. For details of
2396 2348 the semantic rules, see PEP-215:
2397 2349 http://www.python.org/peps/pep-0215.html. This is the library used by
2398 2350 IPython for variable expansion. If you want to access a true shell
2399 2351 variable, an extra $ is necessary to prevent its expansion by IPython:
2400 2352
2401 2353 In [6]: alias show echo\\
2402 2354 In [7]: PATH='A Python string'\\
2403 2355 In [8]: show $PATH\\
2404 2356 A Python string\\
2405 2357 In [9]: show $$PATH\\
2406 2358 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2407 2359
2408 2360 You can use the alias facility to acess all of $PATH. See the %rehash
2409 2361 and %rehashx functions, which automatically create aliases for the
2410 2362 contents of your $PATH.
2411 2363
2412 2364 If called with no parameters, %alias prints the current alias table."""
2413 2365
2414 2366 par = parameter_s.strip()
2415 2367 if not par:
2416 2368 stored = self.db.get('stored_aliases', {} )
2417 2369 atab = self.shell.alias_table
2418 2370 aliases = atab.keys()
2419 2371 aliases.sort()
2420 2372 res = []
2421 2373 showlast = []
2422 2374 for alias in aliases:
2423 2375 tgt = atab[alias][1]
2424 2376 # 'interesting' aliases
2425 2377 if (alias in stored or
2426 2378 alias != os.path.splitext(tgt)[0] or
2427 2379 ' ' in tgt):
2428 2380 showlast.append((alias, tgt))
2429 2381 else:
2430 2382 res.append((alias, tgt ))
2431 2383
2432 2384 # show most interesting aliases last
2433 2385 res.extend(showlast)
2434 2386 print "Total number of aliases:",len(aliases)
2435 2387 return res
2436 2388 try:
2437 2389 alias,cmd = par.split(None,1)
2438 2390 except:
2439 2391 print OInspect.getdoc(self.magic_alias)
2440 2392 else:
2441 2393 nargs = cmd.count('%s')
2442 2394 if nargs>0 and cmd.find('%l')>=0:
2443 2395 error('The %s and %l specifiers are mutually exclusive '
2444 2396 'in alias definitions.')
2445 2397 else: # all looks OK
2446 2398 self.shell.alias_table[alias] = (nargs,cmd)
2447 2399 self.shell.alias_table_validate(verbose=0)
2448 2400 # end magic_alias
2449 2401
2450 2402 def magic_unalias(self, parameter_s = ''):
2451 2403 """Remove an alias"""
2452 2404
2453 2405 aname = parameter_s.strip()
2454 2406 if aname in self.shell.alias_table:
2455 2407 del self.shell.alias_table[aname]
2456 2408 stored = self.db.get('stored_aliases', {} )
2457 2409 if aname in stored:
2458 2410 print "Removing %stored alias",aname
2459 2411 del stored[aname]
2460 2412 self.db['stored_aliases'] = stored
2461 2413
2462 2414 def magic_rehash(self, parameter_s = ''):
2463 2415 """Update the alias table with all entries in $PATH.
2464 2416
2465 2417 This version does no checks on execute permissions or whether the
2466 2418 contents of $PATH are truly files (instead of directories or something
2467 2419 else). For such a safer (but slower) version, use %rehashx."""
2468 2420
2469 2421 # This function (and rehashx) manipulate the alias_table directly
2470 2422 # rather than calling magic_alias, for speed reasons. A rehash on a
2471 2423 # typical Linux box involves several thousand entries, so efficiency
2472 2424 # here is a top concern.
2473 2425
2474 2426 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2475 2427 alias_table = self.shell.alias_table
2476 2428 for pdir in path:
2477 2429 for ff in os.listdir(pdir):
2478 2430 # each entry in the alias table must be (N,name), where
2479 2431 # N is the number of positional arguments of the alias.
2480 2432 alias_table[ff] = (0,ff)
2481 2433 # Make sure the alias table doesn't contain keywords or builtins
2482 2434 self.shell.alias_table_validate()
2483 2435 # Call again init_auto_alias() so we get 'rm -i' and other modified
2484 2436 # aliases since %rehash will probably clobber them
2485 2437 self.shell.init_auto_alias()
2486 2438
2487 2439 def magic_rehashx(self, parameter_s = ''):
2488 2440 """Update the alias table with all executable files in $PATH.
2489 2441
2490 2442 This version explicitly checks that every entry in $PATH is a file
2491 2443 with execute access (os.X_OK), so it is much slower than %rehash.
2492 2444
2493 2445 Under Windows, it checks executability as a match agains a
2494 2446 '|'-separated string of extensions, stored in the IPython config
2495 2447 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2496 2448
2497 2449 path = [os.path.abspath(os.path.expanduser(p)) for p in
2498 2450 os.environ['PATH'].split(os.pathsep)]
2499 2451 path = filter(os.path.isdir,path)
2500 2452
2501 2453 alias_table = self.shell.alias_table
2502 2454 syscmdlist = []
2503 2455 if os.name == 'posix':
2504 2456 isexec = lambda fname:os.path.isfile(fname) and \
2505 2457 os.access(fname,os.X_OK)
2506 2458 else:
2507 2459
2508 2460 try:
2509 2461 winext = os.environ['pathext'].replace(';','|').replace('.','')
2510 2462 except KeyError:
2511 2463 winext = 'exe|com|bat|py'
2512 2464 if 'py' not in winext:
2513 2465 winext += '|py'
2514 2466 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2515 2467 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2516 2468 savedir = os.getcwd()
2517 2469 try:
2518 2470 # write the whole loop for posix/Windows so we don't have an if in
2519 2471 # the innermost part
2520 2472 if os.name == 'posix':
2521 2473 for pdir in path:
2522 2474 os.chdir(pdir)
2523 2475 for ff in os.listdir(pdir):
2524 2476 if isexec(ff) and ff not in self.shell.no_alias:
2525 2477 # each entry in the alias table must be (N,name),
2526 2478 # where N is the number of positional arguments of the
2527 2479 # alias.
2528 2480 alias_table[ff] = (0,ff)
2529 2481 syscmdlist.append(ff)
2530 2482 else:
2531 2483 for pdir in path:
2532 2484 os.chdir(pdir)
2533 2485 for ff in os.listdir(pdir):
2534 2486 base, ext = os.path.splitext(ff)
2535 2487 if isexec(ff) and base not in self.shell.no_alias:
2536 2488 if ext.lower() == '.exe':
2537 2489 ff = base
2538 2490 alias_table[base] = (0,ff)
2539 2491 syscmdlist.append(ff)
2540 2492 # Make sure the alias table doesn't contain keywords or builtins
2541 2493 self.shell.alias_table_validate()
2542 2494 # Call again init_auto_alias() so we get 'rm -i' and other
2543 2495 # modified aliases since %rehashx will probably clobber them
2544 2496 self.shell.init_auto_alias()
2545 2497 db = self.getapi().db
2546 2498 db['syscmdlist'] = syscmdlist
2547 2499 finally:
2548 2500 os.chdir(savedir)
2549 2501
2550 2502 def magic_pwd(self, parameter_s = ''):
2551 2503 """Return the current working directory path."""
2552 2504 return os.getcwd()
2553 2505
2554 2506 def magic_cd(self, parameter_s=''):
2555 2507 """Change the current working directory.
2556 2508
2557 2509 This command automatically maintains an internal list of directories
2558 2510 you visit during your IPython session, in the variable _dh. The
2559 2511 command %dhist shows this history nicely formatted.
2560 2512
2561 2513 Usage:
2562 2514
2563 2515 cd 'dir': changes to directory 'dir'.
2564 2516
2565 2517 cd -: changes to the last visited directory.
2566 2518
2567 2519 cd -<n>: changes to the n-th directory in the directory history.
2568 2520
2569 2521 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2570 2522 (note: cd <bookmark_name> is enough if there is no
2571 2523 directory <bookmark_name>, but a bookmark with the name exists.)
2572 2524
2573 2525 Options:
2574 2526
2575 2527 -q: quiet. Do not print the working directory after the cd command is
2576 2528 executed. By default IPython's cd command does print this directory,
2577 2529 since the default prompts do not display path information.
2578 2530
2579 2531 Note that !cd doesn't work for this purpose because the shell where
2580 2532 !command runs is immediately discarded after executing 'command'."""
2581 2533
2582 2534 parameter_s = parameter_s.strip()
2583 2535 #bkms = self.shell.persist.get("bookmarks",{})
2584 2536
2585 2537 numcd = re.match(r'(-)(\d+)$',parameter_s)
2586 2538 # jump in directory history by number
2587 2539 if numcd:
2588 2540 nn = int(numcd.group(2))
2589 2541 try:
2590 2542 ps = self.shell.user_ns['_dh'][nn]
2591 2543 except IndexError:
2592 2544 print 'The requested directory does not exist in history.'
2593 2545 return
2594 2546 else:
2595 2547 opts = {}
2596 2548 else:
2597 2549 #turn all non-space-escaping backslashes to slashes,
2598 2550 # for c:\windows\directory\names\
2599 2551 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2600 2552 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2601 2553 # jump to previous
2602 2554 if ps == '-':
2603 2555 try:
2604 2556 ps = self.shell.user_ns['_dh'][-2]
2605 2557 except IndexError:
2606 2558 print 'No previous directory to change to.'
2607 2559 return
2608 2560 # jump to bookmark if needed
2609 2561 else:
2610 2562 if not os.path.isdir(ps) or opts.has_key('b'):
2611 2563 bkms = self.db.get('bookmarks', {})
2612 2564
2613 2565 if bkms.has_key(ps):
2614 2566 target = bkms[ps]
2615 2567 print '(bookmark:%s) -> %s' % (ps,target)
2616 2568 ps = target
2617 2569 else:
2618 2570 if opts.has_key('b'):
2619 2571 error("Bookmark '%s' not found. "
2620 2572 "Use '%%bookmark -l' to see your bookmarks." % ps)
2621 2573 return
2622 2574
2623 2575 # at this point ps should point to the target dir
2624 2576 if ps:
2625 2577 try:
2626 2578 os.chdir(os.path.expanduser(ps))
2627 2579 ttitle = ("IPy:" + (
2628 2580 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2629 2581 platutils.set_term_title(ttitle)
2630 2582 except OSError:
2631 2583 print sys.exc_info()[1]
2632 2584 else:
2633 2585 self.shell.user_ns['_dh'].append(os.getcwd())
2634 2586 else:
2635 2587 os.chdir(self.shell.home_dir)
2636 2588 platutils.set_term_title("IPy:~")
2637 2589 self.shell.user_ns['_dh'].append(os.getcwd())
2638 2590 if not 'q' in opts:
2639 2591 print self.shell.user_ns['_dh'][-1]
2640 2592
2641 2593 def magic_dhist(self, parameter_s=''):
2642 2594 """Print your history of visited directories.
2643 2595
2644 2596 %dhist -> print full history\\
2645 2597 %dhist n -> print last n entries only\\
2646 2598 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2647 2599
2648 2600 This history is automatically maintained by the %cd command, and
2649 2601 always available as the global list variable _dh. You can use %cd -<n>
2650 2602 to go to directory number <n>."""
2651 2603
2652 2604 dh = self.shell.user_ns['_dh']
2653 2605 if parameter_s:
2654 2606 try:
2655 2607 args = map(int,parameter_s.split())
2656 2608 except:
2657 2609 self.arg_err(Magic.magic_dhist)
2658 2610 return
2659 2611 if len(args) == 1:
2660 2612 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2661 2613 elif len(args) == 2:
2662 2614 ini,fin = args
2663 2615 else:
2664 2616 self.arg_err(Magic.magic_dhist)
2665 2617 return
2666 2618 else:
2667 2619 ini,fin = 0,len(dh)
2668 2620 nlprint(dh,
2669 2621 header = 'Directory history (kept in _dh)',
2670 2622 start=ini,stop=fin)
2671 2623
2672 2624 def magic_env(self, parameter_s=''):
2673 2625 """List environment variables."""
2674 2626
2675 2627 return os.environ.data
2676 2628
2677 2629 def magic_pushd(self, parameter_s=''):
2678 2630 """Place the current dir on stack and change directory.
2679 2631
2680 2632 Usage:\\
2681 2633 %pushd ['dirname']
2682 2634
2683 2635 %pushd with no arguments does a %pushd to your home directory.
2684 2636 """
2685 2637 if parameter_s == '': parameter_s = '~'
2686 2638 dir_s = self.shell.dir_stack
2687 2639 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2688 2640 os.path.expanduser(self.shell.dir_stack[0]):
2689 2641 try:
2690 2642 self.magic_cd(parameter_s)
2691 2643 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2692 2644 self.magic_dirs()
2693 2645 except:
2694 2646 print 'Invalid directory'
2695 2647 else:
2696 2648 print 'You are already there!'
2697 2649
2698 2650 def magic_popd(self, parameter_s=''):
2699 2651 """Change to directory popped off the top of the stack.
2700 2652 """
2701 2653 if len (self.shell.dir_stack) > 1:
2702 2654 self.shell.dir_stack.pop(0)
2703 2655 self.magic_cd(self.shell.dir_stack[0])
2704 2656 print self.shell.dir_stack[0]
2705 2657 else:
2706 2658 print "You can't remove the starting directory from the stack:",\
2707 2659 self.shell.dir_stack
2708 2660
2709 2661 def magic_dirs(self, parameter_s=''):
2710 2662 """Return the current directory stack."""
2711 2663
2712 2664 return self.shell.dir_stack[:]
2713 2665
2714 2666 def magic_sc(self, parameter_s=''):
2715 2667 """Shell capture - execute a shell command and capture its output.
2716 2668
2717 2669 DEPRECATED. Suboptimal, retained for backwards compatibility.
2718 2670
2719 2671 You should use the form 'var = !command' instead. Example:
2720 2672
2721 2673 "%sc -l myfiles = ls ~" should now be written as
2722 2674
2723 2675 "myfiles = !ls ~"
2724 2676
2725 2677 myfiles.s, myfiles.l and myfiles.n still apply as documented
2726 2678 below.
2727 2679
2728 2680 --
2729 2681 %sc [options] varname=command
2730 2682
2731 2683 IPython will run the given command using commands.getoutput(), and
2732 2684 will then update the user's interactive namespace with a variable
2733 2685 called varname, containing the value of the call. Your command can
2734 2686 contain shell wildcards, pipes, etc.
2735 2687
2736 2688 The '=' sign in the syntax is mandatory, and the variable name you
2737 2689 supply must follow Python's standard conventions for valid names.
2738 2690
2739 2691 (A special format without variable name exists for internal use)
2740 2692
2741 2693 Options:
2742 2694
2743 2695 -l: list output. Split the output on newlines into a list before
2744 2696 assigning it to the given variable. By default the output is stored
2745 2697 as a single string.
2746 2698
2747 2699 -v: verbose. Print the contents of the variable.
2748 2700
2749 2701 In most cases you should not need to split as a list, because the
2750 2702 returned value is a special type of string which can automatically
2751 2703 provide its contents either as a list (split on newlines) or as a
2752 2704 space-separated string. These are convenient, respectively, either
2753 2705 for sequential processing or to be passed to a shell command.
2754 2706
2755 2707 For example:
2756 2708
2757 2709 # Capture into variable a
2758 2710 In [9]: sc a=ls *py
2759 2711
2760 2712 # a is a string with embedded newlines
2761 2713 In [10]: a
2762 2714 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2763 2715
2764 2716 # which can be seen as a list:
2765 2717 In [11]: a.l
2766 2718 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2767 2719
2768 2720 # or as a whitespace-separated string:
2769 2721 In [12]: a.s
2770 2722 Out[12]: 'setup.py win32_manual_post_install.py'
2771 2723
2772 2724 # a.s is useful to pass as a single command line:
2773 2725 In [13]: !wc -l $a.s
2774 2726 146 setup.py
2775 2727 130 win32_manual_post_install.py
2776 2728 276 total
2777 2729
2778 2730 # while the list form is useful to loop over:
2779 2731 In [14]: for f in a.l:
2780 2732 ....: !wc -l $f
2781 2733 ....:
2782 2734 146 setup.py
2783 2735 130 win32_manual_post_install.py
2784 2736
2785 2737 Similiarly, the lists returned by the -l option are also special, in
2786 2738 the sense that you can equally invoke the .s attribute on them to
2787 2739 automatically get a whitespace-separated string from their contents:
2788 2740
2789 2741 In [1]: sc -l b=ls *py
2790 2742
2791 2743 In [2]: b
2792 2744 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2793 2745
2794 2746 In [3]: b.s
2795 2747 Out[3]: 'setup.py win32_manual_post_install.py'
2796 2748
2797 2749 In summary, both the lists and strings used for ouptut capture have
2798 2750 the following special attributes:
2799 2751
2800 2752 .l (or .list) : value as list.
2801 2753 .n (or .nlstr): value as newline-separated string.
2802 2754 .s (or .spstr): value as space-separated string.
2803 2755 """
2804 2756
2805 2757 opts,args = self.parse_options(parameter_s,'lv')
2806 2758 # Try to get a variable name and command to run
2807 2759 try:
2808 2760 # the variable name must be obtained from the parse_options
2809 2761 # output, which uses shlex.split to strip options out.
2810 2762 var,_ = args.split('=',1)
2811 2763 var = var.strip()
2812 2764 # But the the command has to be extracted from the original input
2813 2765 # parameter_s, not on what parse_options returns, to avoid the
2814 2766 # quote stripping which shlex.split performs on it.
2815 2767 _,cmd = parameter_s.split('=',1)
2816 2768 except ValueError:
2817 2769 var,cmd = '',''
2818 2770 # If all looks ok, proceed
2819 2771 out,err = self.shell.getoutputerror(cmd)
2820 2772 if err:
2821 2773 print >> Term.cerr,err
2822 2774 if opts.has_key('l'):
2823 2775 out = SList(out.split('\n'))
2824 2776 else:
2825 2777 out = LSString(out)
2826 2778 if opts.has_key('v'):
2827 2779 print '%s ==\n%s' % (var,pformat(out))
2828 2780 if var:
2829 2781 self.shell.user_ns.update({var:out})
2830 2782 else:
2831 2783 return out
2832 2784
2833 2785 def magic_sx(self, parameter_s=''):
2834 2786 """Shell execute - run a shell command and capture its output.
2835 2787
2836 2788 %sx command
2837 2789
2838 2790 IPython will run the given command using commands.getoutput(), and
2839 2791 return the result formatted as a list (split on '\\n'). Since the
2840 2792 output is _returned_, it will be stored in ipython's regular output
2841 2793 cache Out[N] and in the '_N' automatic variables.
2842 2794
2843 2795 Notes:
2844 2796
2845 2797 1) If an input line begins with '!!', then %sx is automatically
2846 2798 invoked. That is, while:
2847 2799 !ls
2848 2800 causes ipython to simply issue system('ls'), typing
2849 2801 !!ls
2850 2802 is a shorthand equivalent to:
2851 2803 %sx ls
2852 2804
2853 2805 2) %sx differs from %sc in that %sx automatically splits into a list,
2854 2806 like '%sc -l'. The reason for this is to make it as easy as possible
2855 2807 to process line-oriented shell output via further python commands.
2856 2808 %sc is meant to provide much finer control, but requires more
2857 2809 typing.
2858 2810
2859 2811 3) Just like %sc -l, this is a list with special attributes:
2860 2812
2861 2813 .l (or .list) : value as list.
2862 2814 .n (or .nlstr): value as newline-separated string.
2863 2815 .s (or .spstr): value as whitespace-separated string.
2864 2816
2865 2817 This is very useful when trying to use such lists as arguments to
2866 2818 system commands."""
2867 2819
2868 2820 if parameter_s:
2869 2821 out,err = self.shell.getoutputerror(parameter_s)
2870 2822 if err:
2871 2823 print >> Term.cerr,err
2872 2824 return SList(out.split('\n'))
2873 2825
2874 2826 def magic_bg(self, parameter_s=''):
2875 2827 """Run a job in the background, in a separate thread.
2876 2828
2877 2829 For example,
2878 2830
2879 2831 %bg myfunc(x,y,z=1)
2880 2832
2881 2833 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2882 2834 execution starts, a message will be printed indicating the job
2883 2835 number. If your job number is 5, you can use
2884 2836
2885 2837 myvar = jobs.result(5) or myvar = jobs[5].result
2886 2838
2887 2839 to assign this result to variable 'myvar'.
2888 2840
2889 2841 IPython has a job manager, accessible via the 'jobs' object. You can
2890 2842 type jobs? to get more information about it, and use jobs.<TAB> to see
2891 2843 its attributes. All attributes not starting with an underscore are
2892 2844 meant for public use.
2893 2845
2894 2846 In particular, look at the jobs.new() method, which is used to create
2895 2847 new jobs. This magic %bg function is just a convenience wrapper
2896 2848 around jobs.new(), for expression-based jobs. If you want to create a
2897 2849 new job with an explicit function object and arguments, you must call
2898 2850 jobs.new() directly.
2899 2851
2900 2852 The jobs.new docstring also describes in detail several important
2901 2853 caveats associated with a thread-based model for background job
2902 2854 execution. Type jobs.new? for details.
2903 2855
2904 2856 You can check the status of all jobs with jobs.status().
2905 2857
2906 2858 The jobs variable is set by IPython into the Python builtin namespace.
2907 2859 If you ever declare a variable named 'jobs', you will shadow this
2908 2860 name. You can either delete your global jobs variable to regain
2909 2861 access to the job manager, or make a new name and assign it manually
2910 2862 to the manager (stored in IPython's namespace). For example, to
2911 2863 assign the job manager to the Jobs name, use:
2912 2864
2913 2865 Jobs = __builtins__.jobs"""
2914 2866
2915 2867 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2916 2868
2917 2869
2918 2870 def magic_bookmark(self, parameter_s=''):
2919 2871 """Manage IPython's bookmark system.
2920 2872
2921 2873 %bookmark <name> - set bookmark to current dir
2922 2874 %bookmark <name> <dir> - set bookmark to <dir>
2923 2875 %bookmark -l - list all bookmarks
2924 2876 %bookmark -d <name> - remove bookmark
2925 2877 %bookmark -r - remove all bookmarks
2926 2878
2927 2879 You can later on access a bookmarked folder with:
2928 2880 %cd -b <name>
2929 2881 or simply '%cd <name>' if there is no directory called <name> AND
2930 2882 there is such a bookmark defined.
2931 2883
2932 2884 Your bookmarks persist through IPython sessions, but they are
2933 2885 associated with each profile."""
2934 2886
2935 2887 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2936 2888 if len(args) > 2:
2937 2889 error('You can only give at most two arguments')
2938 2890 return
2939 2891
2940 2892 bkms = self.db.get('bookmarks',{})
2941 2893
2942 2894 if opts.has_key('d'):
2943 2895 try:
2944 2896 todel = args[0]
2945 2897 except IndexError:
2946 2898 error('You must provide a bookmark to delete')
2947 2899 else:
2948 2900 try:
2949 2901 del bkms[todel]
2950 2902 except:
2951 2903 error("Can't delete bookmark '%s'" % todel)
2952 2904 elif opts.has_key('r'):
2953 2905 bkms = {}
2954 2906 elif opts.has_key('l'):
2955 2907 bks = bkms.keys()
2956 2908 bks.sort()
2957 2909 if bks:
2958 2910 size = max(map(len,bks))
2959 2911 else:
2960 2912 size = 0
2961 2913 fmt = '%-'+str(size)+'s -> %s'
2962 2914 print 'Current bookmarks:'
2963 2915 for bk in bks:
2964 2916 print fmt % (bk,bkms[bk])
2965 2917 else:
2966 2918 if not args:
2967 2919 error("You must specify the bookmark name")
2968 2920 elif len(args)==1:
2969 2921 bkms[args[0]] = os.getcwd()
2970 2922 elif len(args)==2:
2971 2923 bkms[args[0]] = args[1]
2972 2924 self.db['bookmarks'] = bkms
2973 2925
2974 2926 def magic_pycat(self, parameter_s=''):
2975 2927 """Show a syntax-highlighted file through a pager.
2976 2928
2977 2929 This magic is similar to the cat utility, but it will assume the file
2978 2930 to be Python source and will show it with syntax highlighting. """
2979 2931
2980 2932 try:
2981 2933 filename = get_py_filename(parameter_s)
2982 2934 cont = file_read(filename)
2983 2935 except IOError:
2984 2936 try:
2985 2937 cont = eval(parameter_s,self.user_ns)
2986 2938 except NameError:
2987 2939 cont = None
2988 2940 if cont is None:
2989 2941 print "Error: no such file or variable"
2990 2942 return
2991 2943
2992 2944 page(self.shell.pycolorize(cont),
2993 2945 screen_lines=self.shell.rc.screen_length)
2994 2946
2995 2947 def magic_cpaste(self, parameter_s=''):
2996 2948 """Allows you to paste & execute a pre-formatted code block from clipboard
2997 2949
2998 2950 You must terminate the block with '--' (two minus-signs) alone on the
2999 2951 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3000 2952 is the new sentinel for this operation)
3001 2953
3002 2954 The block is dedented prior to execution to enable execution of
3003 2955 method definitions. '>' characters at the beginning of a line is
3004 2956 ignored, to allow pasting directly from e-mails. The executed block
3005 2957 is also assigned to variable named 'pasted_block' for later editing
3006 2958 with '%edit pasted_block'.
3007 2959
3008 2960 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3009 2961 This assigns the pasted block to variable 'foo' as string, without
3010 2962 dedenting or executing it.
3011 2963
3012 2964 Do not be alarmed by garbled output on Windows (it's a readline bug).
3013 2965 Just press enter and type -- (and press enter again) and the block
3014 2966 will be what was just pasted.
3015 2967
3016 2968 IPython statements (magics, shell escapes) are not supported (yet).
3017 2969 """
3018 2970 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3019 2971 par = args.strip()
3020 2972 sentinel = opts.get('s','--')
3021 2973
3022 2974 from IPython import iplib
3023 2975 lines = []
3024 2976 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3025 2977 while 1:
3026 2978 l = iplib.raw_input_original(':')
3027 2979 if l ==sentinel:
3028 2980 break
3029 2981 lines.append(l.lstrip('>'))
3030 2982 block = "\n".join(lines) + '\n'
3031 2983 #print "block:\n",block
3032 2984 if not par:
3033 2985 b = textwrap.dedent(block)
3034 2986 exec b in self.user_ns
3035 2987 self.user_ns['pasted_block'] = b
3036 2988 else:
3037 2989 self.user_ns[par] = block
3038 2990 print "Block assigned to '%s'" % par
3039 2991
3040 2992 def magic_quickref(self,arg):
3041 2993 """ Show a quick reference sheet """
3042 2994 import IPython.usage
3043 2995 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3044 2996
3045 2997 page(qr)
3046 2998
3047 2999 def magic_upgrade(self,arg):
3048 3000 """ Upgrade your IPython installation
3049 3001
3050 3002 This will copy the config files that don't yet exist in your
3051 3003 ipython dir from the system config dir. Use this after upgrading
3052 3004 IPython if you don't wish to delete your .ipython dir.
3053 3005
3054 3006 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3055 3007 new users)
3056 3008
3057 3009 """
3058 3010 ip = self.getapi()
3059 3011 ipinstallation = path(IPython.__file__).dirname()
3060 3012 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3061 3013 src_config = ipinstallation / 'UserConfig'
3062 3014 userdir = path(ip.options.ipythondir)
3063 3015 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3064 3016 print ">",cmd
3065 3017 shell(cmd)
3066 3018 if arg == '-nolegacy':
3067 3019 legacy = userdir.files('ipythonrc*')
3068 3020 print "Nuking legacy files:",legacy
3069 3021
3070 3022 [p.remove() for p in legacy]
3071 3023 suffix = (sys.platform == 'win32' and '.ini' or '')
3072 3024 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3073 3025
3074 3026
3075 3027 # end Magic
@@ -1,2548 +1,2524 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.3 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 1885 2006-11-08 01:07:28Z fperez $
9 $Id: iplib.py 1934 2006-11-26 20:37:01Z vivainio $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from IPython import Release
32 32 __author__ = '%s <%s>\n%s <%s>' % \
33 33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 34 __license__ = Release.license
35 35 __version__ = Release.version
36 36
37 37 # Python standard modules
38 38 import __main__
39 39 import __builtin__
40 40 import StringIO
41 41 import bdb
42 42 import cPickle as pickle
43 43 import codeop
44 44 import exceptions
45 45 import glob
46 46 import inspect
47 47 import keyword
48 48 import new
49 49 import os
50 50 import pydoc
51 51 import re
52 52 import shutil
53 53 import string
54 54 import sys
55 55 import tempfile
56 56 import traceback
57 57 import types
58 58 import pickleshare
59 59 from sets import Set
60 60 from pprint import pprint, pformat
61 61
62 62 # IPython's own modules
63 63 import IPython
64 64 from IPython import OInspect,PyColorize,ultraTB
65 65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 66 from IPython.FakeModule import FakeModule
67 67 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 68 from IPython.Logger import Logger
69 69 from IPython.Magic import Magic
70 70 from IPython.Prompts import CachedOutput
71 71 from IPython.ipstruct import Struct
72 72 from IPython.background_jobs import BackgroundJobManager
73 73 from IPython.usage import cmd_line_usage,interactive_usage
74 74 from IPython.genutils import *
75 75 from IPython.strdispatch import StrDispatch
76 76 import IPython.ipapi
77 77
78 78 # Globals
79 79
80 80 # store the builtin raw_input globally, and use this always, in case user code
81 81 # overwrites it (like wx.py.PyShell does)
82 82 raw_input_original = raw_input
83 83
84 84 # compiled regexps for autoindent management
85 85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 86
87 87
88 88 #****************************************************************************
89 89 # Some utility function definitions
90 90
91 91 ini_spaces_re = re.compile(r'^(\s+)')
92 92
93 93 def num_ini_spaces(strng):
94 94 """Return the number of initial spaces in a string"""
95 95
96 96 ini_spaces = ini_spaces_re.match(strng)
97 97 if ini_spaces:
98 98 return ini_spaces.end()
99 99 else:
100 100 return 0
101 101
102 102 def softspace(file, newvalue):
103 103 """Copied from code.py, to remove the dependency"""
104 104
105 105 oldvalue = 0
106 106 try:
107 107 oldvalue = file.softspace
108 108 except AttributeError:
109 109 pass
110 110 try:
111 111 file.softspace = newvalue
112 112 except (AttributeError, TypeError):
113 113 # "attribute-less object" or "read-only attributes"
114 114 pass
115 115 return oldvalue
116 116
117 117
118 118 #****************************************************************************
119 119 # Local use exceptions
120 120 class SpaceInInput(exceptions.Exception): pass
121 121
122 122
123 123 #****************************************************************************
124 124 # Local use classes
125 125 class Bunch: pass
126 126
127 127 class Undefined: pass
128 128
129 129 class Quitter(object):
130 130 """Simple class to handle exit, similar to Python 2.5's.
131 131
132 132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
133 133 doesn't do (obviously, since it doesn't know about ipython)."""
134 134
135 135 def __init__(self,shell,name):
136 136 self.shell = shell
137 137 self.name = name
138 138
139 139 def __repr__(self):
140 140 return 'Type %s() to exit.' % self.name
141 141 __str__ = __repr__
142 142
143 143 def __call__(self):
144 144 self.shell.exit()
145 145
146 146 class InputList(list):
147 147 """Class to store user input.
148 148
149 149 It's basically a list, but slices return a string instead of a list, thus
150 150 allowing things like (assuming 'In' is an instance):
151 151
152 152 exec In[4:7]
153 153
154 154 or
155 155
156 156 exec In[5:9] + In[14] + In[21:25]"""
157 157
158 158 def __getslice__(self,i,j):
159 159 return ''.join(list.__getslice__(self,i,j))
160 160
161 161 class SyntaxTB(ultraTB.ListTB):
162 162 """Extension which holds some state: the last exception value"""
163 163
164 164 def __init__(self,color_scheme = 'NoColor'):
165 165 ultraTB.ListTB.__init__(self,color_scheme)
166 166 self.last_syntax_error = None
167 167
168 168 def __call__(self, etype, value, elist):
169 169 self.last_syntax_error = value
170 170 ultraTB.ListTB.__call__(self,etype,value,elist)
171 171
172 172 def clear_err_state(self):
173 173 """Return the current error state and clear it"""
174 174 e = self.last_syntax_error
175 175 self.last_syntax_error = None
176 176 return e
177 177
178 178 #****************************************************************************
179 179 # Main IPython class
180 180
181 181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
182 182 # until a full rewrite is made. I've cleaned all cross-class uses of
183 183 # attributes and methods, but too much user code out there relies on the
184 184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
185 185 #
186 186 # But at least now, all the pieces have been separated and we could, in
187 187 # principle, stop using the mixin. This will ease the transition to the
188 188 # chainsaw branch.
189 189
190 190 # For reference, the following is the list of 'self.foo' uses in the Magic
191 191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
192 192 # class, to prevent clashes.
193 193
194 194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
195 195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
196 196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
197 197 # 'self.value']
198 198
199 199 class InteractiveShell(object,Magic):
200 200 """An enhanced console for Python."""
201 201
202 202 # class attribute to indicate whether the class supports threads or not.
203 203 # Subclasses with thread support should override this as needed.
204 204 isthreaded = False
205 205
206 206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
207 207 user_ns = None,user_global_ns=None,banner2='',
208 208 custom_exceptions=((),None),embedded=False):
209 209
210 210 # log system
211 211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
212 212
213 213 # some minimal strict typechecks. For some core data structures, I
214 214 # want actual basic python types, not just anything that looks like
215 215 # one. This is especially true for namespaces.
216 216 for ns in (user_ns,user_global_ns):
217 217 if ns is not None and type(ns) != types.DictType:
218 218 raise TypeError,'namespace must be a dictionary'
219 219
220 220 # Job manager (for jobs run as background threads)
221 221 self.jobs = BackgroundJobManager()
222 222
223 223 # Store the actual shell's name
224 224 self.name = name
225 225
226 226 # We need to know whether the instance is meant for embedding, since
227 227 # global/local namespaces need to be handled differently in that case
228 228 self.embedded = embedded
229 229
230 230 # command compiler
231 231 self.compile = codeop.CommandCompiler()
232 232
233 233 # User input buffer
234 234 self.buffer = []
235 235
236 236 # Default name given in compilation of code
237 237 self.filename = '<ipython console>'
238 238
239 239 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 240 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 241 __builtin__.exit = Quitter(self,'exit')
242 242 __builtin__.quit = Quitter(self,'quit')
243 243
244 244 # Make an empty namespace, which extension writers can rely on both
245 245 # existing and NEVER being used by ipython itself. This gives them a
246 246 # convenient location for storing additional information and state
247 247 # their extensions may require, without fear of collisions with other
248 248 # ipython names that may develop later.
249 249 self.meta = Struct()
250 250
251 251 # Create the namespace where the user will operate. user_ns is
252 252 # normally the only one used, and it is passed to the exec calls as
253 253 # the locals argument. But we do carry a user_global_ns namespace
254 254 # given as the exec 'globals' argument, This is useful in embedding
255 255 # situations where the ipython shell opens in a context where the
256 256 # distinction between locals and globals is meaningful.
257 257
258 258 # FIXME. For some strange reason, __builtins__ is showing up at user
259 259 # level as a dict instead of a module. This is a manual fix, but I
260 260 # should really track down where the problem is coming from. Alex
261 261 # Schmolck reported this problem first.
262 262
263 263 # A useful post by Alex Martelli on this topic:
264 264 # Re: inconsistent value from __builtins__
265 265 # Von: Alex Martelli <aleaxit@yahoo.com>
266 266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
267 267 # Gruppen: comp.lang.python
268 268
269 269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
270 270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
271 271 # > <type 'dict'>
272 272 # > >>> print type(__builtins__)
273 273 # > <type 'module'>
274 274 # > Is this difference in return value intentional?
275 275
276 276 # Well, it's documented that '__builtins__' can be either a dictionary
277 277 # or a module, and it's been that way for a long time. Whether it's
278 278 # intentional (or sensible), I don't know. In any case, the idea is
279 279 # that if you need to access the built-in namespace directly, you
280 280 # should start with "import __builtin__" (note, no 's') which will
281 281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
282 282
283 283 # These routines return properly built dicts as needed by the rest of
284 284 # the code, and can also be used by extension writers to generate
285 285 # properly initialized namespaces.
286 286 user_ns = IPython.ipapi.make_user_ns(user_ns)
287 287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
288 288
289 289 # Assign namespaces
290 290 # This is the namespace where all normal user variables live
291 291 self.user_ns = user_ns
292 292 # Embedded instances require a separate namespace for globals.
293 293 # Normally this one is unused by non-embedded instances.
294 294 self.user_global_ns = user_global_ns
295 295 # A namespace to keep track of internal data structures to prevent
296 296 # them from cluttering user-visible stuff. Will be updated later
297 297 self.internal_ns = {}
298 298
299 299 # Namespace of system aliases. Each entry in the alias
300 300 # table must be a 2-tuple of the form (N,name), where N is the number
301 301 # of positional arguments of the alias.
302 302 self.alias_table = {}
303 303
304 304 # A table holding all the namespaces IPython deals with, so that
305 305 # introspection facilities can search easily.
306 306 self.ns_table = {'user':user_ns,
307 307 'user_global':user_global_ns,
308 308 'alias':self.alias_table,
309 309 'internal':self.internal_ns,
310 310 'builtin':__builtin__.__dict__
311 311 }
312 312
313 313 # The user namespace MUST have a pointer to the shell itself.
314 314 self.user_ns[name] = self
315 315
316 316 # We need to insert into sys.modules something that looks like a
317 317 # module but which accesses the IPython namespace, for shelve and
318 318 # pickle to work interactively. Normally they rely on getting
319 319 # everything out of __main__, but for embedding purposes each IPython
320 320 # instance has its own private namespace, so we can't go shoving
321 321 # everything into __main__.
322 322
323 323 # note, however, that we should only do this for non-embedded
324 324 # ipythons, which really mimic the __main__.__dict__ with their own
325 325 # namespace. Embedded instances, on the other hand, should not do
326 326 # this because they need to manage the user local/global namespaces
327 327 # only, but they live within a 'normal' __main__ (meaning, they
328 328 # shouldn't overtake the execution environment of the script they're
329 329 # embedded in).
330 330
331 331 if not embedded:
332 332 try:
333 333 main_name = self.user_ns['__name__']
334 334 except KeyError:
335 335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 336 else:
337 337 #print "pickle hack in place" # dbg
338 338 #print 'main_name:',main_name # dbg
339 339 sys.modules[main_name] = FakeModule(self.user_ns)
340 340
341 341 # List of input with multi-line handling.
342 342 # Fill its zero entry, user counter starts at 1
343 343 self.input_hist = InputList(['\n'])
344 344 # This one will hold the 'raw' input history, without any
345 345 # pre-processing. This will allow users to retrieve the input just as
346 346 # it was exactly typed in by the user, with %hist -r.
347 347 self.input_hist_raw = InputList(['\n'])
348 348
349 349 # list of visited directories
350 350 try:
351 351 self.dir_hist = [os.getcwd()]
352 352 except IOError, e:
353 353 self.dir_hist = []
354 354
355 355 # dict of output history
356 356 self.output_hist = {}
357 357
358 358 # dict of things NOT to alias (keywords, builtins and some magics)
359 359 no_alias = {}
360 360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
361 361 for key in keyword.kwlist + no_alias_magics:
362 362 no_alias[key] = 1
363 363 no_alias.update(__builtin__.__dict__)
364 364 self.no_alias = no_alias
365 365
366 366 # make global variables for user access to these
367 367 self.user_ns['_ih'] = self.input_hist
368 368 self.user_ns['_oh'] = self.output_hist
369 369 self.user_ns['_dh'] = self.dir_hist
370 370
371 371 # user aliases to input and output histories
372 372 self.user_ns['In'] = self.input_hist
373 373 self.user_ns['Out'] = self.output_hist
374 374
375 375 # Object variable to store code object waiting execution. This is
376 376 # used mainly by the multithreaded shells, but it can come in handy in
377 377 # other situations. No need to use a Queue here, since it's a single
378 378 # item which gets cleared once run.
379 379 self.code_to_run = None
380 380
381 381 # escapes for automatic behavior on the command line
382 382 self.ESC_SHELL = '!'
383 383 self.ESC_HELP = '?'
384 384 self.ESC_MAGIC = '%'
385 385 self.ESC_QUOTE = ','
386 386 self.ESC_QUOTE2 = ';'
387 387 self.ESC_PAREN = '/'
388 388
389 389 # And their associated handlers
390 390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
391 391 self.ESC_QUOTE : self.handle_auto,
392 392 self.ESC_QUOTE2 : self.handle_auto,
393 393 self.ESC_MAGIC : self.handle_magic,
394 394 self.ESC_HELP : self.handle_help,
395 395 self.ESC_SHELL : self.handle_shell_escape,
396 396 }
397 397
398 398 # class initializations
399 399 Magic.__init__(self,self)
400 400
401 401 # Python source parser/formatter for syntax highlighting
402 402 pyformat = PyColorize.Parser().format
403 403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
404 404
405 405 # hooks holds pointers used for user-side customizations
406 406 self.hooks = Struct()
407 407
408 408 self.strdispatchers = {}
409 409
410 410 # Set all default hooks, defined in the IPython.hooks module.
411 411 hooks = IPython.hooks
412 412 for hook_name in hooks.__all__:
413 413 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
414 414 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
415 415 #print "bound hook",hook_name
416 416
417 417 # Flag to mark unconditional exit
418 418 self.exit_now = False
419 419
420 420 self.usage_min = """\
421 421 An enhanced console for Python.
422 422 Some of its features are:
423 423 - Readline support if the readline library is present.
424 424 - Tab completion in the local namespace.
425 425 - Logging of input, see command-line options.
426 426 - System shell escape via ! , eg !ls.
427 427 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
428 428 - Keeps track of locally defined variables via %who, %whos.
429 429 - Show object information with a ? eg ?x or x? (use ?? for more info).
430 430 """
431 431 if usage: self.usage = usage
432 432 else: self.usage = self.usage_min
433 433
434 434 # Storage
435 435 self.rc = rc # This will hold all configuration information
436 436 self.pager = 'less'
437 437 # temporary files used for various purposes. Deleted at exit.
438 438 self.tempfiles = []
439 439
440 440 # Keep track of readline usage (later set by init_readline)
441 441 self.has_readline = False
442 442
443 443 # template for logfile headers. It gets resolved at runtime by the
444 444 # logstart method.
445 445 self.loghead_tpl = \
446 446 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
447 447 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
448 448 #log# opts = %s
449 449 #log# args = %s
450 450 #log# It is safe to make manual edits below here.
451 451 #log#-----------------------------------------------------------------------
452 452 """
453 453 # for pushd/popd management
454 454 try:
455 455 self.home_dir = get_home_dir()
456 456 except HomeDirError,msg:
457 457 fatal(msg)
458 458
459 459 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
460 460
461 461 # Functions to call the underlying shell.
462 462
463 463 # The first is similar to os.system, but it doesn't return a value,
464 464 # and it allows interpolation of variables in the user's namespace.
465 465 self.system = lambda cmd: \
466 466 shell(self.var_expand(cmd,depth=2),
467 467 header=self.rc.system_header,
468 468 verbose=self.rc.system_verbose)
469 469
470 470 # These are for getoutput and getoutputerror:
471 471 self.getoutput = lambda cmd: \
472 472 getoutput(self.var_expand(cmd,depth=2),
473 473 header=self.rc.system_header,
474 474 verbose=self.rc.system_verbose)
475 475
476 476 self.getoutputerror = lambda cmd: \
477 477 getoutputerror(self.var_expand(cmd,depth=2),
478 478 header=self.rc.system_header,
479 479 verbose=self.rc.system_verbose)
480 480
481 481 # RegExp for splitting line contents into pre-char//first
482 482 # word-method//rest. For clarity, each group in on one line.
483 483
484 484 # WARNING: update the regexp if the above escapes are changed, as they
485 485 # are hardwired in.
486 486
487 487 # Don't get carried away with trying to make the autocalling catch too
488 488 # much: it's better to be conservative rather than to trigger hidden
489 489 # evals() somewhere and end up causing side effects.
490 490
491 491 self.line_split = re.compile(r'^([\s*,;/])'
492 492 r'([\?\w\.]+\w*\s*)'
493 493 r'(\(?.*$)')
494 494
495 495 # Original re, keep around for a while in case changes break something
496 496 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
497 497 # r'(\s*[\?\w\.]+\w*\s*)'
498 498 # r'(\(?.*$)')
499 499
500 500 # RegExp to identify potential function names
501 501 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
502 502
503 503 # RegExp to exclude strings with this start from autocalling. In
504 504 # particular, all binary operators should be excluded, so that if foo
505 505 # is callable, foo OP bar doesn't become foo(OP bar), which is
506 506 # invalid. The characters '!=()' don't need to be checked for, as the
507 507 # _prefilter routine explicitely does so, to catch direct calls and
508 508 # rebindings of existing names.
509 509
510 510 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
511 511 # it affects the rest of the group in square brackets.
512 512 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
513 513 '|^is |^not |^in |^and |^or ')
514 514
515 515 # try to catch also methods for stuff in lists/tuples/dicts: off
516 516 # (experimental). For this to work, the line_split regexp would need
517 517 # to be modified so it wouldn't break things at '['. That line is
518 518 # nasty enough that I shouldn't change it until I can test it _well_.
519 519 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
520 520
521 521 # keep track of where we started running (mainly for crash post-mortem)
522 522 self.starting_dir = os.getcwd()
523 523
524 524 # Various switches which can be set
525 525 self.CACHELENGTH = 5000 # this is cheap, it's just text
526 526 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
527 527 self.banner2 = banner2
528 528
529 529 # TraceBack handlers:
530 530
531 531 # Syntax error handler.
532 532 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
533 533
534 534 # The interactive one is initialized with an offset, meaning we always
535 535 # want to remove the topmost item in the traceback, which is our own
536 536 # internal code. Valid modes: ['Plain','Context','Verbose']
537 537 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
538 538 color_scheme='NoColor',
539 539 tb_offset = 1)
540 540
541 541 # IPython itself shouldn't crash. This will produce a detailed
542 542 # post-mortem if it does. But we only install the crash handler for
543 543 # non-threaded shells, the threaded ones use a normal verbose reporter
544 544 # and lose the crash handler. This is because exceptions in the main
545 545 # thread (such as in GUI code) propagate directly to sys.excepthook,
546 546 # and there's no point in printing crash dumps for every user exception.
547 547 if self.isthreaded:
548 548 ipCrashHandler = ultraTB.FormattedTB()
549 549 else:
550 550 from IPython import CrashHandler
551 551 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
552 552 self.set_crash_handler(ipCrashHandler)
553 553
554 554 # and add any custom exception handlers the user may have specified
555 555 self.set_custom_exc(*custom_exceptions)
556 556
557 557 # indentation management
558 558 self.autoindent = False
559 559 self.indent_current_nsp = 0
560 560
561 561 # Make some aliases automatically
562 562 # Prepare list of shell aliases to auto-define
563 563 if os.name == 'posix':
564 564 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
565 565 'mv mv -i','rm rm -i','cp cp -i',
566 566 'cat cat','less less','clear clear',
567 567 # a better ls
568 568 'ls ls -F',
569 569 # long ls
570 570 'll ls -lF')
571 571 # Extra ls aliases with color, which need special treatment on BSD
572 572 # variants
573 573 ls_extra = ( # color ls
574 574 'lc ls -F -o --color',
575 575 # ls normal files only
576 576 'lf ls -F -o --color %l | grep ^-',
577 577 # ls symbolic links
578 578 'lk ls -F -o --color %l | grep ^l',
579 579 # directories or links to directories,
580 580 'ldir ls -F -o --color %l | grep /$',
581 581 # things which are executable
582 582 'lx ls -F -o --color %l | grep ^-..x',
583 583 )
584 584 # The BSDs don't ship GNU ls, so they don't understand the
585 585 # --color switch out of the box
586 586 if 'bsd' in sys.platform:
587 587 ls_extra = ( # ls normal files only
588 588 'lf ls -lF | grep ^-',
589 589 # ls symbolic links
590 590 'lk ls -lF | grep ^l',
591 591 # directories or links to directories,
592 592 'ldir ls -lF | grep /$',
593 593 # things which are executable
594 594 'lx ls -lF | grep ^-..x',
595 595 )
596 596 auto_alias = auto_alias + ls_extra
597 597 elif os.name in ['nt','dos']:
598 598 auto_alias = ('dir dir /on', 'ls dir /on',
599 599 'ddir dir /ad /on', 'ldir dir /ad /on',
600 600 'mkdir mkdir','rmdir rmdir','echo echo',
601 601 'ren ren','cls cls','copy copy')
602 602 else:
603 603 auto_alias = ()
604 604 self.auto_alias = [s.split(None,1) for s in auto_alias]
605 605 # Call the actual (public) initializer
606 606 self.init_auto_alias()
607 607
608 608 # Produce a public API instance
609 609 self.api = IPython.ipapi.IPApi(self)
610 610
611 611 # track which builtins we add, so we can clean up later
612 612 self.builtins_added = {}
613 613 # This method will add the necessary builtins for operation, but
614 614 # tracking what it did via the builtins_added dict.
615 615 self.add_builtins()
616 616
617 617 # end __init__
618 618
619 619 def var_expand(self,cmd,depth=0):
620 620 """Expand python variables in a string.
621 621
622 622 The depth argument indicates how many frames above the caller should
623 623 be walked to look for the local namespace where to expand variables.
624 624
625 625 The global namespace for expansion is always the user's interactive
626 626 namespace.
627 627 """
628 628
629 629 return str(ItplNS(cmd.replace('#','\#'),
630 630 self.user_ns, # globals
631 631 # Skip our own frame in searching for locals:
632 632 sys._getframe(depth+1).f_locals # locals
633 633 ))
634 634
635 635 def pre_config_initialization(self):
636 636 """Pre-configuration init method
637 637
638 638 This is called before the configuration files are processed to
639 639 prepare the services the config files might need.
640 640
641 641 self.rc already has reasonable default values at this point.
642 642 """
643 643 rc = self.rc
644 644
645 645 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
646 646
647 647 def post_config_initialization(self):
648 648 """Post configuration init method
649 649
650 650 This is called after the configuration files have been processed to
651 651 'finalize' the initialization."""
652 652
653 653 rc = self.rc
654 654
655 655 # Object inspector
656 656 self.inspector = OInspect.Inspector(OInspect.InspectColors,
657 657 PyColorize.ANSICodeColors,
658 658 'NoColor',
659 659 rc.object_info_string_level)
660 660
661 661 # Load readline proper
662 662 if rc.readline:
663 663 self.init_readline()
664 664
665 665 # local shortcut, this is used a LOT
666 666 self.log = self.logger.log
667 667
668 668 # Initialize cache, set in/out prompts and printing system
669 669 self.outputcache = CachedOutput(self,
670 670 rc.cache_size,
671 671 rc.pprint,
672 672 input_sep = rc.separate_in,
673 673 output_sep = rc.separate_out,
674 674 output_sep2 = rc.separate_out2,
675 675 ps1 = rc.prompt_in1,
676 676 ps2 = rc.prompt_in2,
677 677 ps_out = rc.prompt_out,
678 678 pad_left = rc.prompts_pad_left)
679 679
680 680 # user may have over-ridden the default print hook:
681 681 try:
682 682 self.outputcache.__class__.display = self.hooks.display
683 683 except AttributeError:
684 684 pass
685 685
686 686 # I don't like assigning globally to sys, because it means when
687 687 # embedding instances, each embedded instance overrides the previous
688 688 # choice. But sys.displayhook seems to be called internally by exec,
689 689 # so I don't see a way around it. We first save the original and then
690 690 # overwrite it.
691 691 self.sys_displayhook = sys.displayhook
692 692 sys.displayhook = self.outputcache
693 693
694 694 # Set user colors (don't do it in the constructor above so that it
695 695 # doesn't crash if colors option is invalid)
696 696 self.magic_colors(rc.colors)
697 697
698 698 # Set calling of pdb on exceptions
699 699 self.call_pdb = rc.pdb
700 700
701 701 # Load user aliases
702 702 for alias in rc.alias:
703 703 self.magic_alias(alias)
704 704 self.hooks.late_startup_hook()
705 705
706 706 batchrun = False
707 707 for batchfile in [path(arg) for arg in self.rc.args
708 708 if arg.lower().endswith('.ipy')]:
709 709 if not batchfile.isfile():
710 710 print "No such batch file:", batchfile
711 711 continue
712 712 self.api.runlines(batchfile.text())
713 713 batchrun = True
714 714 if batchrun:
715 715 self.exit_now = True
716 716
717 717 def add_builtins(self):
718 718 """Store ipython references into the builtin namespace.
719 719
720 720 Some parts of ipython operate via builtins injected here, which hold a
721 721 reference to IPython itself."""
722 722
723 723 # TODO: deprecate all except _ip; 'jobs' should be installed
724 724 # by an extension and the rest are under _ip, ipalias is redundant
725 725 builtins_new = dict(__IPYTHON__ = self,
726 726 ip_set_hook = self.set_hook,
727 727 jobs = self.jobs,
728 728 ipmagic = self.ipmagic,
729 729 ipalias = self.ipalias,
730 730 ipsystem = self.ipsystem,
731 ipconfig = self.ipconfig,
732 731 _ip = self.api
733 732 )
734 733 for biname,bival in builtins_new.items():
735 734 try:
736 735 # store the orignal value so we can restore it
737 736 self.builtins_added[biname] = __builtin__.__dict__[biname]
738 737 except KeyError:
739 738 # or mark that it wasn't defined, and we'll just delete it at
740 739 # cleanup
741 740 self.builtins_added[biname] = Undefined
742 741 __builtin__.__dict__[biname] = bival
743 742
744 743 # Keep in the builtins a flag for when IPython is active. We set it
745 744 # with setdefault so that multiple nested IPythons don't clobber one
746 745 # another. Each will increase its value by one upon being activated,
747 746 # which also gives us a way to determine the nesting level.
748 747 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
749 748
750 749 def clean_builtins(self):
751 750 """Remove any builtins which might have been added by add_builtins, or
752 751 restore overwritten ones to their previous values."""
753 752 for biname,bival in self.builtins_added.items():
754 753 if bival is Undefined:
755 754 del __builtin__.__dict__[biname]
756 755 else:
757 756 __builtin__.__dict__[biname] = bival
758 757 self.builtins_added.clear()
759 758
760 759 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
761 760 """set_hook(name,hook) -> sets an internal IPython hook.
762 761
763 762 IPython exposes some of its internal API as user-modifiable hooks. By
764 763 adding your function to one of these hooks, you can modify IPython's
765 764 behavior to call at runtime your own routines."""
766 765
767 766 # At some point in the future, this should validate the hook before it
768 767 # accepts it. Probably at least check that the hook takes the number
769 768 # of args it's supposed to.
770 769
771 770 f = new.instancemethod(hook,self,self.__class__)
772 771
773 772 # check if the hook is for strdispatcher first
774 773 if str_key is not None:
775 774 sdp = self.strdispatchers.get(name, StrDispatch())
776 775 sdp.add_s(str_key, f, priority )
777 776 self.strdispatchers[name] = sdp
778 777 return
779 778 if re_key is not None:
780 779 sdp = self.strdispatchers.get(name, StrDispatch())
781 780 sdp.add_re(re.compile(re_key), f, priority )
782 781 self.strdispatchers[name] = sdp
783 782 return
784 783
785 784 dp = getattr(self.hooks, name, None)
786 785 if name not in IPython.hooks.__all__:
787 786 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
788 787 if not dp:
789 788 dp = IPython.hooks.CommandChainDispatcher()
790 789
791 790 try:
792 791 dp.add(f,priority)
793 792 except AttributeError:
794 793 # it was not commandchain, plain old func - replace
795 794 dp = f
796 795
797 796 setattr(self.hooks,name, dp)
798 797
799 798
800 799 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
801 800
802 801 def set_crash_handler(self,crashHandler):
803 802 """Set the IPython crash handler.
804 803
805 804 This must be a callable with a signature suitable for use as
806 805 sys.excepthook."""
807 806
808 807 # Install the given crash handler as the Python exception hook
809 808 sys.excepthook = crashHandler
810 809
811 810 # The instance will store a pointer to this, so that runtime code
812 811 # (such as magics) can access it. This is because during the
813 812 # read-eval loop, it gets temporarily overwritten (to deal with GUI
814 813 # frameworks).
815 814 self.sys_excepthook = sys.excepthook
816 815
817 816
818 817 def set_custom_exc(self,exc_tuple,handler):
819 818 """set_custom_exc(exc_tuple,handler)
820 819
821 820 Set a custom exception handler, which will be called if any of the
822 821 exceptions in exc_tuple occur in the mainloop (specifically, in the
823 822 runcode() method.
824 823
825 824 Inputs:
826 825
827 826 - exc_tuple: a *tuple* of valid exceptions to call the defined
828 827 handler for. It is very important that you use a tuple, and NOT A
829 828 LIST here, because of the way Python's except statement works. If
830 829 you only want to trap a single exception, use a singleton tuple:
831 830
832 831 exc_tuple == (MyCustomException,)
833 832
834 833 - handler: this must be defined as a function with the following
835 834 basic interface: def my_handler(self,etype,value,tb).
836 835
837 836 This will be made into an instance method (via new.instancemethod)
838 837 of IPython itself, and it will be called if any of the exceptions
839 838 listed in the exc_tuple are caught. If the handler is None, an
840 839 internal basic one is used, which just prints basic info.
841 840
842 841 WARNING: by putting in your own exception handler into IPython's main
843 842 execution loop, you run a very good chance of nasty crashes. This
844 843 facility should only be used if you really know what you are doing."""
845 844
846 845 assert type(exc_tuple)==type(()) , \
847 846 "The custom exceptions must be given AS A TUPLE."
848 847
849 848 def dummy_handler(self,etype,value,tb):
850 849 print '*** Simple custom exception handler ***'
851 850 print 'Exception type :',etype
852 851 print 'Exception value:',value
853 852 print 'Traceback :',tb
854 853 print 'Source code :','\n'.join(self.buffer)
855 854
856 855 if handler is None: handler = dummy_handler
857 856
858 857 self.CustomTB = new.instancemethod(handler,self,self.__class__)
859 858 self.custom_exceptions = exc_tuple
860 859
861 860 def set_custom_completer(self,completer,pos=0):
862 861 """set_custom_completer(completer,pos=0)
863 862
864 863 Adds a new custom completer function.
865 864
866 865 The position argument (defaults to 0) is the index in the completers
867 866 list where you want the completer to be inserted."""
868 867
869 868 newcomp = new.instancemethod(completer,self.Completer,
870 869 self.Completer.__class__)
871 870 self.Completer.matchers.insert(pos,newcomp)
872 871
873 872 def _get_call_pdb(self):
874 873 return self._call_pdb
875 874
876 875 def _set_call_pdb(self,val):
877 876
878 877 if val not in (0,1,False,True):
879 878 raise ValueError,'new call_pdb value must be boolean'
880 879
881 880 # store value in instance
882 881 self._call_pdb = val
883 882
884 883 # notify the actual exception handlers
885 884 self.InteractiveTB.call_pdb = val
886 885 if self.isthreaded:
887 886 try:
888 887 self.sys_excepthook.call_pdb = val
889 888 except:
890 889 warn('Failed to activate pdb for threaded exception handler')
891 890
892 891 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
893 892 'Control auto-activation of pdb at exceptions')
894 893
895 894
896 895 # These special functions get installed in the builtin namespace, to
897 896 # provide programmatic (pure python) access to magics, aliases and system
898 897 # calls. This is important for logging, user scripting, and more.
899 898
900 899 # We are basically exposing, via normal python functions, the three
901 900 # mechanisms in which ipython offers special call modes (magics for
902 901 # internal control, aliases for direct system access via pre-selected
903 902 # names, and !cmd for calling arbitrary system commands).
904 903
905 904 def ipmagic(self,arg_s):
906 905 """Call a magic function by name.
907 906
908 907 Input: a string containing the name of the magic function to call and any
909 908 additional arguments to be passed to the magic.
910 909
911 910 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
912 911 prompt:
913 912
914 913 In[1]: %name -opt foo bar
915 914
916 915 To call a magic without arguments, simply use ipmagic('name').
917 916
918 917 This provides a proper Python function to call IPython's magics in any
919 918 valid Python code you can type at the interpreter, including loops and
920 919 compound statements. It is added by IPython to the Python builtin
921 920 namespace upon initialization."""
922 921
923 922 args = arg_s.split(' ',1)
924 923 magic_name = args[0]
925 924 magic_name = magic_name.lstrip(self.ESC_MAGIC)
926 925
927 926 try:
928 927 magic_args = args[1]
929 928 except IndexError:
930 929 magic_args = ''
931 930 fn = getattr(self,'magic_'+magic_name,None)
932 931 if fn is None:
933 932 error("Magic function `%s` not found." % magic_name)
934 933 else:
935 934 magic_args = self.var_expand(magic_args,1)
936 935 return fn(magic_args)
937 936
938 937 def ipalias(self,arg_s):
939 938 """Call an alias by name.
940 939
941 940 Input: a string containing the name of the alias to call and any
942 941 additional arguments to be passed to the magic.
943 942
944 943 ipalias('name -opt foo bar') is equivalent to typing at the ipython
945 944 prompt:
946 945
947 946 In[1]: name -opt foo bar
948 947
949 948 To call an alias without arguments, simply use ipalias('name').
950 949
951 950 This provides a proper Python function to call IPython's aliases in any
952 951 valid Python code you can type at the interpreter, including loops and
953 952 compound statements. It is added by IPython to the Python builtin
954 953 namespace upon initialization."""
955 954
956 955 args = arg_s.split(' ',1)
957 956 alias_name = args[0]
958 957 try:
959 958 alias_args = args[1]
960 959 except IndexError:
961 960 alias_args = ''
962 961 if alias_name in self.alias_table:
963 962 self.call_alias(alias_name,alias_args)
964 963 else:
965 964 error("Alias `%s` not found." % alias_name)
966 965
967 def ipconfig(self,key=None,value=None):
968 """Manipulate the IPython config.
969
970 This provides a python interface to
971 If called with no arguments, it prints the internal IPython config
972
973 Optional arguments:
974
975 - key(None): if given, what key of the rc structure to return.
976
977 - value(None): if given, set the key to this value."""
978
979 if key is None:
980 page('Current configuration structure:\n'+
981 pformat(self.rc.dict()))
982 else:
983 if value is None:
984 print '%s -> %s' % (key,self.rc[key])
985 else:
986 if key not in self.rc:
987 raise KeyError(str(key))
988 self.rc[key] = value
989
990 966 def ipsystem(self,arg_s):
991 967 """Make a system call, using IPython."""
992 968
993 969 self.system(arg_s)
994 970
995 971 def complete(self,text):
996 972 """Return a sorted list of all possible completions on text.
997 973
998 974 Inputs:
999 975
1000 976 - text: a string of text to be completed on.
1001 977
1002 978 This is a wrapper around the completion mechanism, similar to what
1003 979 readline does at the command line when the TAB key is hit. By
1004 980 exposing it as a method, it can be used by other non-readline
1005 981 environments (such as GUIs) for text completion.
1006 982
1007 983 Simple usage example:
1008 984
1009 985 In [1]: x = 'hello'
1010 986
1011 987 In [2]: __IP.complete('x.l')
1012 988 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
1013 989
1014 990 complete = self.Completer.complete
1015 991 state = 0
1016 992 # use a dict so we get unique keys, since ipyhton's multiple
1017 993 # completers can return duplicates.
1018 994 comps = {}
1019 995 while True:
1020 996 newcomp = complete(text,state)
1021 997 if newcomp is None:
1022 998 break
1023 999 comps[newcomp] = 1
1024 1000 state += 1
1025 1001 outcomps = comps.keys()
1026 1002 outcomps.sort()
1027 1003 return outcomps
1028 1004
1029 1005 def set_completer_frame(self, frame=None):
1030 1006 if frame:
1031 1007 self.Completer.namespace = frame.f_locals
1032 1008 self.Completer.global_namespace = frame.f_globals
1033 1009 else:
1034 1010 self.Completer.namespace = self.user_ns
1035 1011 self.Completer.global_namespace = self.user_global_ns
1036 1012
1037 1013 def init_auto_alias(self):
1038 1014 """Define some aliases automatically.
1039 1015
1040 1016 These are ALL parameter-less aliases"""
1041 1017
1042 1018 for alias,cmd in self.auto_alias:
1043 1019 self.alias_table[alias] = (0,cmd)
1044 1020
1045 1021 def alias_table_validate(self,verbose=0):
1046 1022 """Update information about the alias table.
1047 1023
1048 1024 In particular, make sure no Python keywords/builtins are in it."""
1049 1025
1050 1026 no_alias = self.no_alias
1051 1027 for k in self.alias_table.keys():
1052 1028 if k in no_alias:
1053 1029 del self.alias_table[k]
1054 1030 if verbose:
1055 1031 print ("Deleting alias <%s>, it's a Python "
1056 1032 "keyword or builtin." % k)
1057 1033
1058 1034 def set_autoindent(self,value=None):
1059 1035 """Set the autoindent flag, checking for readline support.
1060 1036
1061 1037 If called with no arguments, it acts as a toggle."""
1062 1038
1063 1039 if not self.has_readline:
1064 1040 if os.name == 'posix':
1065 1041 warn("The auto-indent feature requires the readline library")
1066 1042 self.autoindent = 0
1067 1043 return
1068 1044 if value is None:
1069 1045 self.autoindent = not self.autoindent
1070 1046 else:
1071 1047 self.autoindent = value
1072 1048
1073 1049 def rc_set_toggle(self,rc_field,value=None):
1074 1050 """Set or toggle a field in IPython's rc config. structure.
1075 1051
1076 1052 If called with no arguments, it acts as a toggle.
1077 1053
1078 1054 If called with a non-existent field, the resulting AttributeError
1079 1055 exception will propagate out."""
1080 1056
1081 1057 rc_val = getattr(self.rc,rc_field)
1082 1058 if value is None:
1083 1059 value = not rc_val
1084 1060 setattr(self.rc,rc_field,value)
1085 1061
1086 1062 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1087 1063 """Install the user configuration directory.
1088 1064
1089 1065 Can be called when running for the first time or to upgrade the user's
1090 1066 .ipython/ directory with the mode parameter. Valid modes are 'install'
1091 1067 and 'upgrade'."""
1092 1068
1093 1069 def wait():
1094 1070 try:
1095 1071 raw_input("Please press <RETURN> to start IPython.")
1096 1072 except EOFError:
1097 1073 print >> Term.cout
1098 1074 print '*'*70
1099 1075
1100 1076 cwd = os.getcwd() # remember where we started
1101 1077 glb = glob.glob
1102 1078 print '*'*70
1103 1079 if mode == 'install':
1104 1080 print \
1105 1081 """Welcome to IPython. I will try to create a personal configuration directory
1106 1082 where you can customize many aspects of IPython's functionality in:\n"""
1107 1083 else:
1108 1084 print 'I am going to upgrade your configuration in:'
1109 1085
1110 1086 print ipythondir
1111 1087
1112 1088 rcdirend = os.path.join('IPython','UserConfig')
1113 1089 cfg = lambda d: os.path.join(d,rcdirend)
1114 1090 try:
1115 1091 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1116 1092 except IOError:
1117 1093 warning = """
1118 1094 Installation error. IPython's directory was not found.
1119 1095
1120 1096 Check the following:
1121 1097
1122 1098 The ipython/IPython directory should be in a directory belonging to your
1123 1099 PYTHONPATH environment variable (that is, it should be in a directory
1124 1100 belonging to sys.path). You can copy it explicitly there or just link to it.
1125 1101
1126 1102 IPython will proceed with builtin defaults.
1127 1103 """
1128 1104 warn(warning)
1129 1105 wait()
1130 1106 return
1131 1107
1132 1108 if mode == 'install':
1133 1109 try:
1134 1110 shutil.copytree(rcdir,ipythondir)
1135 1111 os.chdir(ipythondir)
1136 1112 rc_files = glb("ipythonrc*")
1137 1113 for rc_file in rc_files:
1138 1114 os.rename(rc_file,rc_file+rc_suffix)
1139 1115 except:
1140 1116 warning = """
1141 1117
1142 1118 There was a problem with the installation:
1143 1119 %s
1144 1120 Try to correct it or contact the developers if you think it's a bug.
1145 1121 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1146 1122 warn(warning)
1147 1123 wait()
1148 1124 return
1149 1125
1150 1126 elif mode == 'upgrade':
1151 1127 try:
1152 1128 os.chdir(ipythondir)
1153 1129 except:
1154 1130 print """
1155 1131 Can not upgrade: changing to directory %s failed. Details:
1156 1132 %s
1157 1133 """ % (ipythondir,sys.exc_info()[1])
1158 1134 wait()
1159 1135 return
1160 1136 else:
1161 1137 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1162 1138 for new_full_path in sources:
1163 1139 new_filename = os.path.basename(new_full_path)
1164 1140 if new_filename.startswith('ipythonrc'):
1165 1141 new_filename = new_filename + rc_suffix
1166 1142 # The config directory should only contain files, skip any
1167 1143 # directories which may be there (like CVS)
1168 1144 if os.path.isdir(new_full_path):
1169 1145 continue
1170 1146 if os.path.exists(new_filename):
1171 1147 old_file = new_filename+'.old'
1172 1148 if os.path.exists(old_file):
1173 1149 os.remove(old_file)
1174 1150 os.rename(new_filename,old_file)
1175 1151 shutil.copy(new_full_path,new_filename)
1176 1152 else:
1177 1153 raise ValueError,'unrecognized mode for install:',`mode`
1178 1154
1179 1155 # Fix line-endings to those native to each platform in the config
1180 1156 # directory.
1181 1157 try:
1182 1158 os.chdir(ipythondir)
1183 1159 except:
1184 1160 print """
1185 1161 Problem: changing to directory %s failed.
1186 1162 Details:
1187 1163 %s
1188 1164
1189 1165 Some configuration files may have incorrect line endings. This should not
1190 1166 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1191 1167 wait()
1192 1168 else:
1193 1169 for fname in glb('ipythonrc*'):
1194 1170 try:
1195 1171 native_line_ends(fname,backup=0)
1196 1172 except IOError:
1197 1173 pass
1198 1174
1199 1175 if mode == 'install':
1200 1176 print """
1201 1177 Successful installation!
1202 1178
1203 1179 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1204 1180 IPython manual (there are both HTML and PDF versions supplied with the
1205 1181 distribution) to make sure that your system environment is properly configured
1206 1182 to take advantage of IPython's features.
1207 1183
1208 1184 Important note: the configuration system has changed! The old system is
1209 1185 still in place, but its setting may be partly overridden by the settings in
1210 1186 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1211 1187 if some of the new settings bother you.
1212 1188
1213 1189 """
1214 1190 else:
1215 1191 print """
1216 1192 Successful upgrade!
1217 1193
1218 1194 All files in your directory:
1219 1195 %(ipythondir)s
1220 1196 which would have been overwritten by the upgrade were backed up with a .old
1221 1197 extension. If you had made particular customizations in those files you may
1222 1198 want to merge them back into the new files.""" % locals()
1223 1199 wait()
1224 1200 os.chdir(cwd)
1225 1201 # end user_setup()
1226 1202
1227 1203 def atexit_operations(self):
1228 1204 """This will be executed at the time of exit.
1229 1205
1230 1206 Saving of persistent data should be performed here. """
1231 1207
1232 1208 #print '*** IPython exit cleanup ***' # dbg
1233 1209 # input history
1234 1210 self.savehist()
1235 1211
1236 1212 # Cleanup all tempfiles left around
1237 1213 for tfile in self.tempfiles:
1238 1214 try:
1239 1215 os.unlink(tfile)
1240 1216 except OSError:
1241 1217 pass
1242 1218
1243 1219 # save the "persistent data" catch-all dictionary
1244 1220 self.hooks.shutdown_hook()
1245 1221
1246 1222 def savehist(self):
1247 1223 """Save input history to a file (via readline library)."""
1248 1224 try:
1249 1225 self.readline.write_history_file(self.histfile)
1250 1226 except:
1251 1227 print 'Unable to save IPython command history to file: ' + \
1252 1228 `self.histfile`
1253 1229
1254 1230 def history_saving_wrapper(self, func):
1255 1231 """ Wrap func for readline history saving
1256 1232
1257 1233 Convert func into callable that saves & restores
1258 1234 history around the call """
1259 1235
1260 1236 if not self.has_readline:
1261 1237 return func
1262 1238
1263 1239 def wrapper():
1264 1240 self.savehist()
1265 1241 try:
1266 1242 func()
1267 1243 finally:
1268 1244 readline.read_history_file(self.histfile)
1269 1245 return wrapper
1270 1246
1271 1247
1272 1248 def pre_readline(self):
1273 1249 """readline hook to be used at the start of each line.
1274 1250
1275 1251 Currently it handles auto-indent only."""
1276 1252
1277 1253 #debugx('self.indent_current_nsp','pre_readline:')
1278 1254 self.readline.insert_text(self.indent_current_str())
1279 1255
1280 1256 def init_readline(self):
1281 1257 """Command history completion/saving/reloading."""
1282 1258
1283 1259 import IPython.rlineimpl as readline
1284 1260 if not readline.have_readline:
1285 1261 self.has_readline = 0
1286 1262 self.readline = None
1287 1263 # no point in bugging windows users with this every time:
1288 1264 warn('Readline services not available on this platform.')
1289 1265 else:
1290 1266 sys.modules['readline'] = readline
1291 1267 import atexit
1292 1268 from IPython.completer import IPCompleter
1293 1269 self.Completer = IPCompleter(self,
1294 1270 self.user_ns,
1295 1271 self.user_global_ns,
1296 1272 self.rc.readline_omit__names,
1297 1273 self.alias_table)
1298 1274 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1299 1275 self.strdispatchers['complete_command'] = sdisp
1300 1276 self.Completer.custom_completers = sdisp
1301 1277 # Platform-specific configuration
1302 1278 if os.name == 'nt':
1303 1279 self.readline_startup_hook = readline.set_pre_input_hook
1304 1280 else:
1305 1281 self.readline_startup_hook = readline.set_startup_hook
1306 1282
1307 1283 # Load user's initrc file (readline config)
1308 1284 inputrc_name = os.environ.get('INPUTRC')
1309 1285 if inputrc_name is None:
1310 1286 home_dir = get_home_dir()
1311 1287 if home_dir is not None:
1312 1288 inputrc_name = os.path.join(home_dir,'.inputrc')
1313 1289 if os.path.isfile(inputrc_name):
1314 1290 try:
1315 1291 readline.read_init_file(inputrc_name)
1316 1292 except:
1317 1293 warn('Problems reading readline initialization file <%s>'
1318 1294 % inputrc_name)
1319 1295
1320 1296 self.has_readline = 1
1321 1297 self.readline = readline
1322 1298 # save this in sys so embedded copies can restore it properly
1323 1299 sys.ipcompleter = self.Completer.complete
1324 1300 readline.set_completer(self.Completer.complete)
1325 1301
1326 1302 # Configure readline according to user's prefs
1327 1303 for rlcommand in self.rc.readline_parse_and_bind:
1328 1304 readline.parse_and_bind(rlcommand)
1329 1305
1330 1306 # remove some chars from the delimiters list
1331 1307 delims = readline.get_completer_delims()
1332 1308 delims = delims.translate(string._idmap,
1333 1309 self.rc.readline_remove_delims)
1334 1310 readline.set_completer_delims(delims)
1335 1311 # otherwise we end up with a monster history after a while:
1336 1312 readline.set_history_length(1000)
1337 1313 try:
1338 1314 #print '*** Reading readline history' # dbg
1339 1315 readline.read_history_file(self.histfile)
1340 1316 except IOError:
1341 1317 pass # It doesn't exist yet.
1342 1318
1343 1319 atexit.register(self.atexit_operations)
1344 1320 del atexit
1345 1321
1346 1322 # Configure auto-indent for all platforms
1347 1323 self.set_autoindent(self.rc.autoindent)
1348 1324
1349 1325 def ask_yes_no(self,prompt,default=True):
1350 1326 if self.rc.quiet:
1351 1327 return True
1352 1328 return ask_yes_no(prompt,default)
1353 1329
1354 1330 def _should_recompile(self,e):
1355 1331 """Utility routine for edit_syntax_error"""
1356 1332
1357 1333 if e.filename in ('<ipython console>','<input>','<string>',
1358 1334 '<console>','<BackgroundJob compilation>',
1359 1335 None):
1360 1336
1361 1337 return False
1362 1338 try:
1363 1339 if (self.rc.autoedit_syntax and
1364 1340 not self.ask_yes_no('Return to editor to correct syntax error? '
1365 1341 '[Y/n] ','y')):
1366 1342 return False
1367 1343 except EOFError:
1368 1344 return False
1369 1345
1370 1346 def int0(x):
1371 1347 try:
1372 1348 return int(x)
1373 1349 except TypeError:
1374 1350 return 0
1375 1351 # always pass integer line and offset values to editor hook
1376 1352 self.hooks.fix_error_editor(e.filename,
1377 1353 int0(e.lineno),int0(e.offset),e.msg)
1378 1354 return True
1379 1355
1380 1356 def edit_syntax_error(self):
1381 1357 """The bottom half of the syntax error handler called in the main loop.
1382 1358
1383 1359 Loop until syntax error is fixed or user cancels.
1384 1360 """
1385 1361
1386 1362 while self.SyntaxTB.last_syntax_error:
1387 1363 # copy and clear last_syntax_error
1388 1364 err = self.SyntaxTB.clear_err_state()
1389 1365 if not self._should_recompile(err):
1390 1366 return
1391 1367 try:
1392 1368 # may set last_syntax_error again if a SyntaxError is raised
1393 1369 self.safe_execfile(err.filename,self.user_ns)
1394 1370 except:
1395 1371 self.showtraceback()
1396 1372 else:
1397 1373 try:
1398 1374 f = file(err.filename)
1399 1375 try:
1400 1376 sys.displayhook(f.read())
1401 1377 finally:
1402 1378 f.close()
1403 1379 except:
1404 1380 self.showtraceback()
1405 1381
1406 1382 def showsyntaxerror(self, filename=None):
1407 1383 """Display the syntax error that just occurred.
1408 1384
1409 1385 This doesn't display a stack trace because there isn't one.
1410 1386
1411 1387 If a filename is given, it is stuffed in the exception instead
1412 1388 of what was there before (because Python's parser always uses
1413 1389 "<string>" when reading from a string).
1414 1390 """
1415 1391 etype, value, last_traceback = sys.exc_info()
1416 1392
1417 1393 # See note about these variables in showtraceback() below
1418 1394 sys.last_type = etype
1419 1395 sys.last_value = value
1420 1396 sys.last_traceback = last_traceback
1421 1397
1422 1398 if filename and etype is SyntaxError:
1423 1399 # Work hard to stuff the correct filename in the exception
1424 1400 try:
1425 1401 msg, (dummy_filename, lineno, offset, line) = value
1426 1402 except:
1427 1403 # Not the format we expect; leave it alone
1428 1404 pass
1429 1405 else:
1430 1406 # Stuff in the right filename
1431 1407 try:
1432 1408 # Assume SyntaxError is a class exception
1433 1409 value = SyntaxError(msg, (filename, lineno, offset, line))
1434 1410 except:
1435 1411 # If that failed, assume SyntaxError is a string
1436 1412 value = msg, (filename, lineno, offset, line)
1437 1413 self.SyntaxTB(etype,value,[])
1438 1414
1439 1415 def debugger(self):
1440 1416 """Call the pydb/pdb debugger."""
1441 1417
1442 1418 if not self.rc.pdb:
1443 1419 return
1444 1420 have_pydb = False
1445 1421 if sys.version[:3] >= '2.5':
1446 1422 try:
1447 1423 from pydb import pm
1448 1424 have_pydb = True
1449 1425 except ImportError:
1450 1426 pass
1451 1427 if not have_pydb:
1452 1428 from pdb import pm
1453 1429 self.history_saving_wrapper(pm)()
1454 1430
1455 1431 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1456 1432 """Display the exception that just occurred.
1457 1433
1458 1434 If nothing is known about the exception, this is the method which
1459 1435 should be used throughout the code for presenting user tracebacks,
1460 1436 rather than directly invoking the InteractiveTB object.
1461 1437
1462 1438 A specific showsyntaxerror() also exists, but this method can take
1463 1439 care of calling it if needed, so unless you are explicitly catching a
1464 1440 SyntaxError exception, don't try to analyze the stack manually and
1465 1441 simply call this method."""
1466 1442
1467 1443 # Though this won't be called by syntax errors in the input line,
1468 1444 # there may be SyntaxError cases whith imported code.
1469 1445 if exc_tuple is None:
1470 1446 etype, value, tb = sys.exc_info()
1471 1447 else:
1472 1448 etype, value, tb = exc_tuple
1473 1449 if etype is SyntaxError:
1474 1450 self.showsyntaxerror(filename)
1475 1451 else:
1476 1452 # WARNING: these variables are somewhat deprecated and not
1477 1453 # necessarily safe to use in a threaded environment, but tools
1478 1454 # like pdb depend on their existence, so let's set them. If we
1479 1455 # find problems in the field, we'll need to revisit their use.
1480 1456 sys.last_type = etype
1481 1457 sys.last_value = value
1482 1458 sys.last_traceback = tb
1483 1459
1484 1460 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1485 1461 if self.InteractiveTB.call_pdb and self.has_readline:
1486 1462 # pdb mucks up readline, fix it back
1487 1463 self.readline.set_completer(self.Completer.complete)
1488 1464
1489 1465 def mainloop(self,banner=None):
1490 1466 """Creates the local namespace and starts the mainloop.
1491 1467
1492 1468 If an optional banner argument is given, it will override the
1493 1469 internally created default banner."""
1494 1470
1495 1471 if self.rc.c: # Emulate Python's -c option
1496 1472 self.exec_init_cmd()
1497 1473 if banner is None:
1498 1474 if not self.rc.banner:
1499 1475 banner = ''
1500 1476 # banner is string? Use it directly!
1501 1477 elif isinstance(self.rc.banner,basestring):
1502 1478 banner = self.rc.banner
1503 1479 else:
1504 1480 banner = self.BANNER+self.banner2
1505 1481
1506 1482 self.interact(banner)
1507 1483
1508 1484 def exec_init_cmd(self):
1509 1485 """Execute a command given at the command line.
1510 1486
1511 1487 This emulates Python's -c option."""
1512 1488
1513 1489 #sys.argv = ['-c']
1514 1490 self.push(self.rc.c)
1515 1491
1516 1492 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1517 1493 """Embeds IPython into a running python program.
1518 1494
1519 1495 Input:
1520 1496
1521 1497 - header: An optional header message can be specified.
1522 1498
1523 1499 - local_ns, global_ns: working namespaces. If given as None, the
1524 1500 IPython-initialized one is updated with __main__.__dict__, so that
1525 1501 program variables become visible but user-specific configuration
1526 1502 remains possible.
1527 1503
1528 1504 - stack_depth: specifies how many levels in the stack to go to
1529 1505 looking for namespaces (when local_ns and global_ns are None). This
1530 1506 allows an intermediate caller to make sure that this function gets
1531 1507 the namespace from the intended level in the stack. By default (0)
1532 1508 it will get its locals and globals from the immediate caller.
1533 1509
1534 1510 Warning: it's possible to use this in a program which is being run by
1535 1511 IPython itself (via %run), but some funny things will happen (a few
1536 1512 globals get overwritten). In the future this will be cleaned up, as
1537 1513 there is no fundamental reason why it can't work perfectly."""
1538 1514
1539 1515 # Get locals and globals from caller
1540 1516 if local_ns is None or global_ns is None:
1541 1517 call_frame = sys._getframe(stack_depth).f_back
1542 1518
1543 1519 if local_ns is None:
1544 1520 local_ns = call_frame.f_locals
1545 1521 if global_ns is None:
1546 1522 global_ns = call_frame.f_globals
1547 1523
1548 1524 # Update namespaces and fire up interpreter
1549 1525
1550 1526 # The global one is easy, we can just throw it in
1551 1527 self.user_global_ns = global_ns
1552 1528
1553 1529 # but the user/local one is tricky: ipython needs it to store internal
1554 1530 # data, but we also need the locals. We'll copy locals in the user
1555 1531 # one, but will track what got copied so we can delete them at exit.
1556 1532 # This is so that a later embedded call doesn't see locals from a
1557 1533 # previous call (which most likely existed in a separate scope).
1558 1534 local_varnames = local_ns.keys()
1559 1535 self.user_ns.update(local_ns)
1560 1536
1561 1537 # Patch for global embedding to make sure that things don't overwrite
1562 1538 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1563 1539 # FIXME. Test this a bit more carefully (the if.. is new)
1564 1540 if local_ns is None and global_ns is None:
1565 1541 self.user_global_ns.update(__main__.__dict__)
1566 1542
1567 1543 # make sure the tab-completer has the correct frame information, so it
1568 1544 # actually completes using the frame's locals/globals
1569 1545 self.set_completer_frame()
1570 1546
1571 1547 # before activating the interactive mode, we need to make sure that
1572 1548 # all names in the builtin namespace needed by ipython point to
1573 1549 # ourselves, and not to other instances.
1574 1550 self.add_builtins()
1575 1551
1576 1552 self.interact(header)
1577 1553
1578 1554 # now, purge out the user namespace from anything we might have added
1579 1555 # from the caller's local namespace
1580 1556 delvar = self.user_ns.pop
1581 1557 for var in local_varnames:
1582 1558 delvar(var,None)
1583 1559 # and clean builtins we may have overridden
1584 1560 self.clean_builtins()
1585 1561
1586 1562 def interact(self, banner=None):
1587 1563 """Closely emulate the interactive Python console.
1588 1564
1589 1565 The optional banner argument specify the banner to print
1590 1566 before the first interaction; by default it prints a banner
1591 1567 similar to the one printed by the real Python interpreter,
1592 1568 followed by the current class name in parentheses (so as not
1593 1569 to confuse this with the real interpreter -- since it's so
1594 1570 close!).
1595 1571
1596 1572 """
1597 1573
1598 1574 if self.exit_now:
1599 1575 # batch run -> do not interact
1600 1576 return
1601 1577 cprt = 'Type "copyright", "credits" or "license" for more information.'
1602 1578 if banner is None:
1603 1579 self.write("Python %s on %s\n%s\n(%s)\n" %
1604 1580 (sys.version, sys.platform, cprt,
1605 1581 self.__class__.__name__))
1606 1582 else:
1607 1583 self.write(banner)
1608 1584
1609 1585 more = 0
1610 1586
1611 1587 # Mark activity in the builtins
1612 1588 __builtin__.__dict__['__IPYTHON__active'] += 1
1613 1589
1614 1590 # exit_now is set by a call to %Exit or %Quit
1615 1591 while not self.exit_now:
1616 1592 if more:
1617 1593 prompt = self.hooks.generate_prompt(True)
1618 1594 if self.autoindent:
1619 1595 self.readline_startup_hook(self.pre_readline)
1620 1596 else:
1621 1597 prompt = self.hooks.generate_prompt(False)
1622 1598 try:
1623 1599 line = self.raw_input(prompt,more)
1624 1600 if self.exit_now:
1625 1601 # quick exit on sys.std[in|out] close
1626 1602 break
1627 1603 if self.autoindent:
1628 1604 self.readline_startup_hook(None)
1629 1605 except KeyboardInterrupt:
1630 1606 self.write('\nKeyboardInterrupt\n')
1631 1607 self.resetbuffer()
1632 1608 # keep cache in sync with the prompt counter:
1633 1609 self.outputcache.prompt_count -= 1
1634 1610
1635 1611 if self.autoindent:
1636 1612 self.indent_current_nsp = 0
1637 1613 more = 0
1638 1614 except EOFError:
1639 1615 if self.autoindent:
1640 1616 self.readline_startup_hook(None)
1641 1617 self.write('\n')
1642 1618 self.exit()
1643 1619 except bdb.BdbQuit:
1644 1620 warn('The Python debugger has exited with a BdbQuit exception.\n'
1645 1621 'Because of how pdb handles the stack, it is impossible\n'
1646 1622 'for IPython to properly format this particular exception.\n'
1647 1623 'IPython will resume normal operation.')
1648 1624 except:
1649 1625 # exceptions here are VERY RARE, but they can be triggered
1650 1626 # asynchronously by signal handlers, for example.
1651 1627 self.showtraceback()
1652 1628 else:
1653 1629 more = self.push(line)
1654 1630 if (self.SyntaxTB.last_syntax_error and
1655 1631 self.rc.autoedit_syntax):
1656 1632 self.edit_syntax_error()
1657 1633
1658 1634 # We are off again...
1659 1635 __builtin__.__dict__['__IPYTHON__active'] -= 1
1660 1636
1661 1637 def excepthook(self, etype, value, tb):
1662 1638 """One more defense for GUI apps that call sys.excepthook.
1663 1639
1664 1640 GUI frameworks like wxPython trap exceptions and call
1665 1641 sys.excepthook themselves. I guess this is a feature that
1666 1642 enables them to keep running after exceptions that would
1667 1643 otherwise kill their mainloop. This is a bother for IPython
1668 1644 which excepts to catch all of the program exceptions with a try:
1669 1645 except: statement.
1670 1646
1671 1647 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1672 1648 any app directly invokes sys.excepthook, it will look to the user like
1673 1649 IPython crashed. In order to work around this, we can disable the
1674 1650 CrashHandler and replace it with this excepthook instead, which prints a
1675 1651 regular traceback using our InteractiveTB. In this fashion, apps which
1676 1652 call sys.excepthook will generate a regular-looking exception from
1677 1653 IPython, and the CrashHandler will only be triggered by real IPython
1678 1654 crashes.
1679 1655
1680 1656 This hook should be used sparingly, only in places which are not likely
1681 1657 to be true IPython errors.
1682 1658 """
1683 1659 self.showtraceback((etype,value,tb),tb_offset=0)
1684 1660
1685 1661 def expand_aliases(self,fn,rest):
1686 1662 """ Expand multiple levels of aliases:
1687 1663
1688 1664 if:
1689 1665
1690 1666 alias foo bar /tmp
1691 1667 alias baz foo
1692 1668
1693 1669 then:
1694 1670
1695 1671 baz huhhahhei -> bar /tmp huhhahhei
1696 1672
1697 1673 """
1698 1674 line = fn + " " + rest
1699 1675
1700 1676 done = Set()
1701 1677 while 1:
1702 1678 pre,fn,rest = self.split_user_input(line)
1703 1679 if fn in self.alias_table:
1704 1680 if fn in done:
1705 1681 warn("Cyclic alias definition, repeated '%s'" % fn)
1706 1682 return ""
1707 1683 done.add(fn)
1708 1684
1709 1685 l2 = self.transform_alias(fn,rest)
1710 1686 # dir -> dir
1711 1687 # print "alias",line, "->",l2 #dbg
1712 1688 if l2 == line:
1713 1689 break
1714 1690 # ls -> ls -F should not recurse forever
1715 1691 if l2.split(None,1)[0] == line.split(None,1)[0]:
1716 1692 line = l2
1717 1693 break
1718 1694
1719 1695 line=l2
1720 1696
1721 1697
1722 1698 # print "al expand to",line #dbg
1723 1699 else:
1724 1700 break
1725 1701
1726 1702 return line
1727 1703
1728 1704 def transform_alias(self, alias,rest=''):
1729 1705 """ Transform alias to system command string.
1730 1706 """
1731 1707 nargs,cmd = self.alias_table[alias]
1732 1708 if ' ' in cmd and os.path.isfile(cmd):
1733 1709 cmd = '"%s"' % cmd
1734 1710
1735 1711 # Expand the %l special to be the user's input line
1736 1712 if cmd.find('%l') >= 0:
1737 1713 cmd = cmd.replace('%l',rest)
1738 1714 rest = ''
1739 1715 if nargs==0:
1740 1716 # Simple, argument-less aliases
1741 1717 cmd = '%s %s' % (cmd,rest)
1742 1718 else:
1743 1719 # Handle aliases with positional arguments
1744 1720 args = rest.split(None,nargs)
1745 1721 if len(args)< nargs:
1746 1722 error('Alias <%s> requires %s arguments, %s given.' %
1747 1723 (alias,nargs,len(args)))
1748 1724 return None
1749 1725 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1750 1726 # Now call the macro, evaluating in the user's namespace
1751 1727 #print 'new command: <%r>' % cmd # dbg
1752 1728 return cmd
1753 1729
1754 1730 def call_alias(self,alias,rest=''):
1755 1731 """Call an alias given its name and the rest of the line.
1756 1732
1757 1733 This is only used to provide backwards compatibility for users of
1758 1734 ipalias(), use of which is not recommended for anymore."""
1759 1735
1760 1736 # Now call the macro, evaluating in the user's namespace
1761 1737 cmd = self.transform_alias(alias, rest)
1762 1738 try:
1763 1739 self.system(cmd)
1764 1740 except:
1765 1741 self.showtraceback()
1766 1742
1767 1743 def indent_current_str(self):
1768 1744 """return the current level of indentation as a string"""
1769 1745 return self.indent_current_nsp * ' '
1770 1746
1771 1747 def autoindent_update(self,line):
1772 1748 """Keep track of the indent level."""
1773 1749
1774 1750 #debugx('line')
1775 1751 #debugx('self.indent_current_nsp')
1776 1752 if self.autoindent:
1777 1753 if line:
1778 1754 inisp = num_ini_spaces(line)
1779 1755 if inisp < self.indent_current_nsp:
1780 1756 self.indent_current_nsp = inisp
1781 1757
1782 1758 if line[-1] == ':':
1783 1759 self.indent_current_nsp += 4
1784 1760 elif dedent_re.match(line):
1785 1761 self.indent_current_nsp -= 4
1786 1762 else:
1787 1763 self.indent_current_nsp = 0
1788 1764
1789 1765 def runlines(self,lines):
1790 1766 """Run a string of one or more lines of source.
1791 1767
1792 1768 This method is capable of running a string containing multiple source
1793 1769 lines, as if they had been entered at the IPython prompt. Since it
1794 1770 exposes IPython's processing machinery, the given strings can contain
1795 1771 magic calls (%magic), special shell access (!cmd), etc."""
1796 1772
1797 1773 # We must start with a clean buffer, in case this is run from an
1798 1774 # interactive IPython session (via a magic, for example).
1799 1775 self.resetbuffer()
1800 1776 lines = lines.split('\n')
1801 1777 more = 0
1802 1778 for line in lines:
1803 1779 # skip blank lines so we don't mess up the prompt counter, but do
1804 1780 # NOT skip even a blank line if we are in a code block (more is
1805 1781 # true)
1806 1782 if line or more:
1807 1783 more = self.push(self.prefilter(line,more))
1808 1784 # IPython's runsource returns None if there was an error
1809 1785 # compiling the code. This allows us to stop processing right
1810 1786 # away, so the user gets the error message at the right place.
1811 1787 if more is None:
1812 1788 break
1813 1789 # final newline in case the input didn't have it, so that the code
1814 1790 # actually does get executed
1815 1791 if more:
1816 1792 self.push('\n')
1817 1793
1818 1794 def runsource(self, source, filename='<input>', symbol='single'):
1819 1795 """Compile and run some source in the interpreter.
1820 1796
1821 1797 Arguments are as for compile_command().
1822 1798
1823 1799 One several things can happen:
1824 1800
1825 1801 1) The input is incorrect; compile_command() raised an
1826 1802 exception (SyntaxError or OverflowError). A syntax traceback
1827 1803 will be printed by calling the showsyntaxerror() method.
1828 1804
1829 1805 2) The input is incomplete, and more input is required;
1830 1806 compile_command() returned None. Nothing happens.
1831 1807
1832 1808 3) The input is complete; compile_command() returned a code
1833 1809 object. The code is executed by calling self.runcode() (which
1834 1810 also handles run-time exceptions, except for SystemExit).
1835 1811
1836 1812 The return value is:
1837 1813
1838 1814 - True in case 2
1839 1815
1840 1816 - False in the other cases, unless an exception is raised, where
1841 1817 None is returned instead. This can be used by external callers to
1842 1818 know whether to continue feeding input or not.
1843 1819
1844 1820 The return value can be used to decide whether to use sys.ps1 or
1845 1821 sys.ps2 to prompt the next line."""
1846 1822
1847 1823 # if the source code has leading blanks, add 'if 1:\n' to it
1848 1824 # this allows execution of indented pasted code. It is tempting
1849 1825 # to add '\n' at the end of source to run commands like ' a=1'
1850 1826 # directly, but this fails for more complicated scenarios
1851 1827 if source[:1] in [' ', '\t']:
1852 1828 source = 'if 1:\n%s' % source
1853 1829
1854 1830 try:
1855 1831 code = self.compile(source,filename,symbol)
1856 1832 except (OverflowError, SyntaxError, ValueError):
1857 1833 # Case 1
1858 1834 self.showsyntaxerror(filename)
1859 1835 return None
1860 1836
1861 1837 if code is None:
1862 1838 # Case 2
1863 1839 return True
1864 1840
1865 1841 # Case 3
1866 1842 # We store the code object so that threaded shells and
1867 1843 # custom exception handlers can access all this info if needed.
1868 1844 # The source corresponding to this can be obtained from the
1869 1845 # buffer attribute as '\n'.join(self.buffer).
1870 1846 self.code_to_run = code
1871 1847 # now actually execute the code object
1872 1848 if self.runcode(code) == 0:
1873 1849 return False
1874 1850 else:
1875 1851 return None
1876 1852
1877 1853 def runcode(self,code_obj):
1878 1854 """Execute a code object.
1879 1855
1880 1856 When an exception occurs, self.showtraceback() is called to display a
1881 1857 traceback.
1882 1858
1883 1859 Return value: a flag indicating whether the code to be run completed
1884 1860 successfully:
1885 1861
1886 1862 - 0: successful execution.
1887 1863 - 1: an error occurred.
1888 1864 """
1889 1865
1890 1866 # Set our own excepthook in case the user code tries to call it
1891 1867 # directly, so that the IPython crash handler doesn't get triggered
1892 1868 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1893 1869
1894 1870 # we save the original sys.excepthook in the instance, in case config
1895 1871 # code (such as magics) needs access to it.
1896 1872 self.sys_excepthook = old_excepthook
1897 1873 outflag = 1 # happens in more places, so it's easier as default
1898 1874 try:
1899 1875 try:
1900 1876 # Embedded instances require separate global/local namespaces
1901 1877 # so they can see both the surrounding (local) namespace and
1902 1878 # the module-level globals when called inside another function.
1903 1879 if self.embedded:
1904 1880 exec code_obj in self.user_global_ns, self.user_ns
1905 1881 # Normal (non-embedded) instances should only have a single
1906 1882 # namespace for user code execution, otherwise functions won't
1907 1883 # see interactive top-level globals.
1908 1884 else:
1909 1885 exec code_obj in self.user_ns
1910 1886 finally:
1911 1887 # Reset our crash handler in place
1912 1888 sys.excepthook = old_excepthook
1913 1889 except SystemExit:
1914 1890 self.resetbuffer()
1915 1891 self.showtraceback()
1916 1892 warn("Type %exit or %quit to exit IPython "
1917 1893 "(%Exit or %Quit do so unconditionally).",level=1)
1918 1894 except self.custom_exceptions:
1919 1895 etype,value,tb = sys.exc_info()
1920 1896 self.CustomTB(etype,value,tb)
1921 1897 except:
1922 1898 self.showtraceback()
1923 1899 else:
1924 1900 outflag = 0
1925 1901 if softspace(sys.stdout, 0):
1926 1902 print
1927 1903 # Flush out code object which has been run (and source)
1928 1904 self.code_to_run = None
1929 1905 return outflag
1930 1906
1931 1907 def push(self, line):
1932 1908 """Push a line to the interpreter.
1933 1909
1934 1910 The line should not have a trailing newline; it may have
1935 1911 internal newlines. The line is appended to a buffer and the
1936 1912 interpreter's runsource() method is called with the
1937 1913 concatenated contents of the buffer as source. If this
1938 1914 indicates that the command was executed or invalid, the buffer
1939 1915 is reset; otherwise, the command is incomplete, and the buffer
1940 1916 is left as it was after the line was appended. The return
1941 1917 value is 1 if more input is required, 0 if the line was dealt
1942 1918 with in some way (this is the same as runsource()).
1943 1919 """
1944 1920
1945 1921 # autoindent management should be done here, and not in the
1946 1922 # interactive loop, since that one is only seen by keyboard input. We
1947 1923 # need this done correctly even for code run via runlines (which uses
1948 1924 # push).
1949 1925
1950 1926 #print 'push line: <%s>' % line # dbg
1951 1927 for subline in line.splitlines():
1952 1928 self.autoindent_update(subline)
1953 1929 self.buffer.append(line)
1954 1930 more = self.runsource('\n'.join(self.buffer), self.filename)
1955 1931 if not more:
1956 1932 self.resetbuffer()
1957 1933 return more
1958 1934
1959 1935 def resetbuffer(self):
1960 1936 """Reset the input buffer."""
1961 1937 self.buffer[:] = []
1962 1938
1963 1939 def raw_input(self,prompt='',continue_prompt=False):
1964 1940 """Write a prompt and read a line.
1965 1941
1966 1942 The returned line does not include the trailing newline.
1967 1943 When the user enters the EOF key sequence, EOFError is raised.
1968 1944
1969 1945 Optional inputs:
1970 1946
1971 1947 - prompt(''): a string to be printed to prompt the user.
1972 1948
1973 1949 - continue_prompt(False): whether this line is the first one or a
1974 1950 continuation in a sequence of inputs.
1975 1951 """
1976 1952
1977 1953 try:
1978 1954 line = raw_input_original(prompt)
1979 1955 except ValueError:
1980 1956 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1981 1957 self.exit_now = True
1982 1958 return ""
1983 1959
1984 1960
1985 1961 # Try to be reasonably smart about not re-indenting pasted input more
1986 1962 # than necessary. We do this by trimming out the auto-indent initial
1987 1963 # spaces, if the user's actual input started itself with whitespace.
1988 1964 #debugx('self.buffer[-1]')
1989 1965
1990 1966 if self.autoindent:
1991 1967 if num_ini_spaces(line) > self.indent_current_nsp:
1992 1968 line = line[self.indent_current_nsp:]
1993 1969 self.indent_current_nsp = 0
1994 1970
1995 1971 # store the unfiltered input before the user has any chance to modify
1996 1972 # it.
1997 1973 if line.strip():
1998 1974 if continue_prompt:
1999 1975 self.input_hist_raw[-1] += '%s\n' % line
2000 1976 if self.has_readline: # and some config option is set?
2001 1977 try:
2002 1978 histlen = self.readline.get_current_history_length()
2003 1979 newhist = self.input_hist_raw[-1].rstrip()
2004 1980 self.readline.remove_history_item(histlen-1)
2005 1981 self.readline.replace_history_item(histlen-2,newhist)
2006 1982 except AttributeError:
2007 1983 pass # re{move,place}_history_item are new in 2.4.
2008 1984 else:
2009 1985 self.input_hist_raw.append('%s\n' % line)
2010 1986
2011 1987 try:
2012 1988 lineout = self.prefilter(line,continue_prompt)
2013 1989 except:
2014 1990 # blanket except, in case a user-defined prefilter crashes, so it
2015 1991 # can't take all of ipython with it.
2016 1992 self.showtraceback()
2017 1993 return ''
2018 1994 else:
2019 1995 return lineout
2020 1996
2021 1997 def split_user_input(self,line):
2022 1998 """Split user input into pre-char, function part and rest."""
2023 1999
2024 2000 lsplit = self.line_split.match(line)
2025 2001 if lsplit is None: # no regexp match returns None
2026 2002 try:
2027 2003 iFun,theRest = line.split(None,1)
2028 2004 except ValueError:
2029 2005 iFun,theRest = line,''
2030 2006 pre = re.match('^(\s*)(.*)',line).groups()[0]
2031 2007 else:
2032 2008 pre,iFun,theRest = lsplit.groups()
2033 2009
2034 2010 #print 'line:<%s>' % line # dbg
2035 2011 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2036 2012 return pre,iFun.strip(),theRest
2037 2013
2038 2014 def _prefilter(self, line, continue_prompt):
2039 2015 """Calls different preprocessors, depending on the form of line."""
2040 2016
2041 2017 # All handlers *must* return a value, even if it's blank ('').
2042 2018
2043 2019 # Lines are NOT logged here. Handlers should process the line as
2044 2020 # needed, update the cache AND log it (so that the input cache array
2045 2021 # stays synced).
2046 2022
2047 2023 # This function is _very_ delicate, and since it's also the one which
2048 2024 # determines IPython's response to user input, it must be as efficient
2049 2025 # as possible. For this reason it has _many_ returns in it, trying
2050 2026 # always to exit as quickly as it can figure out what it needs to do.
2051 2027
2052 2028 # This function is the main responsible for maintaining IPython's
2053 2029 # behavior respectful of Python's semantics. So be _very_ careful if
2054 2030 # making changes to anything here.
2055 2031
2056 2032 #.....................................................................
2057 2033 # Code begins
2058 2034
2059 2035 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2060 2036
2061 2037 # save the line away in case we crash, so the post-mortem handler can
2062 2038 # record it
2063 2039 self._last_input_line = line
2064 2040
2065 2041 #print '***line: <%s>' % line # dbg
2066 2042
2067 2043 # the input history needs to track even empty lines
2068 2044 stripped = line.strip()
2069 2045
2070 2046 if not stripped:
2071 2047 if not continue_prompt:
2072 2048 self.outputcache.prompt_count -= 1
2073 2049 return self.handle_normal(line,continue_prompt)
2074 2050 #return self.handle_normal('',continue_prompt)
2075 2051
2076 2052 # print '***cont',continue_prompt # dbg
2077 2053 # special handlers are only allowed for single line statements
2078 2054 if continue_prompt and not self.rc.multi_line_specials:
2079 2055 return self.handle_normal(line,continue_prompt)
2080 2056
2081 2057
2082 2058 # For the rest, we need the structure of the input
2083 2059 pre,iFun,theRest = self.split_user_input(line)
2084 2060
2085 2061 # See whether any pre-existing handler can take care of it
2086 2062
2087 2063 rewritten = self.hooks.input_prefilter(stripped)
2088 2064 if rewritten != stripped: # ok, some prefilter did something
2089 2065 rewritten = pre + rewritten # add indentation
2090 2066 return self.handle_normal(rewritten)
2091 2067
2092 2068 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2093 2069
2094 2070 # First check for explicit escapes in the last/first character
2095 2071 handler = None
2096 2072 if line[-1] == self.ESC_HELP:
2097 2073 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2098 2074 if handler is None:
2099 2075 # look at the first character of iFun, NOT of line, so we skip
2100 2076 # leading whitespace in multiline input
2101 2077 handler = self.esc_handlers.get(iFun[0:1])
2102 2078 if handler is not None:
2103 2079 return handler(line,continue_prompt,pre,iFun,theRest)
2104 2080 # Emacs ipython-mode tags certain input lines
2105 2081 if line.endswith('# PYTHON-MODE'):
2106 2082 return self.handle_emacs(line,continue_prompt)
2107 2083
2108 2084 # Next, check if we can automatically execute this thing
2109 2085
2110 2086 # Allow ! in multi-line statements if multi_line_specials is on:
2111 2087 if continue_prompt and self.rc.multi_line_specials and \
2112 2088 iFun.startswith(self.ESC_SHELL):
2113 2089 return self.handle_shell_escape(line,continue_prompt,
2114 2090 pre=pre,iFun=iFun,
2115 2091 theRest=theRest)
2116 2092
2117 2093 # Let's try to find if the input line is a magic fn
2118 2094 oinfo = None
2119 2095 if hasattr(self,'magic_'+iFun):
2120 2096 # WARNING: _ofind uses getattr(), so it can consume generators and
2121 2097 # cause other side effects.
2122 2098 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2123 2099 if oinfo['ismagic']:
2124 2100 # Be careful not to call magics when a variable assignment is
2125 2101 # being made (ls='hi', for example)
2126 2102 if self.rc.automagic and \
2127 2103 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2128 2104 (self.rc.multi_line_specials or not continue_prompt):
2129 2105 return self.handle_magic(line,continue_prompt,
2130 2106 pre,iFun,theRest)
2131 2107 else:
2132 2108 return self.handle_normal(line,continue_prompt)
2133 2109
2134 2110 # If the rest of the line begins with an (in)equality, assginment or
2135 2111 # function call, we should not call _ofind but simply execute it.
2136 2112 # This avoids spurious geattr() accesses on objects upon assignment.
2137 2113 #
2138 2114 # It also allows users to assign to either alias or magic names true
2139 2115 # python variables (the magic/alias systems always take second seat to
2140 2116 # true python code).
2141 2117 if theRest and theRest[0] in '!=()':
2142 2118 return self.handle_normal(line,continue_prompt)
2143 2119
2144 2120 if oinfo is None:
2145 2121 # let's try to ensure that _oinfo is ONLY called when autocall is
2146 2122 # on. Since it has inevitable potential side effects, at least
2147 2123 # having autocall off should be a guarantee to the user that no
2148 2124 # weird things will happen.
2149 2125
2150 2126 if self.rc.autocall:
2151 2127 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2152 2128 else:
2153 2129 # in this case, all that's left is either an alias or
2154 2130 # processing the line normally.
2155 2131 if iFun in self.alias_table:
2156 2132 # if autocall is off, by not running _ofind we won't know
2157 2133 # whether the given name may also exist in one of the
2158 2134 # user's namespace. At this point, it's best to do a
2159 2135 # quick check just to be sure that we don't let aliases
2160 2136 # shadow variables.
2161 2137 head = iFun.split('.',1)[0]
2162 2138 if head in self.user_ns or head in self.internal_ns \
2163 2139 or head in __builtin__.__dict__:
2164 2140 return self.handle_normal(line,continue_prompt)
2165 2141 else:
2166 2142 return self.handle_alias(line,continue_prompt,
2167 2143 pre,iFun,theRest)
2168 2144
2169 2145 else:
2170 2146 return self.handle_normal(line,continue_prompt)
2171 2147
2172 2148 if not oinfo['found']:
2173 2149 return self.handle_normal(line,continue_prompt)
2174 2150 else:
2175 2151 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2176 2152 if oinfo['isalias']:
2177 2153 return self.handle_alias(line,continue_prompt,
2178 2154 pre,iFun,theRest)
2179 2155
2180 2156 if (self.rc.autocall
2181 2157 and
2182 2158 (
2183 2159 #only consider exclusion re if not "," or ";" autoquoting
2184 2160 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2185 2161 or pre == self.ESC_PAREN) or
2186 2162 (not self.re_exclude_auto.match(theRest)))
2187 2163 and
2188 2164 self.re_fun_name.match(iFun) and
2189 2165 callable(oinfo['obj'])) :
2190 2166 #print 'going auto' # dbg
2191 2167 return self.handle_auto(line,continue_prompt,
2192 2168 pre,iFun,theRest,oinfo['obj'])
2193 2169 else:
2194 2170 #print 'was callable?', callable(oinfo['obj']) # dbg
2195 2171 return self.handle_normal(line,continue_prompt)
2196 2172
2197 2173 # If we get here, we have a normal Python line. Log and return.
2198 2174 return self.handle_normal(line,continue_prompt)
2199 2175
2200 2176 def _prefilter_dumb(self, line, continue_prompt):
2201 2177 """simple prefilter function, for debugging"""
2202 2178 return self.handle_normal(line,continue_prompt)
2203 2179
2204 2180
2205 2181 def multiline_prefilter(self, line, continue_prompt):
2206 2182 """ Run _prefilter for each line of input
2207 2183
2208 2184 Covers cases where there are multiple lines in the user entry,
2209 2185 which is the case when the user goes back to a multiline history
2210 2186 entry and presses enter.
2211 2187
2212 2188 """
2213 2189 out = []
2214 2190 for l in line.rstrip('\n').split('\n'):
2215 2191 out.append(self._prefilter(l, continue_prompt))
2216 2192 return '\n'.join(out)
2217 2193
2218 2194 # Set the default prefilter() function (this can be user-overridden)
2219 2195 prefilter = multiline_prefilter
2220 2196
2221 2197 def handle_normal(self,line,continue_prompt=None,
2222 2198 pre=None,iFun=None,theRest=None):
2223 2199 """Handle normal input lines. Use as a template for handlers."""
2224 2200
2225 2201 # With autoindent on, we need some way to exit the input loop, and I
2226 2202 # don't want to force the user to have to backspace all the way to
2227 2203 # clear the line. The rule will be in this case, that either two
2228 2204 # lines of pure whitespace in a row, or a line of pure whitespace but
2229 2205 # of a size different to the indent level, will exit the input loop.
2230 2206
2231 2207 if (continue_prompt and self.autoindent and line.isspace() and
2232 2208 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2233 2209 (self.buffer[-1]).isspace() )):
2234 2210 line = ''
2235 2211
2236 2212 self.log(line,line,continue_prompt)
2237 2213 return line
2238 2214
2239 2215 def handle_alias(self,line,continue_prompt=None,
2240 2216 pre=None,iFun=None,theRest=None):
2241 2217 """Handle alias input lines. """
2242 2218
2243 2219 # pre is needed, because it carries the leading whitespace. Otherwise
2244 2220 # aliases won't work in indented sections.
2245 2221 transformed = self.expand_aliases(iFun, theRest)
2246 2222 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2247 2223 self.log(line,line_out,continue_prompt)
2248 2224 #print 'line out:',line_out # dbg
2249 2225 return line_out
2250 2226
2251 2227 def handle_shell_escape(self, line, continue_prompt=None,
2252 2228 pre=None,iFun=None,theRest=None):
2253 2229 """Execute the line in a shell, empty return value"""
2254 2230
2255 2231 #print 'line in :', `line` # dbg
2256 2232 # Example of a special handler. Others follow a similar pattern.
2257 2233 if line.lstrip().startswith('!!'):
2258 2234 # rewrite iFun/theRest to properly hold the call to %sx and
2259 2235 # the actual command to be executed, so handle_magic can work
2260 2236 # correctly
2261 2237 theRest = '%s %s' % (iFun[2:],theRest)
2262 2238 iFun = 'sx'
2263 2239 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2264 2240 line.lstrip()[2:]),
2265 2241 continue_prompt,pre,iFun,theRest)
2266 2242 else:
2267 2243 cmd=line.lstrip().lstrip('!')
2268 2244 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2269 2245 # update cache/log and return
2270 2246 self.log(line,line_out,continue_prompt)
2271 2247 return line_out
2272 2248
2273 2249 def handle_magic(self, line, continue_prompt=None,
2274 2250 pre=None,iFun=None,theRest=None):
2275 2251 """Execute magic functions."""
2276 2252
2277 2253
2278 2254 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2279 2255 self.log(line,cmd,continue_prompt)
2280 2256 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2281 2257 return cmd
2282 2258
2283 2259 def handle_auto(self, line, continue_prompt=None,
2284 2260 pre=None,iFun=None,theRest=None,obj=None):
2285 2261 """Hande lines which can be auto-executed, quoting if requested."""
2286 2262
2287 2263 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2288 2264
2289 2265 # This should only be active for single-line input!
2290 2266 if continue_prompt:
2291 2267 self.log(line,line,continue_prompt)
2292 2268 return line
2293 2269
2294 2270 auto_rewrite = True
2295 2271
2296 2272 if pre == self.ESC_QUOTE:
2297 2273 # Auto-quote splitting on whitespace
2298 2274 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2299 2275 elif pre == self.ESC_QUOTE2:
2300 2276 # Auto-quote whole string
2301 2277 newcmd = '%s("%s")' % (iFun,theRest)
2302 2278 elif pre == self.ESC_PAREN:
2303 2279 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2304 2280 else:
2305 2281 # Auto-paren.
2306 2282 # We only apply it to argument-less calls if the autocall
2307 2283 # parameter is set to 2. We only need to check that autocall is <
2308 2284 # 2, since this function isn't called unless it's at least 1.
2309 2285 if not theRest and (self.rc.autocall < 2):
2310 2286 newcmd = '%s %s' % (iFun,theRest)
2311 2287 auto_rewrite = False
2312 2288 else:
2313 2289 if theRest.startswith('['):
2314 2290 if hasattr(obj,'__getitem__'):
2315 2291 # Don't autocall in this case: item access for an object
2316 2292 # which is BOTH callable and implements __getitem__.
2317 2293 newcmd = '%s %s' % (iFun,theRest)
2318 2294 auto_rewrite = False
2319 2295 else:
2320 2296 # if the object doesn't support [] access, go ahead and
2321 2297 # autocall
2322 2298 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2323 2299 elif theRest.endswith(';'):
2324 2300 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2325 2301 else:
2326 2302 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2327 2303
2328 2304 if auto_rewrite:
2329 2305 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2330 2306 # log what is now valid Python, not the actual user input (without the
2331 2307 # final newline)
2332 2308 self.log(line,newcmd,continue_prompt)
2333 2309 return newcmd
2334 2310
2335 2311 def handle_help(self, line, continue_prompt=None,
2336 2312 pre=None,iFun=None,theRest=None):
2337 2313 """Try to get some help for the object.
2338 2314
2339 2315 obj? or ?obj -> basic information.
2340 2316 obj?? or ??obj -> more details.
2341 2317 """
2342 2318
2343 2319 # We need to make sure that we don't process lines which would be
2344 2320 # otherwise valid python, such as "x=1 # what?"
2345 2321 try:
2346 2322 codeop.compile_command(line)
2347 2323 except SyntaxError:
2348 2324 # We should only handle as help stuff which is NOT valid syntax
2349 2325 if line[0]==self.ESC_HELP:
2350 2326 line = line[1:]
2351 2327 elif line[-1]==self.ESC_HELP:
2352 2328 line = line[:-1]
2353 2329 self.log(line,'#?'+line,continue_prompt)
2354 2330 if line:
2355 2331 self.magic_pinfo(line)
2356 2332 else:
2357 2333 page(self.usage,screen_lines=self.rc.screen_length)
2358 2334 return '' # Empty string is needed here!
2359 2335 except:
2360 2336 # Pass any other exceptions through to the normal handler
2361 2337 return self.handle_normal(line,continue_prompt)
2362 2338 else:
2363 2339 # If the code compiles ok, we should handle it normally
2364 2340 return self.handle_normal(line,continue_prompt)
2365 2341
2366 2342 def getapi(self):
2367 2343 """ Get an IPApi object for this shell instance
2368 2344
2369 2345 Getting an IPApi object is always preferable to accessing the shell
2370 2346 directly, but this holds true especially for extensions.
2371 2347
2372 2348 It should always be possible to implement an extension with IPApi
2373 2349 alone. If not, contact maintainer to request an addition.
2374 2350
2375 2351 """
2376 2352 return self.api
2377 2353
2378 2354 def handle_emacs(self,line,continue_prompt=None,
2379 2355 pre=None,iFun=None,theRest=None):
2380 2356 """Handle input lines marked by python-mode."""
2381 2357
2382 2358 # Currently, nothing is done. Later more functionality can be added
2383 2359 # here if needed.
2384 2360
2385 2361 # The input cache shouldn't be updated
2386 2362
2387 2363 return line
2388 2364
2389 2365 def mktempfile(self,data=None):
2390 2366 """Make a new tempfile and return its filename.
2391 2367
2392 2368 This makes a call to tempfile.mktemp, but it registers the created
2393 2369 filename internally so ipython cleans it up at exit time.
2394 2370
2395 2371 Optional inputs:
2396 2372
2397 2373 - data(None): if data is given, it gets written out to the temp file
2398 2374 immediately, and the file is closed again."""
2399 2375
2400 2376 filename = tempfile.mktemp('.py','ipython_edit_')
2401 2377 self.tempfiles.append(filename)
2402 2378
2403 2379 if data:
2404 2380 tmp_file = open(filename,'w')
2405 2381 tmp_file.write(data)
2406 2382 tmp_file.close()
2407 2383 return filename
2408 2384
2409 2385 def write(self,data):
2410 2386 """Write a string to the default output"""
2411 2387 Term.cout.write(data)
2412 2388
2413 2389 def write_err(self,data):
2414 2390 """Write a string to the default error output"""
2415 2391 Term.cerr.write(data)
2416 2392
2417 2393 def exit(self):
2418 2394 """Handle interactive exit.
2419 2395
2420 2396 This method sets the exit_now attribute."""
2421 2397
2422 2398 if self.rc.confirm_exit:
2423 2399 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2424 2400 self.exit_now = True
2425 2401 else:
2426 2402 self.exit_now = True
2427 2403
2428 2404 def safe_execfile(self,fname,*where,**kw):
2429 2405 """A safe version of the builtin execfile().
2430 2406
2431 2407 This version will never throw an exception, and knows how to handle
2432 2408 ipython logs as well."""
2433 2409
2434 2410 def syspath_cleanup():
2435 2411 """Internal cleanup routine for sys.path."""
2436 2412 if add_dname:
2437 2413 try:
2438 2414 sys.path.remove(dname)
2439 2415 except ValueError:
2440 2416 # For some reason the user has already removed it, ignore.
2441 2417 pass
2442 2418
2443 2419 fname = os.path.expanduser(fname)
2444 2420
2445 2421 # Find things also in current directory. This is needed to mimic the
2446 2422 # behavior of running a script from the system command line, where
2447 2423 # Python inserts the script's directory into sys.path
2448 2424 dname = os.path.dirname(os.path.abspath(fname))
2449 2425 add_dname = False
2450 2426 if dname not in sys.path:
2451 2427 sys.path.insert(0,dname)
2452 2428 add_dname = True
2453 2429
2454 2430 try:
2455 2431 xfile = open(fname)
2456 2432 except:
2457 2433 print >> Term.cerr, \
2458 2434 'Could not open file <%s> for safe execution.' % fname
2459 2435 syspath_cleanup()
2460 2436 return None
2461 2437
2462 2438 kw.setdefault('islog',0)
2463 2439 kw.setdefault('quiet',1)
2464 2440 kw.setdefault('exit_ignore',0)
2465 2441 first = xfile.readline()
2466 2442 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2467 2443 xfile.close()
2468 2444 # line by line execution
2469 2445 if first.startswith(loghead) or kw['islog']:
2470 2446 print 'Loading log file <%s> one line at a time...' % fname
2471 2447 if kw['quiet']:
2472 2448 stdout_save = sys.stdout
2473 2449 sys.stdout = StringIO.StringIO()
2474 2450 try:
2475 2451 globs,locs = where[0:2]
2476 2452 except:
2477 2453 try:
2478 2454 globs = locs = where[0]
2479 2455 except:
2480 2456 globs = locs = globals()
2481 2457 badblocks = []
2482 2458
2483 2459 # we also need to identify indented blocks of code when replaying
2484 2460 # logs and put them together before passing them to an exec
2485 2461 # statement. This takes a bit of regexp and look-ahead work in the
2486 2462 # file. It's easiest if we swallow the whole thing in memory
2487 2463 # first, and manually walk through the lines list moving the
2488 2464 # counter ourselves.
2489 2465 indent_re = re.compile('\s+\S')
2490 2466 xfile = open(fname)
2491 2467 filelines = xfile.readlines()
2492 2468 xfile.close()
2493 2469 nlines = len(filelines)
2494 2470 lnum = 0
2495 2471 while lnum < nlines:
2496 2472 line = filelines[lnum]
2497 2473 lnum += 1
2498 2474 # don't re-insert logger status info into cache
2499 2475 if line.startswith('#log#'):
2500 2476 continue
2501 2477 else:
2502 2478 # build a block of code (maybe a single line) for execution
2503 2479 block = line
2504 2480 try:
2505 2481 next = filelines[lnum] # lnum has already incremented
2506 2482 except:
2507 2483 next = None
2508 2484 while next and indent_re.match(next):
2509 2485 block += next
2510 2486 lnum += 1
2511 2487 try:
2512 2488 next = filelines[lnum]
2513 2489 except:
2514 2490 next = None
2515 2491 # now execute the block of one or more lines
2516 2492 try:
2517 2493 exec block in globs,locs
2518 2494 except SystemExit:
2519 2495 pass
2520 2496 except:
2521 2497 badblocks.append(block.rstrip())
2522 2498 if kw['quiet']: # restore stdout
2523 2499 sys.stdout.close()
2524 2500 sys.stdout = stdout_save
2525 2501 print 'Finished replaying log file <%s>' % fname
2526 2502 if badblocks:
2527 2503 print >> sys.stderr, ('\nThe following lines/blocks in file '
2528 2504 '<%s> reported errors:' % fname)
2529 2505
2530 2506 for badline in badblocks:
2531 2507 print >> sys.stderr, badline
2532 2508 else: # regular file execution
2533 2509 try:
2534 2510 execfile(fname,*where)
2535 2511 except SyntaxError:
2536 2512 self.showsyntaxerror()
2537 2513 warn('Failure executing file: <%s>' % fname)
2538 2514 except SystemExit,status:
2539 2515 if not kw['exit_ignore']:
2540 2516 self.showtraceback()
2541 2517 warn('Failure executing file: <%s>' % fname)
2542 2518 except:
2543 2519 self.showtraceback()
2544 2520 warn('Failure executing file: <%s>' % fname)
2545 2521
2546 2522 syspath_cleanup()
2547 2523
2548 2524 #************************* end of file <iplib.py> *****************************
General Comments 0
You need to be logged in to leave comments. Login now