##// END OF EJS Templates
- add support for PyCrust-style _getAttributeNames magic method. Closes #50....
fperez -
Show More

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

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