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