##// END OF EJS Templates
- Work around pexcept buglet which causes wraparound problems with long...
fptest -
Show More

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

@@ -1,526 +1,548 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tools for inspecting Python objects.
3 3
4 4 Uses syntax highlighting for presenting the various information elements.
5 5
6 6 Similar in spirit to the inspect module, but all calls take a name argument to
7 7 reference the name under which an object is being read.
8 8
9 $Id: OInspect.py 1625 2006-08-12 10:34:44Z vivainio $
9 $Id: OInspect.py 1850 2006-10-28 19:48:13Z fptest $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #*****************************************************************************
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 __all__ = ['Inspector','InspectColors']
24 24
25 25 # stdlib modules
26 26 import __builtin__
27 27 import inspect
28 28 import linecache
29 29 import string
30 30 import StringIO
31 31 import types
32 32 import os
33 33 import sys
34 34 # IPython's own
35 35 from IPython import PyColorize
36 36 from IPython.genutils import page,indent,Term,mkdict
37 37 from IPython.Itpl import itpl
38 38 from IPython.wildcard import list_namespace
39 39 from IPython.ColorANSI import *
40 40
41 41 #****************************************************************************
42 42 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
43 43 # simply monkeypatch inspect with code copied from python 2.4.
44 44 if sys.version_info[:2] == (2,3):
45 45 from inspect import ismodule, getabsfile, modulesbyfile
46 46 def getmodule(object):
47 47 """Return the module an object was defined in, or None if not found."""
48 48 if ismodule(object):
49 49 return object
50 50 if hasattr(object, '__module__'):
51 51 return sys.modules.get(object.__module__)
52 52 try:
53 53 file = getabsfile(object)
54 54 except TypeError:
55 55 return None
56 56 if file in modulesbyfile:
57 57 return sys.modules.get(modulesbyfile[file])
58 58 for module in sys.modules.values():
59 59 if hasattr(module, '__file__'):
60 60 modulesbyfile[
61 61 os.path.realpath(
62 62 getabsfile(module))] = module.__name__
63 63 if file in modulesbyfile:
64 64 return sys.modules.get(modulesbyfile[file])
65 65 main = sys.modules['__main__']
66 66 if not hasattr(object, '__name__'):
67 67 return None
68 68 if hasattr(main, object.__name__):
69 69 mainobject = getattr(main, object.__name__)
70 70 if mainobject is object:
71 71 return main
72 72 builtin = sys.modules['__builtin__']
73 73 if hasattr(builtin, object.__name__):
74 74 builtinobject = getattr(builtin, object.__name__)
75 75 if builtinobject is object:
76 76 return builtin
77 77
78 78 inspect.getmodule = getmodule
79 79
80 80 #****************************************************************************
81 81 # Builtin color schemes
82 82
83 83 Colors = TermColors # just a shorthand
84 84
85 85 # Build a few color schemes
86 86 NoColor = ColorScheme(
87 87 'NoColor',{
88 88 'header' : Colors.NoColor,
89 89 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
90 90 } )
91 91
92 92 LinuxColors = ColorScheme(
93 93 'Linux',{
94 94 'header' : Colors.LightRed,
95 95 'normal' : Colors.Normal # color off (usu. Colors.Normal)
96 96 } )
97 97
98 98 LightBGColors = ColorScheme(
99 99 'LightBG',{
100 100 'header' : Colors.Red,
101 101 'normal' : Colors.Normal # color off (usu. Colors.Normal)
102 102 } )
103 103
104 104 # Build table of color schemes (needed by the parser)
105 105 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
106 106 'Linux')
107 107
108 108 #****************************************************************************
109 109 # Auxiliary functions
110 110 def getdoc(obj):
111 111 """Stable wrapper around inspect.getdoc.
112 112
113 113 This can't crash because of attribute problems.
114 114
115 115 It also attempts to call a getdoc() method on the given object. This
116 116 allows objects which provide their docstrings via non-standard mechanisms
117 117 (like Pyro proxies) to still be inspected by ipython's ? system."""
118 118
119 119 ds = None # default return value
120 120 try:
121 121 ds = inspect.getdoc(obj)
122 122 except:
123 123 # Harden against an inspect failure, which can occur with
124 124 # SWIG-wrapped extensions.
125 125 pass
126 126 # Allow objects to offer customized documentation via a getdoc method:
127 127 try:
128 128 ds2 = obj.getdoc()
129 129 except:
130 130 pass
131 131 else:
132 132 # if we get extra info, we add it to the normal docstring.
133 133 if ds is None:
134 134 ds = ds2
135 135 else:
136 136 ds = '%s\n%s' % (ds,ds2)
137 137 return ds
138 138
139 def getsource(obj,is_binary=False):
140 """Wrapper around inspect.getsource.
141
142 This can be modified by other projects to provide customized source
143 extraction.
144
145 Inputs:
146
147 - obj: an object whose source code we will attempt to extract.
148
149 Optional inputs:
150
151 - is_binary: whether the object is known to come from a binary source.
152 This implementation will skip returning any output for binary objects, but
153 custom extractors may know how to meaninfully process them."""
154
155 if is_binary:
156 return None
157 else:
158 return inspect.getsource(obj)
159
139 160 #****************************************************************************
140 161 # Class definitions
141 162
142 163 class myStringIO(StringIO.StringIO):
143 164 """Adds a writeln method to normal StringIO."""
144 165 def writeln(self,*arg,**kw):
145 166 """Does a write() and then a write('\n')"""
146 167 self.write(*arg,**kw)
147 168 self.write('\n')
148 169
149 170 class Inspector:
150 171 def __init__(self,color_table,code_color_table,scheme,
151 172 str_detail_level=0):
152 173 self.color_table = color_table
153 174 self.parser = PyColorize.Parser(code_color_table,out='str')
154 175 self.format = self.parser.format
155 176 self.str_detail_level = str_detail_level
156 177 self.set_active_scheme(scheme)
157 178
158 179 def __getargspec(self,obj):
159 180 """Get the names and default values of a function's arguments.
160 181
161 182 A tuple of four things is returned: (args, varargs, varkw, defaults).
162 183 'args' is a list of the argument names (it may contain nested lists).
163 184 'varargs' and 'varkw' are the names of the * and ** arguments or None.
164 185 'defaults' is an n-tuple of the default values of the last n arguments.
165 186
166 187 Modified version of inspect.getargspec from the Python Standard
167 188 Library."""
168 189
169 190 if inspect.isfunction(obj):
170 191 func_obj = obj
171 192 elif inspect.ismethod(obj):
172 193 func_obj = obj.im_func
173 194 else:
174 195 raise TypeError, 'arg is not a Python function'
175 196 args, varargs, varkw = inspect.getargs(func_obj.func_code)
176 197 return args, varargs, varkw, func_obj.func_defaults
177 198
178 199 def __getdef(self,obj,oname=''):
179 200 """Return the definition header for any callable object.
180 201
181 202 If any exception is generated, None is returned instead and the
182 203 exception is suppressed."""
183 204
184 205 try:
185 206 return oname + inspect.formatargspec(*self.__getargspec(obj))
186 207 except:
187 208 return None
188 209
189 210 def __head(self,h):
190 211 """Return a header string with proper colors."""
191 212 return '%s%s%s' % (self.color_table.active_colors.header,h,
192 213 self.color_table.active_colors.normal)
193 214
194 215 def set_active_scheme(self,scheme):
195 216 self.color_table.set_active_scheme(scheme)
196 217 self.parser.color_table.set_active_scheme(scheme)
197 218
198 219 def noinfo(self,msg,oname):
199 220 """Generic message when no information is found."""
200 221 print 'No %s found' % msg,
201 222 if oname:
202 223 print 'for %s' % oname
203 224 else:
204 225 print
205 226
206 227 def pdef(self,obj,oname=''):
207 228 """Print the definition header for any callable object.
208 229
209 230 If the object is a class, print the constructor information."""
210 231
211 232 if not callable(obj):
212 233 print 'Object is not callable.'
213 234 return
214 235
215 236 header = ''
216 237 if type(obj) is types.ClassType:
217 238 header = self.__head('Class constructor information:\n')
218 239 obj = obj.__init__
219 240 elif type(obj) is types.InstanceType:
220 241 obj = obj.__call__
221 242
222 243 output = self.__getdef(obj,oname)
223 244 if output is None:
224 245 self.noinfo('definition header',oname)
225 246 else:
226 247 print >>Term.cout, header,self.format(output),
227 248
228 249 def pdoc(self,obj,oname='',formatter = None):
229 250 """Print the docstring for any object.
230 251
231 252 Optional:
232 253 -formatter: a function to run the docstring through for specially
233 254 formatted docstrings."""
234 255
235 256 head = self.__head # so that itpl can find it even if private
236 257 ds = getdoc(obj)
237 258 if formatter:
238 259 ds = formatter(ds)
239 260 if type(obj) is types.ClassType:
240 261 init_ds = getdoc(obj.__init__)
241 262 output = itpl('$head("Class Docstring:")\n'
242 263 '$indent(ds)\n'
243 264 '$head("Constructor Docstring"):\n'
244 265 '$indent(init_ds)')
245 266 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
246 267 call_ds = getdoc(obj.__call__)
247 268 if call_ds:
248 269 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
249 270 '$head("Calling Docstring:")\n$indent(call_ds)')
250 271 else:
251 272 output = ds
252 273 else:
253 274 output = ds
254 275 if output is None:
255 276 self.noinfo('documentation',oname)
256 277 return
257 278 page(output)
258 279
259 280 def psource(self,obj,oname=''):
260 281 """Print the source code for an object."""
261 282
262 283 # Flush the source cache because inspect can return out-of-date source
263 284 linecache.checkcache()
264 285 try:
265 src = inspect.getsource(obj)
286 src = getsource(obj)
266 287 except:
267 288 self.noinfo('source',oname)
268 289 else:
269 290 page(self.format(src))
270 291
271 292 def pfile(self,obj,oname=''):
272 293 """Show the whole file where an object was defined."""
273 294 try:
274 295 sourcelines,lineno = inspect.getsourcelines(obj)
275 296 except:
276 297 self.noinfo('file',oname)
277 298 else:
278 299 # run contents of file through pager starting at line
279 300 # where the object is defined
280 301 ofile = inspect.getabsfile(obj)
281 302
282 303 if (ofile.endswith('.so') or ofile.endswith('.dll')):
283 304 print 'File %r is binary, not printing.' % ofile
284 305 elif not os.path.isfile(ofile):
285 306 print 'File %r does not exist, not printing.' % ofile
286 307 else:
287 308 # Print only text files, not extension binaries.
288 309 page(self.format(open(ofile).read()),lineno)
289 310 #page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
290 311
291 312 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
292 313 """Show detailed information about an object.
293 314
294 315 Optional arguments:
295 316
296 317 - oname: name of the variable pointing to the object.
297 318
298 319 - formatter: special formatter for docstrings (see pdoc)
299 320
300 321 - info: a structure with some information fields which may have been
301 322 precomputed already.
302 323
303 324 - detail_level: if set to 1, more information is given.
304 325 """
305 326
306 327 obj_type = type(obj)
307 328
308 329 header = self.__head
309 330 if info is None:
310 331 ismagic = 0
311 332 isalias = 0
312 333 ospace = ''
313 334 else:
314 335 ismagic = info.ismagic
315 336 isalias = info.isalias
316 337 ospace = info.namespace
317 338 # Get docstring, special-casing aliases:
318 339 if isalias:
319 340 ds = "Alias to the system command:\n %s" % obj[1]
320 341 else:
321 342 ds = getdoc(obj)
322 343 if ds is None:
323 344 ds = '<no docstring>'
324 345 if formatter is not None:
325 346 ds = formatter(ds)
326 347
327 348 # store output in a list which gets joined with \n at the end.
328 349 out = myStringIO()
329 350
330 351 string_max = 200 # max size of strings to show (snipped if longer)
331 352 shalf = int((string_max -5)/2)
332 353
333 354 if ismagic:
334 355 obj_type_name = 'Magic function'
335 356 elif isalias:
336 357 obj_type_name = 'System alias'
337 358 else:
338 359 obj_type_name = obj_type.__name__
339 360 out.writeln(header('Type:\t\t')+obj_type_name)
340 361
341 362 try:
342 363 bclass = obj.__class__
343 364 out.writeln(header('Base Class:\t')+str(bclass))
344 365 except: pass
345 366
346 367 # String form, but snip if too long in ? form (full in ??)
347 368 if detail_level >= self.str_detail_level:
348 369 try:
349 370 ostr = str(obj)
350 371 str_head = 'String Form:'
351 372 if not detail_level and len(ostr)>string_max:
352 373 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
353 374 ostr = ("\n" + " " * len(str_head.expandtabs())).\
354 375 join(map(string.strip,ostr.split("\n")))
355 376 if ostr.find('\n') > -1:
356 377 # Print multi-line strings starting at the next line.
357 378 str_sep = '\n'
358 379 else:
359 380 str_sep = '\t'
360 381 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
361 382 except:
362 383 pass
363 384
364 385 if ospace:
365 386 out.writeln(header('Namespace:\t')+ospace)
366 387
367 388 # Length (for strings and lists)
368 389 try:
369 390 length = str(len(obj))
370 391 out.writeln(header('Length:\t\t')+length)
371 392 except: pass
372 393
373 394 # Filename where object was defined
374 395 binary_file = False
375 396 try:
376 397 fname = inspect.getabsfile(obj)
377 398 if fname.endswith('<string>'):
378 399 fname = 'Dynamically generated function. No source code available.'
379 400 if (fname.endswith('.so') or fname.endswith('.dll') or
380 401 not os.path.isfile(fname)):
381 402 binary_file = True
382 403 out.writeln(header('File:\t\t')+fname)
383 404 except:
384 405 # if anything goes wrong, we don't want to show source, so it's as
385 406 # if the file was binary
386 407 binary_file = True
387 408
388 409 # reconstruct the function definition and print it:
389 410 defln = self.__getdef(obj,oname)
390 411 if defln:
391 412 out.write(header('Definition:\t')+self.format(defln))
392 413
393 414 # Docstrings only in detail 0 mode, since source contains them (we
394 415 # avoid repetitions). If source fails, we add them back, see below.
395 416 if ds and detail_level == 0:
396 417 out.writeln(header('Docstring:\n') + indent(ds))
397 418
398 419
399 420 # Original source code for any callable
400 421 if detail_level:
401 422 # Flush the source cache because inspect can return out-of-date source
402 423 linecache.checkcache()
403 424 source_success = False
404 425 try:
405 if not binary_file:
406 source = self.format(inspect.getsource(obj))
426 source = self.format(getsource(obj,binary_file))
427 if source:
407 428 out.write(header('Source:\n')+source.rstrip())
408 429 source_success = True
409 except:
430 except Exception, msg:
410 431 pass
411 432
412 433 if ds and not source_success:
413 out.writeln(header('Docstring [source file open failed]:\n') + indent(ds))
434 out.writeln(header('Docstring [source file open failed]:\n')
435 + indent(ds))
414 436
415 437 # Constructor docstring for classes
416 438 if obj_type is types.ClassType:
417 439 # reconstruct the function definition and print it:
418 440 try:
419 441 obj_init = obj.__init__
420 442 except AttributeError:
421 443 init_def = init_ds = None
422 444 else:
423 445 init_def = self.__getdef(obj_init,oname)
424 446 init_ds = getdoc(obj_init)
425 447
426 448 if init_def or init_ds:
427 449 out.writeln(header('\nConstructor information:'))
428 450 if init_def:
429 451 out.write(header('Definition:\t')+ self.format(init_def))
430 452 if init_ds:
431 453 out.writeln(header('Docstring:\n') + indent(init_ds))
432 454 # and class docstring for instances:
433 455 elif obj_type is types.InstanceType:
434 456
435 457 # First, check whether the instance docstring is identical to the
436 458 # class one, and print it separately if they don't coincide. In
437 459 # most cases they will, but it's nice to print all the info for
438 460 # objects which use instance-customized docstrings.
439 461 if ds:
440 462 class_ds = getdoc(obj.__class__)
441 463 if class_ds and ds != class_ds:
442 464 out.writeln(header('Class Docstring:\n') +
443 465 indent(class_ds))
444 466
445 467 # Next, try to show constructor docstrings
446 468 try:
447 469 init_ds = getdoc(obj.__init__)
448 470 except AttributeError:
449 471 init_ds = None
450 472 if init_ds:
451 473 out.writeln(header('Constructor Docstring:\n') +
452 474 indent(init_ds))
453 475
454 476 # Call form docstring for callable instances
455 477 if hasattr(obj,'__call__'):
456 478 out.writeln(header('Callable:\t')+'Yes')
457 479 call_def = self.__getdef(obj.__call__,oname)
458 480 if call_def is None:
459 481 out.write(header('Call def:\t')+
460 482 'Calling definition not available.')
461 483 else:
462 484 out.write(header('Call def:\t')+self.format(call_def))
463 485 call_ds = getdoc(obj.__call__)
464 486 if call_ds:
465 487 out.writeln(header('Call docstring:\n') + indent(call_ds))
466 488
467 489 # Finally send to printer/pager
468 490 output = out.getvalue()
469 491 if output:
470 492 page(output)
471 493 # end pinfo
472 494
473 495 def psearch(self,pattern,ns_table,ns_search=[],
474 496 ignore_case=False,show_all=False):
475 497 """Search namespaces with wildcards for objects.
476 498
477 499 Arguments:
478 500
479 501 - pattern: string containing shell-like wildcards to use in namespace
480 502 searches and optionally a type specification to narrow the search to
481 503 objects of that type.
482 504
483 505 - ns_table: dict of name->namespaces for search.
484 506
485 507 Optional arguments:
486 508
487 509 - ns_search: list of namespace names to include in search.
488 510
489 511 - ignore_case(False): make the search case-insensitive.
490 512
491 513 - show_all(False): show all names, including those starting with
492 514 underscores.
493 515 """
494 516 # defaults
495 517 type_pattern = 'all'
496 518 filter = ''
497 519
498 520 cmds = pattern.split()
499 521 len_cmds = len(cmds)
500 522 if len_cmds == 1:
501 523 # Only filter pattern given
502 524 filter = cmds[0]
503 525 elif len_cmds == 2:
504 526 # Both filter and type specified
505 527 filter,type_pattern = cmds
506 528 else:
507 529 raise ValueError('invalid argument string for psearch: <%s>' %
508 530 pattern)
509 531
510 532 # filter search namespaces
511 533 for name in ns_search:
512 534 if name not in ns_table:
513 535 raise ValueError('invalid namespace <%s>. Valid names: %s' %
514 536 (name,ns_table.keys()))
515 537
516 538 #print 'type_pattern:',type_pattern # dbg
517 539 search_result = []
518 540 for ns_name in ns_search:
519 541 ns = ns_table[ns_name]
520 542 tmp_res = list(list_namespace(ns,type_pattern,filter,
521 543 ignore_case=ignore_case,
522 544 show_all=show_all))
523 545 search_result.extend(tmp_res)
524 546 search_result.sort()
525 547
526 548 page('\n'.join(search_result))
@@ -1,588 +1,588 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Classes for handling input/output prompts.
4 4
5 $Id: Prompts.py 1366 2006-06-15 19:45:50Z vivainio $"""
5 $Id: Prompts.py 1850 2006-10-28 19:48:13Z fptest $"""
6 6
7 7 #*****************************************************************************
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 from IPython import Release
15 15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 16 __license__ = Release.license
17 17 __version__ = Release.version
18 18
19 19 #****************************************************************************
20 20 # Required modules
21 21 import __builtin__
22 22 import os
23 23 import socket
24 24 import sys
25 25 import time
26 26
27 27 # IPython's own
28 28 from IPython import ColorANSI
29 29 from IPython.Itpl import ItplNS
30 30 from IPython.ipstruct import Struct
31 31 from IPython.macro import Macro
32 32 from IPython.genutils import *
33 33
34 34 #****************************************************************************
35 35 #Color schemes for Prompts.
36 36
37 37 PromptColors = ColorANSI.ColorSchemeTable()
38 38 InputColors = ColorANSI.InputTermColors # just a shorthand
39 39 Colors = ColorANSI.TermColors # just a shorthand
40 40
41 41 PromptColors.add_scheme(ColorANSI.ColorScheme(
42 42 'NoColor',
43 43 in_prompt = InputColors.NoColor, # Input prompt
44 44 in_number = InputColors.NoColor, # Input prompt number
45 45 in_prompt2 = InputColors.NoColor, # Continuation prompt
46 46 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
47 47
48 48 out_prompt = Colors.NoColor, # Output prompt
49 49 out_number = Colors.NoColor, # Output prompt number
50 50
51 51 normal = Colors.NoColor # color off (usu. Colors.Normal)
52 52 ))
53 53
54 54 # make some schemes as instances so we can copy them for modification easily:
55 55 __PColLinux = ColorANSI.ColorScheme(
56 56 'Linux',
57 57 in_prompt = InputColors.Green,
58 58 in_number = InputColors.LightGreen,
59 59 in_prompt2 = InputColors.Green,
60 60 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
61 61
62 62 out_prompt = Colors.Red,
63 63 out_number = Colors.LightRed,
64 64
65 65 normal = Colors.Normal
66 66 )
67 67 # Don't forget to enter it into the table!
68 68 PromptColors.add_scheme(__PColLinux)
69 69
70 70 # Slightly modified Linux for light backgrounds
71 71 __PColLightBG = __PColLinux.copy('LightBG')
72 72
73 73 __PColLightBG.colors.update(
74 74 in_prompt = InputColors.Blue,
75 75 in_number = InputColors.LightBlue,
76 76 in_prompt2 = InputColors.Blue
77 77 )
78 78 PromptColors.add_scheme(__PColLightBG)
79 79
80 80 del Colors,InputColors
81 81
82 82 #-----------------------------------------------------------------------------
83 83 def multiple_replace(dict, text):
84 84 """ Replace in 'text' all occurences of any key in the given
85 85 dictionary by its corresponding value. Returns the new string."""
86 86
87 87 # Function by Xavier Defrang, originally found at:
88 88 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
89 89
90 90 # Create a regular expression from the dictionary keys
91 91 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
92 92 # For each match, look-up corresponding value in dictionary
93 93 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
94 94
95 95 #-----------------------------------------------------------------------------
96 96 # Special characters that can be used in prompt templates, mainly bash-like
97 97
98 98 # If $HOME isn't defined (Windows), make it an absurd string so that it can
99 99 # never be expanded out into '~'. Basically anything which can never be a
100 100 # reasonable directory name will do, we just want the $HOME -> '~' operation
101 101 # to become a no-op. We pre-compute $HOME here so it's not done on every
102 102 # prompt call.
103 103
104 104 # FIXME:
105 105
106 106 # - This should be turned into a class which does proper namespace management,
107 107 # since the prompt specials need to be evaluated in a certain namespace.
108 108 # Currently it's just globals, which need to be managed manually by code
109 109 # below.
110 110
111 111 # - I also need to split up the color schemes from the prompt specials
112 112 # somehow. I don't have a clean design for that quite yet.
113 113
114 114 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
115 115
116 116 # We precompute a few more strings here for the prompt_specials, which are
117 117 # fixed once ipython starts. This reduces the runtime overhead of computing
118 118 # prompt strings.
119 119 USER = os.environ.get("USER")
120 120 HOSTNAME = socket.gethostname()
121 121 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
122 122 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
123 123
124 124 prompt_specials_color = {
125 125 # Prompt/history count
126 126 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
127 127 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 128 # Prompt/history count, with the actual digits replaced by dots. Used
129 129 # mainly in continuation prompts (prompt_in2)
130 130 '\\D': '${"."*len(str(self.cache.prompt_count))}',
131 131 # Current working directory
132 132 '\\w': '${os.getcwd()}',
133 133 # Current time
134 134 '\\t' : '${time.strftime("%H:%M:%S")}',
135 135 # Basename of current working directory.
136 136 # (use os.sep to make this portable across OSes)
137 137 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
138 138 # These X<N> are an extension to the normal bash prompts. They return
139 139 # N terms of the path, after replacing $HOME with '~'
140 140 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
141 141 '\\X1': '${self.cwd_filt(1)}',
142 142 '\\X2': '${self.cwd_filt(2)}',
143 143 '\\X3': '${self.cwd_filt(3)}',
144 144 '\\X4': '${self.cwd_filt(4)}',
145 145 '\\X5': '${self.cwd_filt(5)}',
146 146 # Y<N> are similar to X<N>, but they show '~' if it's the directory
147 147 # N+1 in the list. Somewhat like %cN in tcsh.
148 148 '\\Y0': '${self.cwd_filt2(0)}',
149 149 '\\Y1': '${self.cwd_filt2(1)}',
150 150 '\\Y2': '${self.cwd_filt2(2)}',
151 151 '\\Y3': '${self.cwd_filt2(3)}',
152 152 '\\Y4': '${self.cwd_filt2(4)}',
153 153 '\\Y5': '${self.cwd_filt2(5)}',
154 154 # Hostname up to first .
155 155 '\\h': HOSTNAME_SHORT,
156 156 # Full hostname
157 157 '\\H': HOSTNAME,
158 158 # Username of current user
159 159 '\\u': USER,
160 160 # Escaped '\'
161 161 '\\\\': '\\',
162 162 # Newline
163 163 '\\n': '\n',
164 164 # Carriage return
165 165 '\\r': '\r',
166 166 # Release version
167 167 '\\v': __version__,
168 168 # Root symbol ($ or #)
169 169 '\\$': ROOT_SYMBOL,
170 170 }
171 171
172 172 # A copy of the prompt_specials dictionary but with all color escapes removed,
173 173 # so we can correctly compute the prompt length for the auto_rewrite method.
174 174 prompt_specials_nocolor = prompt_specials_color.copy()
175 175 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
176 176 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
177 177
178 178 # Add in all the InputTermColors color escapes as valid prompt characters.
179 179 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
180 180 # with a color name which may begin with a letter used by any other of the
181 181 # allowed specials. This of course means that \\C will never be allowed for
182 182 # anything else.
183 183 input_colors = ColorANSI.InputTermColors
184 184 for _color in dir(input_colors):
185 185 if _color[0] != '_':
186 186 c_name = '\\C_'+_color
187 187 prompt_specials_color[c_name] = getattr(input_colors,_color)
188 188 prompt_specials_nocolor[c_name] = ''
189 189
190 190 # we default to no color for safety. Note that prompt_specials is a global
191 191 # variable used by all prompt objects.
192 192 prompt_specials = prompt_specials_nocolor
193 193
194 194 #-----------------------------------------------------------------------------
195 195 def str_safe(arg):
196 196 """Convert to a string, without ever raising an exception.
197 197
198 198 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
199 199 error message."""
200 200
201 201 try:
202 202 out = str(arg)
203 203 except UnicodeError:
204 204 try:
205 205 out = arg.encode('utf_8','replace')
206 206 except Exception,msg:
207 207 # let's keep this little duplication here, so that the most common
208 208 # case doesn't suffer from a double try wrapping.
209 209 out = '<ERROR: %s>' % msg
210 210 except Exception,msg:
211 211 out = '<ERROR: %s>' % msg
212 212 return out
213 213
214 214 class BasePrompt:
215 215 """Interactive prompt similar to Mathematica's."""
216 216 def __init__(self,cache,sep,prompt,pad_left=False):
217 217
218 218 # Hack: we access information about the primary prompt through the
219 219 # cache argument. We need this, because we want the secondary prompt
220 220 # to be aligned with the primary one. Color table info is also shared
221 221 # by all prompt classes through the cache. Nice OO spaghetti code!
222 222 self.cache = cache
223 223 self.sep = sep
224 224
225 225 # regexp to count the number of spaces at the end of a prompt
226 226 # expression, useful for prompt auto-rewriting
227 227 self.rspace = re.compile(r'(\s*)$')
228 228 # Flag to left-pad prompt strings to match the length of the primary
229 229 # prompt
230 230 self.pad_left = pad_left
231 231 # Set template to create each actual prompt (where numbers change)
232 232 self.p_template = prompt
233 233 self.set_p_str()
234 234
235 235 def set_p_str(self):
236 236 """ Set the interpolating prompt strings.
237 237
238 238 This must be called every time the color settings change, because the
239 239 prompt_specials global may have changed."""
240 240
241 241 import os,time # needed in locals for prompt string handling
242 242 loc = locals()
243 243 self.p_str = ItplNS('%s%s%s' %
244 244 ('${self.sep}${self.col_p}',
245 245 multiple_replace(prompt_specials, self.p_template),
246 246 '${self.col_norm}'),self.cache.user_ns,loc)
247 247
248 248 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
249 249 self.p_template),
250 250 self.cache.user_ns,loc)
251 251
252 252 def write(self,msg): # dbg
253 253 sys.stdout.write(msg)
254 254 return ''
255 255
256 256 def __str__(self):
257 257 """Return a string form of the prompt.
258 258
259 259 This for is useful for continuation and output prompts, since it is
260 260 left-padded to match lengths with the primary one (if the
261 261 self.pad_left attribute is set)."""
262 262
263 263 out_str = str_safe(self.p_str)
264 264 if self.pad_left:
265 265 # We must find the amount of padding required to match lengths,
266 266 # taking the color escapes (which are invisible on-screen) into
267 267 # account.
268 268 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
269 269 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
270 270 return format % out_str
271 271 else:
272 272 return out_str
273 273
274 274 # these path filters are put in as methods so that we can control the
275 275 # namespace where the prompt strings get evaluated
276 276 def cwd_filt(self,depth):
277 277 """Return the last depth elements of the current working directory.
278 278
279 279 $HOME is always replaced with '~'.
280 280 If depth==0, the full path is returned."""
281 281
282 282 cwd = os.getcwd().replace(HOME,"~")
283 283 out = os.sep.join(cwd.split(os.sep)[-depth:])
284 284 if out:
285 285 return out
286 286 else:
287 287 return os.sep
288 288
289 289 def cwd_filt2(self,depth):
290 290 """Return the last depth elements of the current working directory.
291 291
292 292 $HOME is always replaced with '~'.
293 293 If depth==0, the full path is returned."""
294 294
295 295 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
296 296 if '~' in cwd and len(cwd) == depth+1:
297 297 depth += 1
298 298 out = os.sep.join(cwd[-depth:])
299 299 if out:
300 300 return out
301 301 else:
302 302 return os.sep
303 303
304 304 class Prompt1(BasePrompt):
305 305 """Input interactive prompt similar to Mathematica's."""
306 306
307 307 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
308 308 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
309 309
310 310 def set_colors(self):
311 311 self.set_p_str()
312 312 Colors = self.cache.color_table.active_colors # shorthand
313 313 self.col_p = Colors.in_prompt
314 314 self.col_num = Colors.in_number
315 315 self.col_norm = Colors.in_normal
316 316 # We need a non-input version of these escapes for the '--->'
317 317 # auto-call prompts used in the auto_rewrite() method.
318 318 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
319 319 self.col_norm_ni = Colors.normal
320 320
321 321 def __str__(self):
322 322 self.cache.prompt_count += 1
323 323 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
324 324 return str_safe(self.p_str)
325 325
326 326 def auto_rewrite(self):
327 327 """Print a string of the form '--->' which lines up with the previous
328 328 input string. Useful for systems which re-write the user input when
329 329 handling automatically special syntaxes."""
330 330
331 331 curr = str(self.cache.last_prompt)
332 332 nrspaces = len(self.rspace.search(curr).group())
333 333 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
334 334 ' '*nrspaces,self.col_norm_ni)
335 335
336 336 class PromptOut(BasePrompt):
337 337 """Output interactive prompt similar to Mathematica's."""
338 338
339 339 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
340 340 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
341 341 if not self.p_template:
342 342 self.__str__ = lambda: ''
343 343
344 344 def set_colors(self):
345 345 self.set_p_str()
346 346 Colors = self.cache.color_table.active_colors # shorthand
347 347 self.col_p = Colors.out_prompt
348 348 self.col_num = Colors.out_number
349 349 self.col_norm = Colors.normal
350 350
351 351 class Prompt2(BasePrompt):
352 352 """Interactive continuation prompt."""
353 353
354 354 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
355 355 self.cache = cache
356 356 self.p_template = prompt
357 357 self.pad_left = pad_left
358 358 self.set_p_str()
359 359
360 360 def set_p_str(self):
361 361 import os,time # needed in locals for prompt string handling
362 362 loc = locals()
363 363 self.p_str = ItplNS('%s%s%s' %
364 364 ('${self.col_p2}',
365 365 multiple_replace(prompt_specials, self.p_template),
366 366 '$self.col_norm'),
367 367 self.cache.user_ns,loc)
368 368 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
369 369 self.p_template),
370 370 self.cache.user_ns,loc)
371 371
372 372 def set_colors(self):
373 373 self.set_p_str()
374 374 Colors = self.cache.color_table.active_colors
375 375 self.col_p2 = Colors.in_prompt2
376 376 self.col_norm = Colors.in_normal
377 377 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
378 378 # updated their prompt_in2 definitions. Remove eventually.
379 379 self.col_p = Colors.out_prompt
380 380 self.col_num = Colors.out_number
381 381
382 382
383 383 #-----------------------------------------------------------------------------
384 384 class CachedOutput:
385 385 """Class for printing output from calculations while keeping a cache of
386 386 reults. It dynamically creates global variables prefixed with _ which
387 387 contain these results.
388 388
389 389 Meant to be used as a sys.displayhook replacement, providing numbered
390 390 prompts and cache services.
391 391
392 392 Initialize with initial and final values for cache counter (this defines
393 393 the maximum size of the cache."""
394 394
395 395 def __init__(self,shell,cache_size,Pprint,
396 396 colors='NoColor',input_sep='\n',
397 397 output_sep='\n',output_sep2='',
398 398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
399 399
400 400 cache_size_min = 3
401 401 if cache_size <= 0:
402 402 self.do_full_cache = 0
403 403 cache_size = 0
404 404 elif cache_size < cache_size_min:
405 405 self.do_full_cache = 0
406 406 cache_size = 0
407 407 warn('caching was disabled (min value for cache size is %s).' %
408 408 cache_size_min,level=3)
409 409 else:
410 410 self.do_full_cache = 1
411 411
412 412 self.cache_size = cache_size
413 413 self.input_sep = input_sep
414 414
415 415 # we need a reference to the user-level namespace
416 416 self.shell = shell
417 417 self.user_ns = shell.user_ns
418 418 # and to the user's input
419 419 self.input_hist = shell.input_hist
420 420 # and to the user's logger, for logging output
421 421 self.logger = shell.logger
422 422
423 423 # Set input prompt strings and colors
424 424 if cache_size == 0:
425 425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
426 426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
427 427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
428 428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
429 429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
430 430
431 431 self.color_table = PromptColors
432 432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
433 433 pad_left=pad_left)
434 434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
435 435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
436 436 pad_left=pad_left)
437 437 self.set_colors(colors)
438 438
439 439 # other more normal stuff
440 440 # b/c each call to the In[] prompt raises it by 1, even the first.
441 441 self.prompt_count = 0
442 442 # Store the last prompt string each time, we need it for aligning
443 443 # continuation and auto-rewrite prompts
444 444 self.last_prompt = ''
445 445 self.Pprint = Pprint
446 446 self.output_sep = output_sep
447 447 self.output_sep2 = output_sep2
448 448 self._,self.__,self.___ = '','',''
449 449 self.pprint_types = map(type,[(),[],{}])
450 450
451 451 # these are deliberately global:
452 452 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
453 453 self.user_ns.update(to_user_ns)
454 454
455 455 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
456 456 if p_str is None:
457 457 if self.do_full_cache:
458 458 return cache_def
459 459 else:
460 460 return no_cache_def
461 461 else:
462 462 return p_str
463 463
464 464 def set_colors(self,colors):
465 465 """Set the active color scheme and configure colors for the three
466 466 prompt subsystems."""
467 467
468 468 # FIXME: the prompt_specials global should be gobbled inside this
469 469 # class instead. Do it when cleaning up the whole 3-prompt system.
470 470 global prompt_specials
471 471 if colors.lower()=='nocolor':
472 472 prompt_specials = prompt_specials_nocolor
473 473 else:
474 474 prompt_specials = prompt_specials_color
475 475
476 476 self.color_table.set_active_scheme(colors)
477 477 self.prompt1.set_colors()
478 478 self.prompt2.set_colors()
479 479 self.prompt_out.set_colors()
480 480
481 481 def __call__(self,arg=None):
482 482 """Printing with history cache management.
483 483
484 484 This is invoked everytime the interpreter needs to print, and is
485 485 activated by setting the variable sys.displayhook to it."""
486 486
487 487 # If something injected a '_' variable in __builtin__, delete
488 488 # ipython's automatic one so we don't clobber that. gettext() in
489 489 # particular uses _, so we need to stay away from it.
490 490 if '_' in __builtin__.__dict__:
491 491 try:
492 492 del self.user_ns['_']
493 493 except KeyError:
494 494 pass
495 495 if arg is not None:
496 496 cout_write = Term.cout.write # fast lookup
497 497 # first handle the cache and counters
498 498
499 499 # do not print output if input ends in ';'
500 500 if self.input_hist[self.prompt_count].endswith(';\n'):
501 501 return
502 502 # don't use print, puts an extra space
503 503 cout_write(self.output_sep)
504 504 outprompt = self.shell.hooks.generate_output_prompt()
505 505 if self.do_full_cache:
506 506 cout_write(outprompt)
507 507
508 508 if isinstance(arg,Macro):
509 509 print 'Executing Macro...'
510 510 # in case the macro takes a long time to execute
511 511 Term.cout.flush()
512 512 self.shell.runlines(arg.value)
513 513 return None
514 514
515 515 # and now call a possibly user-defined print mechanism
516 516 manipulated_val = self.display(arg)
517 517
518 518 # user display hooks can change the variable to be stored in
519 519 # output history
520 520
521 521 if manipulated_val is not None:
522 522 arg = manipulated_val
523 523
524 524 # avoid recursive reference when displaying _oh/Out
525 525 if arg is not self.user_ns['_oh']:
526 526 self.update(arg)
527 527
528 528 if self.logger.log_output:
529 529 self.logger.log_write(repr(arg),'output')
530 530 cout_write(self.output_sep2)
531 531 Term.cout.flush()
532 532
533 533 def _display(self,arg):
534 534 """Default printer method, uses pprint.
535 535
536 536 Do ip.set_hook("result_display", my_displayhook) for custom result
537 537 display, e.g. when your own objects need special formatting.
538 538 """
539 539
540 540 return self.shell.hooks.result_display(arg)
541 541
542 542 # Assign the default display method:
543 543 display = _display
544 544
545 545 def update(self,arg):
546 546 #print '***cache_count', self.cache_count # dbg
547 547 if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
548 548 warn('Output cache limit (currently '+
549 549 `self.cache_size`+' entries) hit.\n'
550 550 'Flushing cache and resetting history counter...\n'
551 551 'The only history variables available will be _,__,___ and _1\n'
552 552 'with the current result.')
553 553
554 554 self.flush()
555 555 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
556 556 # we cause buggy behavior for things like gettext).
557 557 if '_' not in __builtin__.__dict__:
558 558 self.___ = self.__
559 559 self.__ = self._
560 560 self._ = arg
561 561 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
562 562
563 563 # hackish access to top-level namespace to create _1,_2... dynamically
564 564 to_main = {}
565 565 if self.do_full_cache:
566 566 new_result = '_'+`self.prompt_count`
567 567 to_main[new_result] = arg
568 568 self.user_ns.update(to_main)
569 569 self.user_ns['_oh'][self.prompt_count] = arg
570 570
571 571 def flush(self):
572 572 if not self.do_full_cache:
573 573 raise ValueError,"You shouldn't have reached the cache flush "\
574 574 "if full caching is not enabled!"
575 575 # delete auto-generated vars from global namespace
576 576
577 577 for n in range(1,self.prompt_count + 1):
578 578 key = '_'+`n`
579 579 try:
580 580 del self.user_ns[key]
581 581 except: pass
582 582 self.user_ns['_oh'].clear()
583 583
584 584 if '_' not in __builtin__.__dict__:
585 585 self.user_ns.update({'_':None,'__':None, '___':None})
586 586 import gc
587 587 gc.collect() # xxx needed?
588 588
@@ -1,2432 +1,2434 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 1828 2006-10-16 02:04:33Z fptest $
9 $Id: iplib.py 1850 2006-10-28 19:48:13Z fptest $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from IPython import Release
32 32 __author__ = '%s <%s>\n%s <%s>' % \
33 33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 34 __license__ = Release.license
35 35 __version__ = Release.version
36 36
37 37 # Python standard modules
38 38 import __main__
39 39 import __builtin__
40 40 import StringIO
41 41 import bdb
42 42 import cPickle as pickle
43 43 import codeop
44 44 import exceptions
45 45 import glob
46 46 import inspect
47 47 import keyword
48 48 import new
49 49 import os
50 50 import pdb
51 51 import pydoc
52 52 import re
53 53 import shutil
54 54 import string
55 55 import sys
56 56 import tempfile
57 57 import traceback
58 58 import types
59 59 import pickleshare
60 60 from sets import Set
61 61 from pprint import pprint, pformat
62 62
63 63 # IPython's own modules
64 64 import IPython
65 65 from IPython import OInspect,PyColorize,ultraTB
66 66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 67 from IPython.FakeModule import FakeModule
68 68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 69 from IPython.Logger import Logger
70 70 from IPython.Magic import Magic
71 71 from IPython.Prompts import CachedOutput
72 72 from IPython.ipstruct import Struct
73 73 from IPython.background_jobs import BackgroundJobManager
74 74 from IPython.usage import cmd_line_usage,interactive_usage
75 75 from IPython.genutils import *
76 76 import IPython.ipapi
77 77
78 78 # Globals
79 79
80 80 # store the builtin raw_input globally, and use this always, in case user code
81 81 # overwrites it (like wx.py.PyShell does)
82 82 raw_input_original = raw_input
83 83
84 84 # compiled regexps for autoindent management
85 85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 86
87 87
88 88 #****************************************************************************
89 89 # Some utility function definitions
90 90
91 91 ini_spaces_re = re.compile(r'^(\s+)')
92 92
93 93 def num_ini_spaces(strng):
94 94 """Return the number of initial spaces in a string"""
95 95
96 96 ini_spaces = ini_spaces_re.match(strng)
97 97 if ini_spaces:
98 98 return ini_spaces.end()
99 99 else:
100 100 return 0
101 101
102 102 def softspace(file, newvalue):
103 103 """Copied from code.py, to remove the dependency"""
104 104
105 105 oldvalue = 0
106 106 try:
107 107 oldvalue = file.softspace
108 108 except AttributeError:
109 109 pass
110 110 try:
111 111 file.softspace = newvalue
112 112 except (AttributeError, TypeError):
113 113 # "attribute-less object" or "read-only attributes"
114 114 pass
115 115 return oldvalue
116 116
117 117
118 118 #****************************************************************************
119 119 # Local use exceptions
120 120 class SpaceInInput(exceptions.Exception): pass
121 121
122 122
123 123 #****************************************************************************
124 124 # Local use classes
125 125 class Bunch: pass
126 126
127 127 class Undefined: pass
128 128
129 129 class Quitter(object):
130 130 """Simple class to handle exit, similar to Python 2.5's.
131 131
132 132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
133 133 doesn't do (obviously, since it doesn't know about ipython)."""
134 134
135 135 def __init__(self,shell,name):
136 136 self.shell = shell
137 137 self.name = name
138 138
139 139 def __repr__(self):
140 140 return 'Type %s() to exit.' % self.name
141 141 __str__ = __repr__
142 142
143 143 def __call__(self):
144 144 self.shell.exit()
145 145
146 146 class InputList(list):
147 147 """Class to store user input.
148 148
149 149 It's basically a list, but slices return a string instead of a list, thus
150 150 allowing things like (assuming 'In' is an instance):
151 151
152 152 exec In[4:7]
153 153
154 154 or
155 155
156 156 exec In[5:9] + In[14] + In[21:25]"""
157 157
158 158 def __getslice__(self,i,j):
159 159 return ''.join(list.__getslice__(self,i,j))
160 160
161 161 class SyntaxTB(ultraTB.ListTB):
162 162 """Extension which holds some state: the last exception value"""
163 163
164 164 def __init__(self,color_scheme = 'NoColor'):
165 165 ultraTB.ListTB.__init__(self,color_scheme)
166 166 self.last_syntax_error = None
167 167
168 168 def __call__(self, etype, value, elist):
169 169 self.last_syntax_error = value
170 170 ultraTB.ListTB.__call__(self,etype,value,elist)
171 171
172 172 def clear_err_state(self):
173 173 """Return the current error state and clear it"""
174 174 e = self.last_syntax_error
175 175 self.last_syntax_error = None
176 176 return e
177 177
178 178 #****************************************************************************
179 179 # Main IPython class
180 180
181 181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
182 182 # until a full rewrite is made. I've cleaned all cross-class uses of
183 183 # attributes and methods, but too much user code out there relies on the
184 184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
185 185 #
186 186 # But at least now, all the pieces have been separated and we could, in
187 187 # principle, stop using the mixin. This will ease the transition to the
188 188 # chainsaw branch.
189 189
190 190 # For reference, the following is the list of 'self.foo' uses in the Magic
191 191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
192 192 # class, to prevent clashes.
193 193
194 194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
195 195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
196 196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
197 197 # 'self.value']
198 198
199 199 class InteractiveShell(object,Magic):
200 200 """An enhanced console for Python."""
201 201
202 202 # class attribute to indicate whether the class supports threads or not.
203 203 # Subclasses with thread support should override this as needed.
204 204 isthreaded = False
205 205
206 206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
207 207 user_ns = None,user_global_ns=None,banner2='',
208 208 custom_exceptions=((),None),embedded=False):
209 209
210 210 # log system
211 211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
212 212
213 213 # some minimal strict typechecks. For some core data structures, I
214 214 # want actual basic python types, not just anything that looks like
215 215 # one. This is especially true for namespaces.
216 216 for ns in (user_ns,user_global_ns):
217 217 if ns is not None and type(ns) != types.DictType:
218 218 raise TypeError,'namespace must be a dictionary'
219 219
220 220 # Job manager (for jobs run as background threads)
221 221 self.jobs = BackgroundJobManager()
222 222
223 223 # Store the actual shell's name
224 224 self.name = name
225 225
226 226 # We need to know whether the instance is meant for embedding, since
227 227 # global/local namespaces need to be handled differently in that case
228 228 self.embedded = embedded
229 229
230 230 # command compiler
231 231 self.compile = codeop.CommandCompiler()
232 232
233 233 # User input buffer
234 234 self.buffer = []
235 235
236 236 # Default name given in compilation of code
237 237 self.filename = '<ipython console>'
238 238
239 239 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 240 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 241 __builtin__.exit = Quitter(self,'exit')
242 242 __builtin__.quit = Quitter(self,'quit')
243 243
244 244 # Make an empty namespace, which extension writers can rely on both
245 245 # existing and NEVER being used by ipython itself. This gives them a
246 246 # convenient location for storing additional information and state
247 247 # their extensions may require, without fear of collisions with other
248 248 # ipython names that may develop later.
249 249 self.meta = Struct()
250 250
251 251 # Create the namespace where the user will operate. user_ns is
252 252 # normally the only one used, and it is passed to the exec calls as
253 253 # the locals argument. But we do carry a user_global_ns namespace
254 254 # given as the exec 'globals' argument, This is useful in embedding
255 255 # situations where the ipython shell opens in a context where the
256 256 # distinction between locals and globals is meaningful.
257 257
258 258 # FIXME. For some strange reason, __builtins__ is showing up at user
259 259 # level as a dict instead of a module. This is a manual fix, but I
260 260 # should really track down where the problem is coming from. Alex
261 261 # Schmolck reported this problem first.
262 262
263 263 # A useful post by Alex Martelli on this topic:
264 264 # Re: inconsistent value from __builtins__
265 265 # Von: Alex Martelli <aleaxit@yahoo.com>
266 266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
267 267 # Gruppen: comp.lang.python
268 268
269 269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
270 270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
271 271 # > <type 'dict'>
272 272 # > >>> print type(__builtins__)
273 273 # > <type 'module'>
274 274 # > Is this difference in return value intentional?
275 275
276 276 # Well, it's documented that '__builtins__' can be either a dictionary
277 277 # or a module, and it's been that way for a long time. Whether it's
278 278 # intentional (or sensible), I don't know. In any case, the idea is
279 279 # that if you need to access the built-in namespace directly, you
280 280 # should start with "import __builtin__" (note, no 's') which will
281 281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
282 282
283 283 # These routines return properly built dicts as needed by the rest of
284 284 # the code, and can also be used by extension writers to generate
285 285 # properly initialized namespaces.
286 286 user_ns = IPython.ipapi.make_user_ns(user_ns)
287 287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
288 288
289 289 # Assign namespaces
290 290 # This is the namespace where all normal user variables live
291 291 self.user_ns = user_ns
292 292 # Embedded instances require a separate namespace for globals.
293 293 # Normally this one is unused by non-embedded instances.
294 294 self.user_global_ns = user_global_ns
295 295 # A namespace to keep track of internal data structures to prevent
296 296 # them from cluttering user-visible stuff. Will be updated later
297 297 self.internal_ns = {}
298 298
299 299 # Namespace of system aliases. Each entry in the alias
300 300 # table must be a 2-tuple of the form (N,name), where N is the number
301 301 # of positional arguments of the alias.
302 302 self.alias_table = {}
303 303
304 304 # A table holding all the namespaces IPython deals with, so that
305 305 # introspection facilities can search easily.
306 306 self.ns_table = {'user':user_ns,
307 307 'user_global':user_global_ns,
308 308 'alias':self.alias_table,
309 309 'internal':self.internal_ns,
310 310 'builtin':__builtin__.__dict__
311 311 }
312 312
313 313 # The user namespace MUST have a pointer to the shell itself.
314 314 self.user_ns[name] = self
315 315
316 316 # We need to insert into sys.modules something that looks like a
317 317 # module but which accesses the IPython namespace, for shelve and
318 318 # pickle to work interactively. Normally they rely on getting
319 319 # everything out of __main__, but for embedding purposes each IPython
320 320 # instance has its own private namespace, so we can't go shoving
321 321 # everything into __main__.
322 322
323 323 # note, however, that we should only do this for non-embedded
324 324 # ipythons, which really mimic the __main__.__dict__ with their own
325 325 # namespace. Embedded instances, on the other hand, should not do
326 326 # this because they need to manage the user local/global namespaces
327 327 # only, but they live within a 'normal' __main__ (meaning, they
328 328 # shouldn't overtake the execution environment of the script they're
329 329 # embedded in).
330 330
331 331 if not embedded:
332 332 try:
333 333 main_name = self.user_ns['__name__']
334 334 except KeyError:
335 335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 336 else:
337 337 #print "pickle hack in place" # dbg
338 338 #print 'main_name:',main_name # dbg
339 339 sys.modules[main_name] = FakeModule(self.user_ns)
340 340
341 341 # List of input with multi-line handling.
342 342 # Fill its zero entry, user counter starts at 1
343 343 self.input_hist = InputList(['\n'])
344 344 # This one will hold the 'raw' input history, without any
345 345 # pre-processing. This will allow users to retrieve the input just as
346 346 # it was exactly typed in by the user, with %hist -r.
347 347 self.input_hist_raw = InputList(['\n'])
348 348
349 349 # list of visited directories
350 350 try:
351 351 self.dir_hist = [os.getcwd()]
352 352 except IOError, e:
353 353 self.dir_hist = []
354 354
355 355 # dict of output history
356 356 self.output_hist = {}
357 357
358 358 # dict of things NOT to alias (keywords, builtins and some magics)
359 359 no_alias = {}
360 360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
361 361 for key in keyword.kwlist + no_alias_magics:
362 362 no_alias[key] = 1
363 363 no_alias.update(__builtin__.__dict__)
364 364 self.no_alias = no_alias
365 365
366 366 # make global variables for user access to these
367 367 self.user_ns['_ih'] = self.input_hist
368 368 self.user_ns['_oh'] = self.output_hist
369 369 self.user_ns['_dh'] = self.dir_hist
370 370
371 371 # user aliases to input and output histories
372 372 self.user_ns['In'] = self.input_hist
373 373 self.user_ns['Out'] = self.output_hist
374 374
375 375 # Object variable to store code object waiting execution. This is
376 376 # used mainly by the multithreaded shells, but it can come in handy in
377 377 # other situations. No need to use a Queue here, since it's a single
378 378 # item which gets cleared once run.
379 379 self.code_to_run = None
380 380
381 381 # escapes for automatic behavior on the command line
382 382 self.ESC_SHELL = '!'
383 383 self.ESC_HELP = '?'
384 384 self.ESC_MAGIC = '%'
385 385 self.ESC_QUOTE = ','
386 386 self.ESC_QUOTE2 = ';'
387 387 self.ESC_PAREN = '/'
388 388
389 389 # And their associated handlers
390 390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
391 391 self.ESC_QUOTE : self.handle_auto,
392 392 self.ESC_QUOTE2 : self.handle_auto,
393 393 self.ESC_MAGIC : self.handle_magic,
394 394 self.ESC_HELP : self.handle_help,
395 395 self.ESC_SHELL : self.handle_shell_escape,
396 396 }
397 397
398 398 # class initializations
399 399 Magic.__init__(self,self)
400 400
401 401 # Python source parser/formatter for syntax highlighting
402 402 pyformat = PyColorize.Parser().format
403 403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
404 404
405 405 # hooks holds pointers used for user-side customizations
406 406 self.hooks = Struct()
407 407
408 408 # 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(self.var_expand(cmd),
476 476 header='IPython system call: ',
477 477 verbose=self.rc.system_verbose)
478 478
479 479 # RegExp for splitting line contents into pre-char//first
480 480 # word-method//rest. For clarity, each group in on one line.
481 481
482 482 # WARNING: update the regexp if the above escapes are changed, as they
483 483 # are hardwired in.
484 484
485 485 # Don't get carried away with trying to make the autocalling catch too
486 486 # much: it's better to be conservative rather than to trigger hidden
487 487 # evals() somewhere and end up causing side effects.
488 488
489 489 self.line_split = re.compile(r'^([\s*,;/])'
490 490 r'([\?\w\.]+\w*\s*)'
491 491 r'(\(?.*$)')
492 492
493 493 # Original re, keep around for a while in case changes break something
494 494 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
495 495 # r'(\s*[\?\w\.]+\w*\s*)'
496 496 # r'(\(?.*$)')
497 497
498 498 # RegExp to identify potential function names
499 499 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
500 500
501 501 # RegExp to exclude strings with this start from autocalling. In
502 502 # particular, all binary operators should be excluded, so that if foo
503 503 # is callable, foo OP bar doesn't become foo(OP bar), which is
504 504 # invalid. The characters '!=()' don't need to be checked for, as the
505 505 # _prefilter routine explicitely does so, to catch direct calls and
506 506 # rebindings of existing names.
507 507
508 508 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
509 509 # it affects the rest of the group in square brackets.
510 510 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
511 511 '|^is |^not |^in |^and |^or ')
512 512
513 513 # try to catch also methods for stuff in lists/tuples/dicts: off
514 514 # (experimental). For this to work, the line_split regexp would need
515 515 # to be modified so it wouldn't break things at '['. That line is
516 516 # nasty enough that I shouldn't change it until I can test it _well_.
517 517 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
518 518
519 519 # keep track of where we started running (mainly for crash post-mortem)
520 520 self.starting_dir = os.getcwd()
521 521
522 522 # Various switches which can be set
523 523 self.CACHELENGTH = 5000 # this is cheap, it's just text
524 524 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
525 525 self.banner2 = banner2
526 526
527 527 # TraceBack handlers:
528 528
529 529 # Syntax error handler.
530 530 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
531 531
532 532 # The interactive one is initialized with an offset, meaning we always
533 533 # want to remove the topmost item in the traceback, which is our own
534 534 # internal code. Valid modes: ['Plain','Context','Verbose']
535 535 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
536 536 color_scheme='NoColor',
537 537 tb_offset = 1)
538 538
539 539 # IPython itself shouldn't crash. This will produce a detailed
540 540 # post-mortem if it does. But we only install the crash handler for
541 541 # non-threaded shells, the threaded ones use a normal verbose reporter
542 542 # and lose the crash handler. This is because exceptions in the main
543 543 # thread (such as in GUI code) propagate directly to sys.excepthook,
544 544 # and there's no point in printing crash dumps for every user exception.
545 545 if self.isthreaded:
546 546 ipCrashHandler = ultraTB.FormattedTB()
547 547 else:
548 548 from IPython import CrashHandler
549 549 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
550 550 self.set_crash_handler(ipCrashHandler)
551 551
552 552 # and add any custom exception handlers the user may have specified
553 553 self.set_custom_exc(*custom_exceptions)
554 554
555 555 # indentation management
556 556 self.autoindent = False
557 557 self.indent_current_nsp = 0
558 558
559 559 # Make some aliases automatically
560 560 # Prepare list of shell aliases to auto-define
561 561 if os.name == 'posix':
562 562 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
563 563 'mv mv -i','rm rm -i','cp cp -i',
564 564 'cat cat','less less','clear clear',
565 565 # a better ls
566 566 'ls ls -F',
567 567 # long ls
568 568 'll ls -lF')
569 569 # Extra ls aliases with color, which need special treatment on BSD
570 570 # variants
571 571 ls_extra = ( # color ls
572 572 'lc ls -F -o --color',
573 573 # ls normal files only
574 574 'lf ls -F -o --color %l | grep ^-',
575 575 # ls symbolic links
576 576 'lk ls -F -o --color %l | grep ^l',
577 577 # directories or links to directories,
578 578 'ldir ls -F -o --color %l | grep /$',
579 579 # things which are executable
580 580 'lx ls -F -o --color %l | grep ^-..x',
581 581 )
582 582 # The BSDs don't ship GNU ls, so they don't understand the
583 583 # --color switch out of the box
584 584 if 'bsd' in sys.platform:
585 585 ls_extra = ( # ls normal files only
586 586 'lf ls -lF | grep ^-',
587 587 # ls symbolic links
588 588 'lk ls -lF | grep ^l',
589 589 # directories or links to directories,
590 590 'ldir ls -lF | grep /$',
591 591 # things which are executable
592 592 'lx ls -lF | grep ^-..x',
593 593 )
594 594 auto_alias = auto_alias + ls_extra
595 595 elif os.name in ['nt','dos']:
596 596 auto_alias = ('dir dir /on', 'ls dir /on',
597 597 'ddir dir /ad /on', 'ldir dir /ad /on',
598 598 'mkdir mkdir','rmdir rmdir','echo echo',
599 599 'ren ren','cls cls','copy copy')
600 600 else:
601 601 auto_alias = ()
602 602 self.auto_alias = [s.split(None,1) for s in auto_alias]
603 603 # Call the actual (public) initializer
604 604 self.init_auto_alias()
605 605
606 606 # Produce a public API instance
607 607 self.api = IPython.ipapi.IPApi(self)
608 608
609 609 # track which builtins we add, so we can clean up later
610 610 self.builtins_added = {}
611 611 # This method will add the necessary builtins for operation, but
612 612 # tracking what it did via the builtins_added dict.
613 613 self.add_builtins()
614 614
615 615 # end __init__
616 616
617 617 def pre_config_initialization(self):
618 618 """Pre-configuration init method
619 619
620 620 This is called before the configuration files are processed to
621 621 prepare the services the config files might need.
622 622
623 623 self.rc already has reasonable default values at this point.
624 624 """
625 625 rc = self.rc
626 626
627 627 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
628 628
629 629 def post_config_initialization(self):
630 630 """Post configuration init method
631 631
632 632 This is called after the configuration files have been processed to
633 633 'finalize' the initialization."""
634 634
635 635 rc = self.rc
636 636
637 637 # Object inspector
638 638 self.inspector = OInspect.Inspector(OInspect.InspectColors,
639 639 PyColorize.ANSICodeColors,
640 640 'NoColor',
641 641 rc.object_info_string_level)
642 642
643 643 # Load readline proper
644 644 if rc.readline:
645 645 self.init_readline()
646 646
647 647 # local shortcut, this is used a LOT
648 648 self.log = self.logger.log
649 649
650 650 # Initialize cache, set in/out prompts and printing system
651 651 self.outputcache = CachedOutput(self,
652 652 rc.cache_size,
653 653 rc.pprint,
654 654 input_sep = rc.separate_in,
655 655 output_sep = rc.separate_out,
656 656 output_sep2 = rc.separate_out2,
657 657 ps1 = rc.prompt_in1,
658 658 ps2 = rc.prompt_in2,
659 659 ps_out = rc.prompt_out,
660 660 pad_left = rc.prompts_pad_left)
661 661
662 662 # user may have over-ridden the default print hook:
663 663 try:
664 664 self.outputcache.__class__.display = self.hooks.display
665 665 except AttributeError:
666 666 pass
667 667
668 # I don't like assigning globally to sys, because it means when embedding
669 # instances, each embedded instance overrides the previous choice. But
670 # sys.displayhook seems to be called internally by exec, so I don't see a
671 # way around it.
668 # I don't like assigning globally to sys, because it means when
669 # embedding instances, each embedded instance overrides the previous
670 # choice. But sys.displayhook seems to be called internally by exec,
671 # so I don't see a way around it. We first save the original and then
672 # overwrite it.
673 self.sys_displayhook = sys.displayhook
672 674 sys.displayhook = self.outputcache
673 675
674 676 # Set user colors (don't do it in the constructor above so that it
675 677 # doesn't crash if colors option is invalid)
676 678 self.magic_colors(rc.colors)
677 679
678 680 # Set calling of pdb on exceptions
679 681 self.call_pdb = rc.pdb
680 682
681 683 # Load user aliases
682 684 for alias in rc.alias:
683 685 self.magic_alias(alias)
684 686 self.hooks.late_startup_hook()
685 687
686 688 batchrun = False
687 689 for batchfile in [path(arg) for arg in self.rc.args
688 690 if arg.lower().endswith('.ipy')]:
689 691 if not batchfile.isfile():
690 692 print "No such batch file:", batchfile
691 693 continue
692 694 self.api.runlines(batchfile.text())
693 695 batchrun = True
694 696 if batchrun:
695 697 self.exit_now = True
696 698
697 699 def add_builtins(self):
698 700 """Store ipython references into the builtin namespace.
699 701
700 702 Some parts of ipython operate via builtins injected here, which hold a
701 703 reference to IPython itself."""
702 704
703 705 # TODO: deprecate all except _ip; 'jobs' should be installed
704 706 # by an extension and the rest are under _ip, ipalias is redundant
705 707 builtins_new = dict(__IPYTHON__ = self,
706 708 ip_set_hook = self.set_hook,
707 709 jobs = self.jobs,
708 710 ipmagic = self.ipmagic,
709 711 ipalias = self.ipalias,
710 712 ipsystem = self.ipsystem,
711 713 _ip = self.api
712 714 )
713 715 for biname,bival in builtins_new.items():
714 716 try:
715 717 # store the orignal value so we can restore it
716 718 self.builtins_added[biname] = __builtin__.__dict__[biname]
717 719 except KeyError:
718 720 # or mark that it wasn't defined, and we'll just delete it at
719 721 # cleanup
720 722 self.builtins_added[biname] = Undefined
721 723 __builtin__.__dict__[biname] = bival
722 724
723 725 # Keep in the builtins a flag for when IPython is active. We set it
724 726 # with setdefault so that multiple nested IPythons don't clobber one
725 727 # another. Each will increase its value by one upon being activated,
726 728 # which also gives us a way to determine the nesting level.
727 729 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
728 730
729 731 def clean_builtins(self):
730 732 """Remove any builtins which might have been added by add_builtins, or
731 733 restore overwritten ones to their previous values."""
732 734 for biname,bival in self.builtins_added.items():
733 735 if bival is Undefined:
734 736 del __builtin__.__dict__[biname]
735 737 else:
736 738 __builtin__.__dict__[biname] = bival
737 739 self.builtins_added.clear()
738 740
739 741 def set_hook(self,name,hook, priority = 50):
740 742 """set_hook(name,hook) -> sets an internal IPython hook.
741 743
742 744 IPython exposes some of its internal API as user-modifiable hooks. By
743 745 adding your function to one of these hooks, you can modify IPython's
744 746 behavior to call at runtime your own routines."""
745 747
746 748 # At some point in the future, this should validate the hook before it
747 749 # accepts it. Probably at least check that the hook takes the number
748 750 # of args it's supposed to.
749 751 dp = getattr(self.hooks, name, None)
750 752 if name not in IPython.hooks.__all__:
751 753 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
752 754 if not dp:
753 755 dp = IPython.hooks.CommandChainDispatcher()
754 756
755 757 f = new.instancemethod(hook,self,self.__class__)
756 758 try:
757 759 dp.add(f,priority)
758 760 except AttributeError:
759 761 # it was not commandchain, plain old func - replace
760 762 dp = f
761 763
762 764 setattr(self.hooks,name, dp)
763 765
764 766
765 767 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
766 768
767 769 def set_crash_handler(self,crashHandler):
768 770 """Set the IPython crash handler.
769 771
770 772 This must be a callable with a signature suitable for use as
771 773 sys.excepthook."""
772 774
773 775 # Install the given crash handler as the Python exception hook
774 776 sys.excepthook = crashHandler
775 777
776 778 # The instance will store a pointer to this, so that runtime code
777 779 # (such as magics) can access it. This is because during the
778 780 # read-eval loop, it gets temporarily overwritten (to deal with GUI
779 781 # frameworks).
780 782 self.sys_excepthook = sys.excepthook
781 783
782 784
783 785 def set_custom_exc(self,exc_tuple,handler):
784 786 """set_custom_exc(exc_tuple,handler)
785 787
786 788 Set a custom exception handler, which will be called if any of the
787 789 exceptions in exc_tuple occur in the mainloop (specifically, in the
788 790 runcode() method.
789 791
790 792 Inputs:
791 793
792 794 - exc_tuple: a *tuple* of valid exceptions to call the defined
793 795 handler for. It is very important that you use a tuple, and NOT A
794 796 LIST here, because of the way Python's except statement works. If
795 797 you only want to trap a single exception, use a singleton tuple:
796 798
797 799 exc_tuple == (MyCustomException,)
798 800
799 801 - handler: this must be defined as a function with the following
800 802 basic interface: def my_handler(self,etype,value,tb).
801 803
802 804 This will be made into an instance method (via new.instancemethod)
803 805 of IPython itself, and it will be called if any of the exceptions
804 806 listed in the exc_tuple are caught. If the handler is None, an
805 807 internal basic one is used, which just prints basic info.
806 808
807 809 WARNING: by putting in your own exception handler into IPython's main
808 810 execution loop, you run a very good chance of nasty crashes. This
809 811 facility should only be used if you really know what you are doing."""
810 812
811 813 assert type(exc_tuple)==type(()) , \
812 814 "The custom exceptions must be given AS A TUPLE."
813 815
814 816 def dummy_handler(self,etype,value,tb):
815 817 print '*** Simple custom exception handler ***'
816 818 print 'Exception type :',etype
817 819 print 'Exception value:',value
818 820 print 'Traceback :',tb
819 821 print 'Source code :','\n'.join(self.buffer)
820 822
821 823 if handler is None: handler = dummy_handler
822 824
823 825 self.CustomTB = new.instancemethod(handler,self,self.__class__)
824 826 self.custom_exceptions = exc_tuple
825 827
826 828 def set_custom_completer(self,completer,pos=0):
827 829 """set_custom_completer(completer,pos=0)
828 830
829 831 Adds a new custom completer function.
830 832
831 833 The position argument (defaults to 0) is the index in the completers
832 834 list where you want the completer to be inserted."""
833 835
834 836 newcomp = new.instancemethod(completer,self.Completer,
835 837 self.Completer.__class__)
836 838 self.Completer.matchers.insert(pos,newcomp)
837 839
838 840 def _get_call_pdb(self):
839 841 return self._call_pdb
840 842
841 843 def _set_call_pdb(self,val):
842 844
843 845 if val not in (0,1,False,True):
844 846 raise ValueError,'new call_pdb value must be boolean'
845 847
846 848 # store value in instance
847 849 self._call_pdb = val
848 850
849 851 # notify the actual exception handlers
850 852 self.InteractiveTB.call_pdb = val
851 853 if self.isthreaded:
852 854 try:
853 855 self.sys_excepthook.call_pdb = val
854 856 except:
855 857 warn('Failed to activate pdb for threaded exception handler')
856 858
857 859 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
858 860 'Control auto-activation of pdb at exceptions')
859 861
860 862
861 863 # These special functions get installed in the builtin namespace, to
862 864 # provide programmatic (pure python) access to magics, aliases and system
863 865 # calls. This is important for logging, user scripting, and more.
864 866
865 867 # We are basically exposing, via normal python functions, the three
866 868 # mechanisms in which ipython offers special call modes (magics for
867 869 # internal control, aliases for direct system access via pre-selected
868 870 # names, and !cmd for calling arbitrary system commands).
869 871
870 872 def ipmagic(self,arg_s):
871 873 """Call a magic function by name.
872 874
873 875 Input: a string containing the name of the magic function to call and any
874 876 additional arguments to be passed to the magic.
875 877
876 878 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
877 879 prompt:
878 880
879 881 In[1]: %name -opt foo bar
880 882
881 883 To call a magic without arguments, simply use ipmagic('name').
882 884
883 885 This provides a proper Python function to call IPython's magics in any
884 886 valid Python code you can type at the interpreter, including loops and
885 887 compound statements. It is added by IPython to the Python builtin
886 888 namespace upon initialization."""
887 889
888 890 args = arg_s.split(' ',1)
889 891 magic_name = args[0]
890 892 magic_name = magic_name.lstrip(self.ESC_MAGIC)
891 893
892 894 try:
893 895 magic_args = args[1]
894 896 except IndexError:
895 897 magic_args = ''
896 898 fn = getattr(self,'magic_'+magic_name,None)
897 899 if fn is None:
898 900 error("Magic function `%s` not found." % magic_name)
899 901 else:
900 902 magic_args = self.var_expand(magic_args)
901 903 return fn(magic_args)
902 904
903 905 def ipalias(self,arg_s):
904 906 """Call an alias by name.
905 907
906 908 Input: a string containing the name of the alias to call and any
907 909 additional arguments to be passed to the magic.
908 910
909 911 ipalias('name -opt foo bar') is equivalent to typing at the ipython
910 912 prompt:
911 913
912 914 In[1]: name -opt foo bar
913 915
914 916 To call an alias without arguments, simply use ipalias('name').
915 917
916 918 This provides a proper Python function to call IPython's aliases in any
917 919 valid Python code you can type at the interpreter, including loops and
918 920 compound statements. It is added by IPython to the Python builtin
919 921 namespace upon initialization."""
920 922
921 923 args = arg_s.split(' ',1)
922 924 alias_name = args[0]
923 925 try:
924 926 alias_args = args[1]
925 927 except IndexError:
926 928 alias_args = ''
927 929 if alias_name in self.alias_table:
928 930 self.call_alias(alias_name,alias_args)
929 931 else:
930 932 error("Alias `%s` not found." % alias_name)
931 933
932 934 def ipsystem(self,arg_s):
933 935 """Make a system call, using IPython."""
934 936
935 937 self.system(arg_s)
936 938
937 939 def complete(self,text):
938 940 """Return a sorted list of all possible completions on text.
939 941
940 942 Inputs:
941 943
942 944 - text: a string of text to be completed on.
943 945
944 946 This is a wrapper around the completion mechanism, similar to what
945 947 readline does at the command line when the TAB key is hit. By
946 948 exposing it as a method, it can be used by other non-readline
947 949 environments (such as GUIs) for text completion.
948 950
949 951 Simple usage example:
950 952
951 953 In [1]: x = 'hello'
952 954
953 955 In [2]: __IP.complete('x.l')
954 956 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
955 957
956 958 complete = self.Completer.complete
957 959 state = 0
958 960 # use a dict so we get unique keys, since ipyhton's multiple
959 961 # completers can return duplicates.
960 962 comps = {}
961 963 while True:
962 964 newcomp = complete(text,state)
963 965 if newcomp is None:
964 966 break
965 967 comps[newcomp] = 1
966 968 state += 1
967 969 outcomps = comps.keys()
968 970 outcomps.sort()
969 971 return outcomps
970 972
971 973 def set_completer_frame(self, frame=None):
972 974 if frame:
973 975 self.Completer.namespace = frame.f_locals
974 976 self.Completer.global_namespace = frame.f_globals
975 977 else:
976 978 self.Completer.namespace = self.user_ns
977 979 self.Completer.global_namespace = self.user_global_ns
978 980
979 981 def init_auto_alias(self):
980 982 """Define some aliases automatically.
981 983
982 984 These are ALL parameter-less aliases"""
983 985
984 986 for alias,cmd in self.auto_alias:
985 987 self.alias_table[alias] = (0,cmd)
986 988
987 989 def alias_table_validate(self,verbose=0):
988 990 """Update information about the alias table.
989 991
990 992 In particular, make sure no Python keywords/builtins are in it."""
991 993
992 994 no_alias = self.no_alias
993 995 for k in self.alias_table.keys():
994 996 if k in no_alias:
995 997 del self.alias_table[k]
996 998 if verbose:
997 999 print ("Deleting alias <%s>, it's a Python "
998 1000 "keyword or builtin." % k)
999 1001
1000 1002 def set_autoindent(self,value=None):
1001 1003 """Set the autoindent flag, checking for readline support.
1002 1004
1003 1005 If called with no arguments, it acts as a toggle."""
1004 1006
1005 1007 if not self.has_readline:
1006 1008 if os.name == 'posix':
1007 1009 warn("The auto-indent feature requires the readline library")
1008 1010 self.autoindent = 0
1009 1011 return
1010 1012 if value is None:
1011 1013 self.autoindent = not self.autoindent
1012 1014 else:
1013 1015 self.autoindent = value
1014 1016
1015 1017 def rc_set_toggle(self,rc_field,value=None):
1016 1018 """Set or toggle a field in IPython's rc config. structure.
1017 1019
1018 1020 If called with no arguments, it acts as a toggle.
1019 1021
1020 1022 If called with a non-existent field, the resulting AttributeError
1021 1023 exception will propagate out."""
1022 1024
1023 1025 rc_val = getattr(self.rc,rc_field)
1024 1026 if value is None:
1025 1027 value = not rc_val
1026 1028 setattr(self.rc,rc_field,value)
1027 1029
1028 1030 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1029 1031 """Install the user configuration directory.
1030 1032
1031 1033 Can be called when running for the first time or to upgrade the user's
1032 1034 .ipython/ directory with the mode parameter. Valid modes are 'install'
1033 1035 and 'upgrade'."""
1034 1036
1035 1037 def wait():
1036 1038 try:
1037 1039 raw_input("Please press <RETURN> to start IPython.")
1038 1040 except EOFError:
1039 1041 print >> Term.cout
1040 1042 print '*'*70
1041 1043
1042 1044 cwd = os.getcwd() # remember where we started
1043 1045 glb = glob.glob
1044 1046 print '*'*70
1045 1047 if mode == 'install':
1046 1048 print \
1047 1049 """Welcome to IPython. I will try to create a personal configuration directory
1048 1050 where you can customize many aspects of IPython's functionality in:\n"""
1049 1051 else:
1050 1052 print 'I am going to upgrade your configuration in:'
1051 1053
1052 1054 print ipythondir
1053 1055
1054 1056 rcdirend = os.path.join('IPython','UserConfig')
1055 1057 cfg = lambda d: os.path.join(d,rcdirend)
1056 1058 try:
1057 1059 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1058 1060 except IOError:
1059 1061 warning = """
1060 1062 Installation error. IPython's directory was not found.
1061 1063
1062 1064 Check the following:
1063 1065
1064 1066 The ipython/IPython directory should be in a directory belonging to your
1065 1067 PYTHONPATH environment variable (that is, it should be in a directory
1066 1068 belonging to sys.path). You can copy it explicitly there or just link to it.
1067 1069
1068 1070 IPython will proceed with builtin defaults.
1069 1071 """
1070 1072 warn(warning)
1071 1073 wait()
1072 1074 return
1073 1075
1074 1076 if mode == 'install':
1075 1077 try:
1076 1078 shutil.copytree(rcdir,ipythondir)
1077 1079 os.chdir(ipythondir)
1078 1080 rc_files = glb("ipythonrc*")
1079 1081 for rc_file in rc_files:
1080 1082 os.rename(rc_file,rc_file+rc_suffix)
1081 1083 except:
1082 1084 warning = """
1083 1085
1084 1086 There was a problem with the installation:
1085 1087 %s
1086 1088 Try to correct it or contact the developers if you think it's a bug.
1087 1089 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1088 1090 warn(warning)
1089 1091 wait()
1090 1092 return
1091 1093
1092 1094 elif mode == 'upgrade':
1093 1095 try:
1094 1096 os.chdir(ipythondir)
1095 1097 except:
1096 1098 print """
1097 1099 Can not upgrade: changing to directory %s failed. Details:
1098 1100 %s
1099 1101 """ % (ipythondir,sys.exc_info()[1])
1100 1102 wait()
1101 1103 return
1102 1104 else:
1103 1105 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1104 1106 for new_full_path in sources:
1105 1107 new_filename = os.path.basename(new_full_path)
1106 1108 if new_filename.startswith('ipythonrc'):
1107 1109 new_filename = new_filename + rc_suffix
1108 1110 # The config directory should only contain files, skip any
1109 1111 # directories which may be there (like CVS)
1110 1112 if os.path.isdir(new_full_path):
1111 1113 continue
1112 1114 if os.path.exists(new_filename):
1113 1115 old_file = new_filename+'.old'
1114 1116 if os.path.exists(old_file):
1115 1117 os.remove(old_file)
1116 1118 os.rename(new_filename,old_file)
1117 1119 shutil.copy(new_full_path,new_filename)
1118 1120 else:
1119 1121 raise ValueError,'unrecognized mode for install:',`mode`
1120 1122
1121 1123 # Fix line-endings to those native to each platform in the config
1122 1124 # directory.
1123 1125 try:
1124 1126 os.chdir(ipythondir)
1125 1127 except:
1126 1128 print """
1127 1129 Problem: changing to directory %s failed.
1128 1130 Details:
1129 1131 %s
1130 1132
1131 1133 Some configuration files may have incorrect line endings. This should not
1132 1134 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1133 1135 wait()
1134 1136 else:
1135 1137 for fname in glb('ipythonrc*'):
1136 1138 try:
1137 1139 native_line_ends(fname,backup=0)
1138 1140 except IOError:
1139 1141 pass
1140 1142
1141 1143 if mode == 'install':
1142 1144 print """
1143 1145 Successful installation!
1144 1146
1145 1147 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1146 1148 IPython manual (there are both HTML and PDF versions supplied with the
1147 1149 distribution) to make sure that your system environment is properly configured
1148 1150 to take advantage of IPython's features.
1149 1151
1150 1152 Important note: the configuration system has changed! The old system is
1151 1153 still in place, but its setting may be partly overridden by the settings in
1152 1154 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1153 1155 if some of the new settings bother you.
1154 1156
1155 1157 """
1156 1158 else:
1157 1159 print """
1158 1160 Successful upgrade!
1159 1161
1160 1162 All files in your directory:
1161 1163 %(ipythondir)s
1162 1164 which would have been overwritten by the upgrade were backed up with a .old
1163 1165 extension. If you had made particular customizations in those files you may
1164 1166 want to merge them back into the new files.""" % locals()
1165 1167 wait()
1166 1168 os.chdir(cwd)
1167 1169 # end user_setup()
1168 1170
1169 1171 def atexit_operations(self):
1170 1172 """This will be executed at the time of exit.
1171 1173
1172 1174 Saving of persistent data should be performed here. """
1173 1175
1174 1176 #print '*** IPython exit cleanup ***' # dbg
1175 1177 # input history
1176 1178 self.savehist()
1177 1179
1178 1180 # Cleanup all tempfiles left around
1179 1181 for tfile in self.tempfiles:
1180 1182 try:
1181 1183 os.unlink(tfile)
1182 1184 except OSError:
1183 1185 pass
1184 1186
1185 1187 # save the "persistent data" catch-all dictionary
1186 1188 self.hooks.shutdown_hook()
1187 1189
1188 1190 def savehist(self):
1189 1191 """Save input history to a file (via readline library)."""
1190 1192 try:
1191 1193 self.readline.write_history_file(self.histfile)
1192 1194 except:
1193 1195 print 'Unable to save IPython command history to file: ' + \
1194 1196 `self.histfile`
1195 1197
1196 1198 def pre_readline(self):
1197 1199 """readline hook to be used at the start of each line.
1198 1200
1199 1201 Currently it handles auto-indent only."""
1200 1202
1201 1203 #debugx('self.indent_current_nsp','pre_readline:')
1202 1204 self.readline.insert_text(self.indent_current_str())
1203 1205
1204 1206 def init_readline(self):
1205 1207 """Command history completion/saving/reloading."""
1206 1208
1207 1209 import IPython.rlineimpl as readline
1208 1210 if not readline.have_readline:
1209 1211 self.has_readline = 0
1210 1212 self.readline = None
1211 1213 # no point in bugging windows users with this every time:
1212 1214 warn('Readline services not available on this platform.')
1213 1215 else:
1214 1216 sys.modules['readline'] = readline
1215 1217 import atexit
1216 1218 from IPython.completer import IPCompleter
1217 1219 self.Completer = IPCompleter(self,
1218 1220 self.user_ns,
1219 1221 self.user_global_ns,
1220 1222 self.rc.readline_omit__names,
1221 1223 self.alias_table)
1222 1224
1223 1225 # Platform-specific configuration
1224 1226 if os.name == 'nt':
1225 1227 self.readline_startup_hook = readline.set_pre_input_hook
1226 1228 else:
1227 1229 self.readline_startup_hook = readline.set_startup_hook
1228 1230
1229 1231 # Load user's initrc file (readline config)
1230 1232 inputrc_name = os.environ.get('INPUTRC')
1231 1233 if inputrc_name is None:
1232 1234 home_dir = get_home_dir()
1233 1235 if home_dir is not None:
1234 1236 inputrc_name = os.path.join(home_dir,'.inputrc')
1235 1237 if os.path.isfile(inputrc_name):
1236 1238 try:
1237 1239 readline.read_init_file(inputrc_name)
1238 1240 except:
1239 1241 warn('Problems reading readline initialization file <%s>'
1240 1242 % inputrc_name)
1241 1243
1242 1244 self.has_readline = 1
1243 1245 self.readline = readline
1244 1246 # save this in sys so embedded copies can restore it properly
1245 1247 sys.ipcompleter = self.Completer.complete
1246 1248 readline.set_completer(self.Completer.complete)
1247 1249
1248 1250 # Configure readline according to user's prefs
1249 1251 for rlcommand in self.rc.readline_parse_and_bind:
1250 1252 readline.parse_and_bind(rlcommand)
1251 1253
1252 1254 # remove some chars from the delimiters list
1253 1255 delims = readline.get_completer_delims()
1254 1256 delims = delims.translate(string._idmap,
1255 1257 self.rc.readline_remove_delims)
1256 1258 readline.set_completer_delims(delims)
1257 1259 # otherwise we end up with a monster history after a while:
1258 1260 readline.set_history_length(1000)
1259 1261 try:
1260 1262 #print '*** Reading readline history' # dbg
1261 1263 readline.read_history_file(self.histfile)
1262 1264 except IOError:
1263 1265 pass # It doesn't exist yet.
1264 1266
1265 1267 atexit.register(self.atexit_operations)
1266 1268 del atexit
1267 1269
1268 1270 # Configure auto-indent for all platforms
1269 1271 self.set_autoindent(self.rc.autoindent)
1270 1272
1271 1273 def ask_yes_no(self,prompt,default=True):
1272 1274 if self.rc.quiet:
1273 1275 return True
1274 1276 return ask_yes_no(prompt,default)
1275 1277
1276 1278 def _should_recompile(self,e):
1277 1279 """Utility routine for edit_syntax_error"""
1278 1280
1279 1281 if e.filename in ('<ipython console>','<input>','<string>',
1280 1282 '<console>','<BackgroundJob compilation>',
1281 1283 None):
1282 1284
1283 1285 return False
1284 1286 try:
1285 1287 if (self.rc.autoedit_syntax and
1286 1288 not self.ask_yes_no('Return to editor to correct syntax error? '
1287 1289 '[Y/n] ','y')):
1288 1290 return False
1289 1291 except EOFError:
1290 1292 return False
1291 1293
1292 1294 def int0(x):
1293 1295 try:
1294 1296 return int(x)
1295 1297 except TypeError:
1296 1298 return 0
1297 1299 # always pass integer line and offset values to editor hook
1298 1300 self.hooks.fix_error_editor(e.filename,
1299 1301 int0(e.lineno),int0(e.offset),e.msg)
1300 1302 return True
1301 1303
1302 1304 def edit_syntax_error(self):
1303 1305 """The bottom half of the syntax error handler called in the main loop.
1304 1306
1305 1307 Loop until syntax error is fixed or user cancels.
1306 1308 """
1307 1309
1308 1310 while self.SyntaxTB.last_syntax_error:
1309 1311 # copy and clear last_syntax_error
1310 1312 err = self.SyntaxTB.clear_err_state()
1311 1313 if not self._should_recompile(err):
1312 1314 return
1313 1315 try:
1314 1316 # may set last_syntax_error again if a SyntaxError is raised
1315 1317 self.safe_execfile(err.filename,self.user_ns)
1316 1318 except:
1317 1319 self.showtraceback()
1318 1320 else:
1319 1321 try:
1320 1322 f = file(err.filename)
1321 1323 try:
1322 1324 sys.displayhook(f.read())
1323 1325 finally:
1324 1326 f.close()
1325 1327 except:
1326 1328 self.showtraceback()
1327 1329
1328 1330 def showsyntaxerror(self, filename=None):
1329 1331 """Display the syntax error that just occurred.
1330 1332
1331 1333 This doesn't display a stack trace because there isn't one.
1332 1334
1333 1335 If a filename is given, it is stuffed in the exception instead
1334 1336 of what was there before (because Python's parser always uses
1335 1337 "<string>" when reading from a string).
1336 1338 """
1337 1339 etype, value, last_traceback = sys.exc_info()
1338 1340
1339 1341 # See note about these variables in showtraceback() below
1340 1342 sys.last_type = etype
1341 1343 sys.last_value = value
1342 1344 sys.last_traceback = last_traceback
1343 1345
1344 1346 if filename and etype is SyntaxError:
1345 1347 # Work hard to stuff the correct filename in the exception
1346 1348 try:
1347 1349 msg, (dummy_filename, lineno, offset, line) = value
1348 1350 except:
1349 1351 # Not the format we expect; leave it alone
1350 1352 pass
1351 1353 else:
1352 1354 # Stuff in the right filename
1353 1355 try:
1354 1356 # Assume SyntaxError is a class exception
1355 1357 value = SyntaxError(msg, (filename, lineno, offset, line))
1356 1358 except:
1357 1359 # If that failed, assume SyntaxError is a string
1358 1360 value = msg, (filename, lineno, offset, line)
1359 1361 self.SyntaxTB(etype,value,[])
1360 1362
1361 1363 def debugger(self):
1362 1364 """Call the pdb debugger."""
1363 1365
1364 1366 if not self.rc.pdb:
1365 1367 return
1366 1368 pdb.pm()
1367 1369
1368 1370 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1369 1371 """Display the exception that just occurred.
1370 1372
1371 1373 If nothing is known about the exception, this is the method which
1372 1374 should be used throughout the code for presenting user tracebacks,
1373 1375 rather than directly invoking the InteractiveTB object.
1374 1376
1375 1377 A specific showsyntaxerror() also exists, but this method can take
1376 1378 care of calling it if needed, so unless you are explicitly catching a
1377 1379 SyntaxError exception, don't try to analyze the stack manually and
1378 1380 simply call this method."""
1379 1381
1380 1382 # Though this won't be called by syntax errors in the input line,
1381 1383 # there may be SyntaxError cases whith imported code.
1382 1384 if exc_tuple is None:
1383 1385 etype, value, tb = sys.exc_info()
1384 1386 else:
1385 1387 etype, value, tb = exc_tuple
1386 1388 if etype is SyntaxError:
1387 1389 self.showsyntaxerror(filename)
1388 1390 else:
1389 1391 # WARNING: these variables are somewhat deprecated and not
1390 1392 # necessarily safe to use in a threaded environment, but tools
1391 1393 # like pdb depend on their existence, so let's set them. If we
1392 1394 # find problems in the field, we'll need to revisit their use.
1393 1395 sys.last_type = etype
1394 1396 sys.last_value = value
1395 1397 sys.last_traceback = tb
1396 1398
1397 1399 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1398 1400 if self.InteractiveTB.call_pdb and self.has_readline:
1399 1401 # pdb mucks up readline, fix it back
1400 1402 self.readline.set_completer(self.Completer.complete)
1401 1403
1402 1404 def mainloop(self,banner=None):
1403 1405 """Creates the local namespace and starts the mainloop.
1404 1406
1405 1407 If an optional banner argument is given, it will override the
1406 1408 internally created default banner."""
1407 1409
1408 1410 if self.rc.c: # Emulate Python's -c option
1409 1411 self.exec_init_cmd()
1410 1412 if banner is None:
1411 1413 if not self.rc.banner:
1412 1414 banner = ''
1413 1415 # banner is string? Use it directly!
1414 1416 elif isinstance(self.rc.banner,basestring):
1415 1417 banner = self.rc.banner
1416 1418 else:
1417 1419 banner = self.BANNER+self.banner2
1418 1420
1419 1421 self.interact(banner)
1420 1422
1421 1423 def exec_init_cmd(self):
1422 1424 """Execute a command given at the command line.
1423 1425
1424 1426 This emulates Python's -c option."""
1425 1427
1426 1428 #sys.argv = ['-c']
1427 1429 self.push(self.rc.c)
1428 1430
1429 1431 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1430 1432 """Embeds IPython into a running python program.
1431 1433
1432 1434 Input:
1433 1435
1434 1436 - header: An optional header message can be specified.
1435 1437
1436 1438 - local_ns, global_ns: working namespaces. If given as None, the
1437 1439 IPython-initialized one is updated with __main__.__dict__, so that
1438 1440 program variables become visible but user-specific configuration
1439 1441 remains possible.
1440 1442
1441 1443 - stack_depth: specifies how many levels in the stack to go to
1442 1444 looking for namespaces (when local_ns and global_ns are None). This
1443 1445 allows an intermediate caller to make sure that this function gets
1444 1446 the namespace from the intended level in the stack. By default (0)
1445 1447 it will get its locals and globals from the immediate caller.
1446 1448
1447 1449 Warning: it's possible to use this in a program which is being run by
1448 1450 IPython itself (via %run), but some funny things will happen (a few
1449 1451 globals get overwritten). In the future this will be cleaned up, as
1450 1452 there is no fundamental reason why it can't work perfectly."""
1451 1453
1452 1454 # Get locals and globals from caller
1453 1455 if local_ns is None or global_ns is None:
1454 1456 call_frame = sys._getframe(stack_depth).f_back
1455 1457
1456 1458 if local_ns is None:
1457 1459 local_ns = call_frame.f_locals
1458 1460 if global_ns is None:
1459 1461 global_ns = call_frame.f_globals
1460 1462
1461 1463 # Update namespaces and fire up interpreter
1462 1464
1463 1465 # The global one is easy, we can just throw it in
1464 1466 self.user_global_ns = global_ns
1465 1467
1466 1468 # but the user/local one is tricky: ipython needs it to store internal
1467 1469 # data, but we also need the locals. We'll copy locals in the user
1468 1470 # one, but will track what got copied so we can delete them at exit.
1469 1471 # This is so that a later embedded call doesn't see locals from a
1470 1472 # previous call (which most likely existed in a separate scope).
1471 1473 local_varnames = local_ns.keys()
1472 1474 self.user_ns.update(local_ns)
1473 1475
1474 1476 # Patch for global embedding to make sure that things don't overwrite
1475 1477 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1476 1478 # FIXME. Test this a bit more carefully (the if.. is new)
1477 1479 if local_ns is None and global_ns is None:
1478 1480 self.user_global_ns.update(__main__.__dict__)
1479 1481
1480 1482 # make sure the tab-completer has the correct frame information, so it
1481 1483 # actually completes using the frame's locals/globals
1482 1484 self.set_completer_frame()
1483 1485
1484 1486 # before activating the interactive mode, we need to make sure that
1485 1487 # all names in the builtin namespace needed by ipython point to
1486 1488 # ourselves, and not to other instances.
1487 1489 self.add_builtins()
1488 1490
1489 1491 self.interact(header)
1490 1492
1491 1493 # now, purge out the user namespace from anything we might have added
1492 1494 # from the caller's local namespace
1493 1495 delvar = self.user_ns.pop
1494 1496 for var in local_varnames:
1495 1497 delvar(var,None)
1496 1498 # and clean builtins we may have overridden
1497 1499 self.clean_builtins()
1498 1500
1499 1501 def interact(self, banner=None):
1500 1502 """Closely emulate the interactive Python console.
1501 1503
1502 1504 The optional banner argument specify the banner to print
1503 1505 before the first interaction; by default it prints a banner
1504 1506 similar to the one printed by the real Python interpreter,
1505 1507 followed by the current class name in parentheses (so as not
1506 1508 to confuse this with the real interpreter -- since it's so
1507 1509 close!).
1508 1510
1509 1511 """
1510 1512
1511 1513 if self.exit_now:
1512 1514 # batch run -> do not interact
1513 1515 return
1514 1516 cprt = 'Type "copyright", "credits" or "license" for more information.'
1515 1517 if banner is None:
1516 1518 self.write("Python %s on %s\n%s\n(%s)\n" %
1517 1519 (sys.version, sys.platform, cprt,
1518 1520 self.__class__.__name__))
1519 1521 else:
1520 1522 self.write(banner)
1521 1523
1522 1524 more = 0
1523 1525
1524 1526 # Mark activity in the builtins
1525 1527 __builtin__.__dict__['__IPYTHON__active'] += 1
1526 1528
1527 1529 # exit_now is set by a call to %Exit or %Quit
1528 1530 while not self.exit_now:
1529 1531 if more:
1530 1532 prompt = self.hooks.generate_prompt(True)
1531 1533 if self.autoindent:
1532 1534 self.readline_startup_hook(self.pre_readline)
1533 1535 else:
1534 1536 prompt = self.hooks.generate_prompt(False)
1535 1537 try:
1536 1538 line = self.raw_input(prompt,more)
1537 1539 if self.exit_now:
1538 1540 # quick exit on sys.std[in|out] close
1539 1541 break
1540 1542 if self.autoindent:
1541 1543 self.readline_startup_hook(None)
1542 1544 except KeyboardInterrupt:
1543 1545 self.write('\nKeyboardInterrupt\n')
1544 1546 self.resetbuffer()
1545 1547 # keep cache in sync with the prompt counter:
1546 1548 self.outputcache.prompt_count -= 1
1547 1549
1548 1550 if self.autoindent:
1549 1551 self.indent_current_nsp = 0
1550 1552 more = 0
1551 1553 except EOFError:
1552 1554 if self.autoindent:
1553 1555 self.readline_startup_hook(None)
1554 1556 self.write('\n')
1555 1557 self.exit()
1556 1558 except bdb.BdbQuit:
1557 1559 warn('The Python debugger has exited with a BdbQuit exception.\n'
1558 1560 'Because of how pdb handles the stack, it is impossible\n'
1559 1561 'for IPython to properly format this particular exception.\n'
1560 1562 'IPython will resume normal operation.')
1561 1563 except:
1562 1564 # exceptions here are VERY RARE, but they can be triggered
1563 1565 # asynchronously by signal handlers, for example.
1564 1566 self.showtraceback()
1565 1567 else:
1566 1568 more = self.push(line)
1567 1569 if (self.SyntaxTB.last_syntax_error and
1568 1570 self.rc.autoedit_syntax):
1569 1571 self.edit_syntax_error()
1570 1572
1571 1573 # We are off again...
1572 1574 __builtin__.__dict__['__IPYTHON__active'] -= 1
1573 1575
1574 1576 def excepthook(self, etype, value, tb):
1575 1577 """One more defense for GUI apps that call sys.excepthook.
1576 1578
1577 1579 GUI frameworks like wxPython trap exceptions and call
1578 1580 sys.excepthook themselves. I guess this is a feature that
1579 1581 enables them to keep running after exceptions that would
1580 1582 otherwise kill their mainloop. This is a bother for IPython
1581 1583 which excepts to catch all of the program exceptions with a try:
1582 1584 except: statement.
1583 1585
1584 1586 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1585 1587 any app directly invokes sys.excepthook, it will look to the user like
1586 1588 IPython crashed. In order to work around this, we can disable the
1587 1589 CrashHandler and replace it with this excepthook instead, which prints a
1588 1590 regular traceback using our InteractiveTB. In this fashion, apps which
1589 1591 call sys.excepthook will generate a regular-looking exception from
1590 1592 IPython, and the CrashHandler will only be triggered by real IPython
1591 1593 crashes.
1592 1594
1593 1595 This hook should be used sparingly, only in places which are not likely
1594 1596 to be true IPython errors.
1595 1597 """
1596 1598 self.showtraceback((etype,value,tb),tb_offset=0)
1597 1599
1598 1600 def expand_aliases(self,fn,rest):
1599 1601 """ Expand multiple levels of aliases:
1600 1602
1601 1603 if:
1602 1604
1603 1605 alias foo bar /tmp
1604 1606 alias baz foo
1605 1607
1606 1608 then:
1607 1609
1608 1610 baz huhhahhei -> bar /tmp huhhahhei
1609 1611
1610 1612 """
1611 1613 line = fn + " " + rest
1612 1614
1613 1615 done = Set()
1614 1616 while 1:
1615 1617 pre,fn,rest = self.split_user_input(line)
1616 1618 if fn in self.alias_table:
1617 1619 if fn in done:
1618 1620 warn("Cyclic alias definition, repeated '%s'" % fn)
1619 1621 return ""
1620 1622 done.add(fn)
1621 1623
1622 1624 l2 = self.transform_alias(fn,rest)
1623 1625 # dir -> dir
1624 1626 if l2 == line:
1625 1627 break
1626 1628 # ls -> ls -F should not recurse forever
1627 1629 if l2.split(None,1)[0] == line.split(None,1)[0]:
1628 1630 line = l2
1629 1631 break
1630 1632
1631 1633 line=l2
1632 1634
1633 1635
1634 1636 # print "al expand to",line #dbg
1635 1637 else:
1636 1638 break
1637 1639
1638 1640 return line
1639 1641
1640 1642 def transform_alias(self, alias,rest=''):
1641 1643 """ Transform alias to system command string.
1642 1644 """
1643 1645 nargs,cmd = self.alias_table[alias]
1644 1646 if ' ' in cmd and os.path.isfile(cmd):
1645 1647 cmd = '"%s"' % cmd
1646 1648
1647 1649 # Expand the %l special to be the user's input line
1648 1650 if cmd.find('%l') >= 0:
1649 1651 cmd = cmd.replace('%l',rest)
1650 1652 rest = ''
1651 1653 if nargs==0:
1652 1654 # Simple, argument-less aliases
1653 1655 cmd = '%s %s' % (cmd,rest)
1654 1656 else:
1655 1657 # Handle aliases with positional arguments
1656 1658 args = rest.split(None,nargs)
1657 1659 if len(args)< nargs:
1658 1660 error('Alias <%s> requires %s arguments, %s given.' %
1659 1661 (alias,nargs,len(args)))
1660 1662 return None
1661 1663 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1662 1664 # Now call the macro, evaluating in the user's namespace
1663 1665 #print 'new command: <%r>' % cmd # dbg
1664 1666 return cmd
1665 1667
1666 1668 def call_alias(self,alias,rest=''):
1667 1669 """Call an alias given its name and the rest of the line.
1668 1670
1669 1671 This is only used to provide backwards compatibility for users of
1670 1672 ipalias(), use of which is not recommended for anymore."""
1671 1673
1672 1674 # Now call the macro, evaluating in the user's namespace
1673 1675 cmd = self.transform_alias(alias, rest)
1674 1676 try:
1675 1677 self.system(cmd)
1676 1678 except:
1677 1679 self.showtraceback()
1678 1680
1679 1681 def indent_current_str(self):
1680 1682 """return the current level of indentation as a string"""
1681 1683 return self.indent_current_nsp * ' '
1682 1684
1683 1685 def autoindent_update(self,line):
1684 1686 """Keep track of the indent level."""
1685 1687
1686 1688 #debugx('line')
1687 1689 #debugx('self.indent_current_nsp')
1688 1690 if self.autoindent:
1689 1691 if line:
1690 1692 inisp = num_ini_spaces(line)
1691 1693 if inisp < self.indent_current_nsp:
1692 1694 self.indent_current_nsp = inisp
1693 1695
1694 1696 if line[-1] == ':':
1695 1697 self.indent_current_nsp += 4
1696 1698 elif dedent_re.match(line):
1697 1699 self.indent_current_nsp -= 4
1698 1700 else:
1699 1701 self.indent_current_nsp = 0
1700 1702
1701 1703 def runlines(self,lines):
1702 1704 """Run a string of one or more lines of source.
1703 1705
1704 1706 This method is capable of running a string containing multiple source
1705 1707 lines, as if they had been entered at the IPython prompt. Since it
1706 1708 exposes IPython's processing machinery, the given strings can contain
1707 1709 magic calls (%magic), special shell access (!cmd), etc."""
1708 1710
1709 1711 # We must start with a clean buffer, in case this is run from an
1710 1712 # interactive IPython session (via a magic, for example).
1711 1713 self.resetbuffer()
1712 1714 lines = lines.split('\n')
1713 1715 more = 0
1714 1716 for line in lines:
1715 1717 # skip blank lines so we don't mess up the prompt counter, but do
1716 1718 # NOT skip even a blank line if we are in a code block (more is
1717 1719 # true)
1718 1720 if line or more:
1719 1721 more = self.push(self.prefilter(line,more))
1720 1722 # IPython's runsource returns None if there was an error
1721 1723 # compiling the code. This allows us to stop processing right
1722 1724 # away, so the user gets the error message at the right place.
1723 1725 if more is None:
1724 1726 break
1725 1727 # final newline in case the input didn't have it, so that the code
1726 1728 # actually does get executed
1727 1729 if more:
1728 1730 self.push('\n')
1729 1731
1730 1732 def runsource(self, source, filename='<input>', symbol='single'):
1731 1733 """Compile and run some source in the interpreter.
1732 1734
1733 1735 Arguments are as for compile_command().
1734 1736
1735 1737 One several things can happen:
1736 1738
1737 1739 1) The input is incorrect; compile_command() raised an
1738 1740 exception (SyntaxError or OverflowError). A syntax traceback
1739 1741 will be printed by calling the showsyntaxerror() method.
1740 1742
1741 1743 2) The input is incomplete, and more input is required;
1742 1744 compile_command() returned None. Nothing happens.
1743 1745
1744 1746 3) The input is complete; compile_command() returned a code
1745 1747 object. The code is executed by calling self.runcode() (which
1746 1748 also handles run-time exceptions, except for SystemExit).
1747 1749
1748 1750 The return value is:
1749 1751
1750 1752 - True in case 2
1751 1753
1752 1754 - False in the other cases, unless an exception is raised, where
1753 1755 None is returned instead. This can be used by external callers to
1754 1756 know whether to continue feeding input or not.
1755 1757
1756 1758 The return value can be used to decide whether to use sys.ps1 or
1757 1759 sys.ps2 to prompt the next line."""
1758 1760
1759 1761 try:
1760 1762 code = self.compile(source,filename,symbol)
1761 1763 except (OverflowError, SyntaxError, ValueError):
1762 1764 # Case 1
1763 1765 self.showsyntaxerror(filename)
1764 1766 return None
1765 1767
1766 1768 if code is None:
1767 1769 # Case 2
1768 1770 return True
1769 1771
1770 1772 # Case 3
1771 1773 # We store the code object so that threaded shells and
1772 1774 # custom exception handlers can access all this info if needed.
1773 1775 # The source corresponding to this can be obtained from the
1774 1776 # buffer attribute as '\n'.join(self.buffer).
1775 1777 self.code_to_run = code
1776 1778 # now actually execute the code object
1777 1779 if self.runcode(code) == 0:
1778 1780 return False
1779 1781 else:
1780 1782 return None
1781 1783
1782 1784 def runcode(self,code_obj):
1783 1785 """Execute a code object.
1784 1786
1785 1787 When an exception occurs, self.showtraceback() is called to display a
1786 1788 traceback.
1787 1789
1788 1790 Return value: a flag indicating whether the code to be run completed
1789 1791 successfully:
1790 1792
1791 1793 - 0: successful execution.
1792 1794 - 1: an error occurred.
1793 1795 """
1794 1796
1795 1797 # Set our own excepthook in case the user code tries to call it
1796 1798 # directly, so that the IPython crash handler doesn't get triggered
1797 1799 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1798 1800
1799 1801 # we save the original sys.excepthook in the instance, in case config
1800 1802 # code (such as magics) needs access to it.
1801 1803 self.sys_excepthook = old_excepthook
1802 1804 outflag = 1 # happens in more places, so it's easier as default
1803 1805 try:
1804 1806 try:
1805 1807 # Embedded instances require separate global/local namespaces
1806 1808 # so they can see both the surrounding (local) namespace and
1807 1809 # the module-level globals when called inside another function.
1808 1810 if self.embedded:
1809 1811 exec code_obj in self.user_global_ns, self.user_ns
1810 1812 # Normal (non-embedded) instances should only have a single
1811 1813 # namespace for user code execution, otherwise functions won't
1812 1814 # see interactive top-level globals.
1813 1815 else:
1814 1816 exec code_obj in self.user_ns
1815 1817 finally:
1816 1818 # Reset our crash handler in place
1817 1819 sys.excepthook = old_excepthook
1818 1820 except SystemExit:
1819 1821 self.resetbuffer()
1820 1822 self.showtraceback()
1821 1823 warn("Type %exit or %quit to exit IPython "
1822 1824 "(%Exit or %Quit do so unconditionally).",level=1)
1823 1825 except self.custom_exceptions:
1824 1826 etype,value,tb = sys.exc_info()
1825 1827 self.CustomTB(etype,value,tb)
1826 1828 except:
1827 1829 self.showtraceback()
1828 1830 else:
1829 1831 outflag = 0
1830 1832 if softspace(sys.stdout, 0):
1831 1833 print
1832 1834 # Flush out code object which has been run (and source)
1833 1835 self.code_to_run = None
1834 1836 return outflag
1835 1837
1836 1838 def push(self, line):
1837 1839 """Push a line to the interpreter.
1838 1840
1839 1841 The line should not have a trailing newline; it may have
1840 1842 internal newlines. The line is appended to a buffer and the
1841 1843 interpreter's runsource() method is called with the
1842 1844 concatenated contents of the buffer as source. If this
1843 1845 indicates that the command was executed or invalid, the buffer
1844 1846 is reset; otherwise, the command is incomplete, and the buffer
1845 1847 is left as it was after the line was appended. The return
1846 1848 value is 1 if more input is required, 0 if the line was dealt
1847 1849 with in some way (this is the same as runsource()).
1848 1850 """
1849 1851
1850 1852 # autoindent management should be done here, and not in the
1851 1853 # interactive loop, since that one is only seen by keyboard input. We
1852 1854 # need this done correctly even for code run via runlines (which uses
1853 1855 # push).
1854 1856
1855 1857 #print 'push line: <%s>' % line # dbg
1856 1858 for subline in line.splitlines():
1857 1859 self.autoindent_update(subline)
1858 1860 self.buffer.append(line)
1859 1861 more = self.runsource('\n'.join(self.buffer), self.filename)
1860 1862 if not more:
1861 1863 self.resetbuffer()
1862 1864 return more
1863 1865
1864 1866 def resetbuffer(self):
1865 1867 """Reset the input buffer."""
1866 1868 self.buffer[:] = []
1867 1869
1868 1870 def raw_input(self,prompt='',continue_prompt=False):
1869 1871 """Write a prompt and read a line.
1870 1872
1871 1873 The returned line does not include the trailing newline.
1872 1874 When the user enters the EOF key sequence, EOFError is raised.
1873 1875
1874 1876 Optional inputs:
1875 1877
1876 1878 - prompt(''): a string to be printed to prompt the user.
1877 1879
1878 1880 - continue_prompt(False): whether this line is the first one or a
1879 1881 continuation in a sequence of inputs.
1880 1882 """
1881 1883
1882 1884 try:
1883 1885 line = raw_input_original(prompt)
1884 1886 except ValueError:
1885 1887 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1886 1888 self.exit_now = True
1887 1889 return ""
1888 1890
1889 1891
1890 1892 # Try to be reasonably smart about not re-indenting pasted input more
1891 1893 # than necessary. We do this by trimming out the auto-indent initial
1892 1894 # spaces, if the user's actual input started itself with whitespace.
1893 1895 #debugx('self.buffer[-1]')
1894 1896
1895 1897 if self.autoindent:
1896 1898 if num_ini_spaces(line) > self.indent_current_nsp:
1897 1899 line = line[self.indent_current_nsp:]
1898 1900 self.indent_current_nsp = 0
1899 1901
1900 1902 # store the unfiltered input before the user has any chance to modify
1901 1903 # it.
1902 1904 if line.strip():
1903 1905 if continue_prompt:
1904 1906 self.input_hist_raw[-1] += '%s\n' % line
1905 1907 if self.has_readline: # and some config option is set?
1906 1908 try:
1907 1909 histlen = self.readline.get_current_history_length()
1908 1910 newhist = self.input_hist_raw[-1].rstrip()
1909 1911 self.readline.remove_history_item(histlen-1)
1910 1912 self.readline.replace_history_item(histlen-2,newhist)
1911 1913 except AttributeError:
1912 1914 pass # re{move,place}_history_item are new in 2.4.
1913 1915 else:
1914 1916 self.input_hist_raw.append('%s\n' % line)
1915 1917
1916 1918 try:
1917 1919 lineout = self.prefilter(line,continue_prompt)
1918 1920 except:
1919 1921 # blanket except, in case a user-defined prefilter crashes, so it
1920 1922 # can't take all of ipython with it.
1921 1923 self.showtraceback()
1922 1924 return ''
1923 1925 else:
1924 1926 return lineout
1925 1927
1926 1928 def split_user_input(self,line):
1927 1929 """Split user input into pre-char, function part and rest."""
1928 1930
1929 1931 lsplit = self.line_split.match(line)
1930 1932 if lsplit is None: # no regexp match returns None
1931 1933 try:
1932 1934 iFun,theRest = line.split(None,1)
1933 1935 except ValueError:
1934 1936 iFun,theRest = line,''
1935 1937 pre = re.match('^(\s*)(.*)',line).groups()[0]
1936 1938 else:
1937 1939 pre,iFun,theRest = lsplit.groups()
1938 1940
1939 1941 #print 'line:<%s>' % line # dbg
1940 1942 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1941 1943 return pre,iFun.strip(),theRest
1942 1944
1943 1945 def _prefilter(self, line, continue_prompt):
1944 1946 """Calls different preprocessors, depending on the form of line."""
1945 1947
1946 1948 # All handlers *must* return a value, even if it's blank ('').
1947 1949
1948 1950 # Lines are NOT logged here. Handlers should process the line as
1949 1951 # needed, update the cache AND log it (so that the input cache array
1950 1952 # stays synced).
1951 1953
1952 1954 # This function is _very_ delicate, and since it's also the one which
1953 1955 # determines IPython's response to user input, it must be as efficient
1954 1956 # as possible. For this reason it has _many_ returns in it, trying
1955 1957 # always to exit as quickly as it can figure out what it needs to do.
1956 1958
1957 1959 # This function is the main responsible for maintaining IPython's
1958 1960 # behavior respectful of Python's semantics. So be _very_ careful if
1959 1961 # making changes to anything here.
1960 1962
1961 1963 #.....................................................................
1962 1964 # Code begins
1963 1965
1964 1966 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1965 1967
1966 1968 # save the line away in case we crash, so the post-mortem handler can
1967 1969 # record it
1968 1970 self._last_input_line = line
1969 1971
1970 1972 #print '***line: <%s>' % line # dbg
1971 1973
1972 1974 # the input history needs to track even empty lines
1973 1975 stripped = line.strip()
1974 1976
1975 1977 if not stripped:
1976 1978 if not continue_prompt:
1977 1979 self.outputcache.prompt_count -= 1
1978 1980 return self.handle_normal(line,continue_prompt)
1979 1981 #return self.handle_normal('',continue_prompt)
1980 1982
1981 1983 # print '***cont',continue_prompt # dbg
1982 1984 # special handlers are only allowed for single line statements
1983 1985 if continue_prompt and not self.rc.multi_line_specials:
1984 1986 return self.handle_normal(line,continue_prompt)
1985 1987
1986 1988
1987 1989 # For the rest, we need the structure of the input
1988 1990 pre,iFun,theRest = self.split_user_input(line)
1989 1991
1990 1992 # See whether any pre-existing handler can take care of it
1991 1993
1992 1994 rewritten = self.hooks.input_prefilter(stripped)
1993 1995 if rewritten != stripped: # ok, some prefilter did something
1994 1996 rewritten = pre + rewritten # add indentation
1995 1997 return self.handle_normal(rewritten)
1996 1998
1997 1999 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1998 2000
1999 2001 # First check for explicit escapes in the last/first character
2000 2002 handler = None
2001 2003 if line[-1] == self.ESC_HELP:
2002 2004 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2003 2005 if handler is None:
2004 2006 # look at the first character of iFun, NOT of line, so we skip
2005 2007 # leading whitespace in multiline input
2006 2008 handler = self.esc_handlers.get(iFun[0:1])
2007 2009 if handler is not None:
2008 2010 return handler(line,continue_prompt,pre,iFun,theRest)
2009 2011 # Emacs ipython-mode tags certain input lines
2010 2012 if line.endswith('# PYTHON-MODE'):
2011 2013 return self.handle_emacs(line,continue_prompt)
2012 2014
2013 2015 # Next, check if we can automatically execute this thing
2014 2016
2015 2017 # Allow ! in multi-line statements if multi_line_specials is on:
2016 2018 if continue_prompt and self.rc.multi_line_specials and \
2017 2019 iFun.startswith(self.ESC_SHELL):
2018 2020 return self.handle_shell_escape(line,continue_prompt,
2019 2021 pre=pre,iFun=iFun,
2020 2022 theRest=theRest)
2021 2023
2022 2024 # Let's try to find if the input line is a magic fn
2023 2025 oinfo = None
2024 2026 if hasattr(self,'magic_'+iFun):
2025 2027 # WARNING: _ofind uses getattr(), so it can consume generators and
2026 2028 # cause other side effects.
2027 2029 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2028 2030 if oinfo['ismagic']:
2029 2031 # Be careful not to call magics when a variable assignment is
2030 2032 # being made (ls='hi', for example)
2031 2033 if self.rc.automagic and \
2032 2034 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2033 2035 (self.rc.multi_line_specials or not continue_prompt):
2034 2036 return self.handle_magic(line,continue_prompt,
2035 2037 pre,iFun,theRest)
2036 2038 else:
2037 2039 return self.handle_normal(line,continue_prompt)
2038 2040
2039 2041 # If the rest of the line begins with an (in)equality, assginment or
2040 2042 # function call, we should not call _ofind but simply execute it.
2041 2043 # This avoids spurious geattr() accesses on objects upon assignment.
2042 2044 #
2043 2045 # It also allows users to assign to either alias or magic names true
2044 2046 # python variables (the magic/alias systems always take second seat to
2045 2047 # true python code).
2046 2048 if theRest and theRest[0] in '!=()':
2047 2049 return self.handle_normal(line,continue_prompt)
2048 2050
2049 2051 if oinfo is None:
2050 2052 # let's try to ensure that _oinfo is ONLY called when autocall is
2051 2053 # on. Since it has inevitable potential side effects, at least
2052 2054 # having autocall off should be a guarantee to the user that no
2053 2055 # weird things will happen.
2054 2056
2055 2057 if self.rc.autocall:
2056 2058 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2057 2059 else:
2058 2060 # in this case, all that's left is either an alias or
2059 2061 # processing the line normally.
2060 2062 if iFun in self.alias_table:
2061 2063 # if autocall is off, by not running _ofind we won't know
2062 2064 # whether the given name may also exist in one of the
2063 2065 # user's namespace. At this point, it's best to do a
2064 2066 # quick check just to be sure that we don't let aliases
2065 2067 # shadow variables.
2066 2068 head = iFun.split('.',1)[0]
2067 2069 if head in self.user_ns or head in self.internal_ns \
2068 2070 or head in __builtin__.__dict__:
2069 2071 return self.handle_normal(line,continue_prompt)
2070 2072 else:
2071 2073 return self.handle_alias(line,continue_prompt,
2072 2074 pre,iFun,theRest)
2073 2075
2074 2076 else:
2075 2077 return self.handle_normal(line,continue_prompt)
2076 2078
2077 2079 if not oinfo['found']:
2078 2080 return self.handle_normal(line,continue_prompt)
2079 2081 else:
2080 2082 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2081 2083 if oinfo['isalias']:
2082 2084 return self.handle_alias(line,continue_prompt,
2083 2085 pre,iFun,theRest)
2084 2086
2085 2087 if (self.rc.autocall
2086 2088 and
2087 2089 (
2088 2090 #only consider exclusion re if not "," or ";" autoquoting
2089 2091 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2090 2092 or pre == self.ESC_PAREN) or
2091 2093 (not self.re_exclude_auto.match(theRest)))
2092 2094 and
2093 2095 self.re_fun_name.match(iFun) and
2094 2096 callable(oinfo['obj'])) :
2095 2097 #print 'going auto' # dbg
2096 2098 return self.handle_auto(line,continue_prompt,
2097 2099 pre,iFun,theRest,oinfo['obj'])
2098 2100 else:
2099 2101 #print 'was callable?', callable(oinfo['obj']) # dbg
2100 2102 return self.handle_normal(line,continue_prompt)
2101 2103
2102 2104 # If we get here, we have a normal Python line. Log and return.
2103 2105 return self.handle_normal(line,continue_prompt)
2104 2106
2105 2107 def _prefilter_dumb(self, line, continue_prompt):
2106 2108 """simple prefilter function, for debugging"""
2107 2109 return self.handle_normal(line,continue_prompt)
2108 2110
2109 2111
2110 2112 def multiline_prefilter(self, line, continue_prompt):
2111 2113 """ Run _prefilter for each line of input
2112 2114
2113 2115 Covers cases where there are multiple lines in the user entry,
2114 2116 which is the case when the user goes back to a multiline history
2115 2117 entry and presses enter.
2116 2118
2117 2119 """
2118 2120 out = []
2119 2121 for l in line.rstrip('\n').split('\n'):
2120 2122 out.append(self._prefilter(l, continue_prompt))
2121 2123 return '\n'.join(out)
2122 2124
2123 2125 # Set the default prefilter() function (this can be user-overridden)
2124 2126 prefilter = multiline_prefilter
2125 2127
2126 2128 def handle_normal(self,line,continue_prompt=None,
2127 2129 pre=None,iFun=None,theRest=None):
2128 2130 """Handle normal input lines. Use as a template for handlers."""
2129 2131
2130 2132 # With autoindent on, we need some way to exit the input loop, and I
2131 2133 # don't want to force the user to have to backspace all the way to
2132 2134 # clear the line. The rule will be in this case, that either two
2133 2135 # lines of pure whitespace in a row, or a line of pure whitespace but
2134 2136 # of a size different to the indent level, will exit the input loop.
2135 2137
2136 2138 if (continue_prompt and self.autoindent and line.isspace() and
2137 2139 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2138 2140 (self.buffer[-1]).isspace() )):
2139 2141 line = ''
2140 2142
2141 2143 self.log(line,line,continue_prompt)
2142 2144 return line
2143 2145
2144 2146 def handle_alias(self,line,continue_prompt=None,
2145 2147 pre=None,iFun=None,theRest=None):
2146 2148 """Handle alias input lines. """
2147 2149
2148 2150 # pre is needed, because it carries the leading whitespace. Otherwise
2149 2151 # aliases won't work in indented sections.
2150 2152 transformed = self.expand_aliases(iFun, theRest)
2151 2153 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2152 2154 self.log(line,line_out,continue_prompt)
2153 2155 #print 'line out:',line_out # dbg
2154 2156 return line_out
2155 2157
2156 2158 def handle_shell_escape(self, line, continue_prompt=None,
2157 2159 pre=None,iFun=None,theRest=None):
2158 2160 """Execute the line in a shell, empty return value"""
2159 2161
2160 2162 #print 'line in :', `line` # dbg
2161 2163 # Example of a special handler. Others follow a similar pattern.
2162 2164 if line.lstrip().startswith('!!'):
2163 2165 # rewrite iFun/theRest to properly hold the call to %sx and
2164 2166 # the actual command to be executed, so handle_magic can work
2165 2167 # correctly
2166 2168 theRest = '%s %s' % (iFun[2:],theRest)
2167 2169 iFun = 'sx'
2168 2170 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2169 2171 line.lstrip()[2:]),
2170 2172 continue_prompt,pre,iFun,theRest)
2171 2173 else:
2172 2174 cmd=line.lstrip().lstrip('!')
2173 2175 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2174 2176 # update cache/log and return
2175 2177 self.log(line,line_out,continue_prompt)
2176 2178 return line_out
2177 2179
2178 2180 def handle_magic(self, line, continue_prompt=None,
2179 2181 pre=None,iFun=None,theRest=None):
2180 2182 """Execute magic functions."""
2181 2183
2182 2184
2183 2185 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2184 2186 self.log(line,cmd,continue_prompt)
2185 2187 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2186 2188 return cmd
2187 2189
2188 2190 def handle_auto(self, line, continue_prompt=None,
2189 2191 pre=None,iFun=None,theRest=None,obj=None):
2190 2192 """Hande lines which can be auto-executed, quoting if requested."""
2191 2193
2192 2194 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2193 2195
2194 2196 # This should only be active for single-line input!
2195 2197 if continue_prompt:
2196 2198 self.log(line,line,continue_prompt)
2197 2199 return line
2198 2200
2199 2201 auto_rewrite = True
2200 2202
2201 2203 if pre == self.ESC_QUOTE:
2202 2204 # Auto-quote splitting on whitespace
2203 2205 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2204 2206 elif pre == self.ESC_QUOTE2:
2205 2207 # Auto-quote whole string
2206 2208 newcmd = '%s("%s")' % (iFun,theRest)
2207 2209 elif pre == self.ESC_PAREN:
2208 2210 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2209 2211 else:
2210 2212 # Auto-paren.
2211 2213 # We only apply it to argument-less calls if the autocall
2212 2214 # parameter is set to 2. We only need to check that autocall is <
2213 2215 # 2, since this function isn't called unless it's at least 1.
2214 2216 if not theRest and (self.rc.autocall < 2):
2215 2217 newcmd = '%s %s' % (iFun,theRest)
2216 2218 auto_rewrite = False
2217 2219 else:
2218 2220 if theRest.startswith('['):
2219 2221 if hasattr(obj,'__getitem__'):
2220 2222 # Don't autocall in this case: item access for an object
2221 2223 # which is BOTH callable and implements __getitem__.
2222 2224 newcmd = '%s %s' % (iFun,theRest)
2223 2225 auto_rewrite = False
2224 2226 else:
2225 2227 # if the object doesn't support [] access, go ahead and
2226 2228 # autocall
2227 2229 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2228 2230 elif theRest.endswith(';'):
2229 2231 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2230 2232 else:
2231 2233 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2232 2234
2233 2235 if auto_rewrite:
2234 2236 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2235 2237 # log what is now valid Python, not the actual user input (without the
2236 2238 # final newline)
2237 2239 self.log(line,newcmd,continue_prompt)
2238 2240 return newcmd
2239 2241
2240 2242 def handle_help(self, line, continue_prompt=None,
2241 2243 pre=None,iFun=None,theRest=None):
2242 2244 """Try to get some help for the object.
2243 2245
2244 2246 obj? or ?obj -> basic information.
2245 2247 obj?? or ??obj -> more details.
2246 2248 """
2247 2249
2248 2250 # We need to make sure that we don't process lines which would be
2249 2251 # otherwise valid python, such as "x=1 # what?"
2250 2252 try:
2251 2253 codeop.compile_command(line)
2252 2254 except SyntaxError:
2253 2255 # We should only handle as help stuff which is NOT valid syntax
2254 2256 if line[0]==self.ESC_HELP:
2255 2257 line = line[1:]
2256 2258 elif line[-1]==self.ESC_HELP:
2257 2259 line = line[:-1]
2258 2260 self.log(line,'#?'+line,continue_prompt)
2259 2261 if line:
2260 2262 self.magic_pinfo(line)
2261 2263 else:
2262 2264 page(self.usage,screen_lines=self.rc.screen_length)
2263 2265 return '' # Empty string is needed here!
2264 2266 except:
2265 2267 # Pass any other exceptions through to the normal handler
2266 2268 return self.handle_normal(line,continue_prompt)
2267 2269 else:
2268 2270 # If the code compiles ok, we should handle it normally
2269 2271 return self.handle_normal(line,continue_prompt)
2270 2272
2271 2273 def getapi(self):
2272 2274 """ Get an IPApi object for this shell instance
2273 2275
2274 2276 Getting an IPApi object is always preferable to accessing the shell
2275 2277 directly, but this holds true especially for extensions.
2276 2278
2277 2279 It should always be possible to implement an extension with IPApi
2278 2280 alone. If not, contact maintainer to request an addition.
2279 2281
2280 2282 """
2281 2283 return self.api
2282 2284
2283 2285 def handle_emacs(self,line,continue_prompt=None,
2284 2286 pre=None,iFun=None,theRest=None):
2285 2287 """Handle input lines marked by python-mode."""
2286 2288
2287 2289 # Currently, nothing is done. Later more functionality can be added
2288 2290 # here if needed.
2289 2291
2290 2292 # The input cache shouldn't be updated
2291 2293
2292 2294 return line
2293 2295
2294 2296 def mktempfile(self,data=None):
2295 2297 """Make a new tempfile and return its filename.
2296 2298
2297 2299 This makes a call to tempfile.mktemp, but it registers the created
2298 2300 filename internally so ipython cleans it up at exit time.
2299 2301
2300 2302 Optional inputs:
2301 2303
2302 2304 - data(None): if data is given, it gets written out to the temp file
2303 2305 immediately, and the file is closed again."""
2304 2306
2305 2307 filename = tempfile.mktemp('.py','ipython_edit_')
2306 2308 self.tempfiles.append(filename)
2307 2309
2308 2310 if data:
2309 2311 tmp_file = open(filename,'w')
2310 2312 tmp_file.write(data)
2311 2313 tmp_file.close()
2312 2314 return filename
2313 2315
2314 2316 def write(self,data):
2315 2317 """Write a string to the default output"""
2316 2318 Term.cout.write(data)
2317 2319
2318 2320 def write_err(self,data):
2319 2321 """Write a string to the default error output"""
2320 2322 Term.cerr.write(data)
2321 2323
2322 2324 def exit(self):
2323 2325 """Handle interactive exit.
2324 2326
2325 2327 This method sets the exit_now attribute."""
2326 2328
2327 2329 if self.rc.confirm_exit:
2328 2330 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2329 2331 self.exit_now = True
2330 2332 else:
2331 2333 self.exit_now = True
2332 2334
2333 2335 def safe_execfile(self,fname,*where,**kw):
2334 2336 fname = os.path.expanduser(fname)
2335 2337
2336 2338 # find things also in current directory
2337 2339 dname = os.path.dirname(fname)
2338 2340 if not sys.path.count(dname):
2339 2341 sys.path.append(dname)
2340 2342
2341 2343 try:
2342 2344 xfile = open(fname)
2343 2345 except:
2344 2346 print >> Term.cerr, \
2345 2347 'Could not open file <%s> for safe execution.' % fname
2346 2348 return None
2347 2349
2348 2350 kw.setdefault('islog',0)
2349 2351 kw.setdefault('quiet',1)
2350 2352 kw.setdefault('exit_ignore',0)
2351 2353 first = xfile.readline()
2352 2354 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2353 2355 xfile.close()
2354 2356 # line by line execution
2355 2357 if first.startswith(loghead) or kw['islog']:
2356 2358 print 'Loading log file <%s> one line at a time...' % fname
2357 2359 if kw['quiet']:
2358 2360 stdout_save = sys.stdout
2359 2361 sys.stdout = StringIO.StringIO()
2360 2362 try:
2361 2363 globs,locs = where[0:2]
2362 2364 except:
2363 2365 try:
2364 2366 globs = locs = where[0]
2365 2367 except:
2366 2368 globs = locs = globals()
2367 2369 badblocks = []
2368 2370
2369 2371 # we also need to identify indented blocks of code when replaying
2370 2372 # logs and put them together before passing them to an exec
2371 2373 # statement. This takes a bit of regexp and look-ahead work in the
2372 2374 # file. It's easiest if we swallow the whole thing in memory
2373 2375 # first, and manually walk through the lines list moving the
2374 2376 # counter ourselves.
2375 2377 indent_re = re.compile('\s+\S')
2376 2378 xfile = open(fname)
2377 2379 filelines = xfile.readlines()
2378 2380 xfile.close()
2379 2381 nlines = len(filelines)
2380 2382 lnum = 0
2381 2383 while lnum < nlines:
2382 2384 line = filelines[lnum]
2383 2385 lnum += 1
2384 2386 # don't re-insert logger status info into cache
2385 2387 if line.startswith('#log#'):
2386 2388 continue
2387 2389 else:
2388 2390 # build a block of code (maybe a single line) for execution
2389 2391 block = line
2390 2392 try:
2391 2393 next = filelines[lnum] # lnum has already incremented
2392 2394 except:
2393 2395 next = None
2394 2396 while next and indent_re.match(next):
2395 2397 block += next
2396 2398 lnum += 1
2397 2399 try:
2398 2400 next = filelines[lnum]
2399 2401 except:
2400 2402 next = None
2401 2403 # now execute the block of one or more lines
2402 2404 try:
2403 2405 exec block in globs,locs
2404 2406 except SystemExit:
2405 2407 pass
2406 2408 except:
2407 2409 badblocks.append(block.rstrip())
2408 2410 if kw['quiet']: # restore stdout
2409 2411 sys.stdout.close()
2410 2412 sys.stdout = stdout_save
2411 2413 print 'Finished replaying log file <%s>' % fname
2412 2414 if badblocks:
2413 2415 print >> sys.stderr, ('\nThe following lines/blocks in file '
2414 2416 '<%s> reported errors:' % fname)
2415 2417
2416 2418 for badline in badblocks:
2417 2419 print >> sys.stderr, badline
2418 2420 else: # regular file execution
2419 2421 try:
2420 2422 execfile(fname,*where)
2421 2423 except SyntaxError:
2422 2424 self.showsyntaxerror()
2423 2425 warn('Failure executing file: <%s>' % fname)
2424 2426 except SystemExit,status:
2425 2427 if not kw['exit_ignore']:
2426 2428 self.showtraceback()
2427 2429 warn('Failure executing file: <%s>' % fname)
2428 2430 except:
2429 2431 self.showtraceback()
2430 2432 warn('Failure executing file: <%s>' % fname)
2431 2433
2432 2434 #************************* end of file <iplib.py> *****************************
@@ -1,297 +1,305 b''
1 1 #!/usr/bin/env python
2 2 """Module for interactively running scripts.
3 3
4 4 This module implements classes for interactively running scripts written for
5 5 any system with a prompt which can be matched by a regexp suitable for
6 6 pexpect. It can be used to run as if they had been typed up interactively, an
7 7 arbitrary series of commands for the target system.
8 8
9 9 The module includes classes ready for IPython (with the default prompts),
10 10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 11 simply run the module as a script:
12 12
13 13 ./irunner.py --help
14 14
15 15
16 16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 17 contributed on the ipython-user list:
18 18
19 19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20 20
21 21
22 22 NOTES:
23 23
24 24 - This module requires pexpect, available in most linux distros, or which can
25 25 be downloaded from
26 26
27 27 http://pexpect.sourceforge.net
28 28
29 29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 30 limitations. This means that it will NOT work under native windows Python.
31 31 """
32 32
33 33 # Stdlib imports
34 34 import optparse
35 35 import os
36 36 import sys
37 37
38 38 # Third-party modules.
39 39 import pexpect
40 40
41 41 # Global usage strings, to avoid indentation issues when typing it below.
42 42 USAGE = """
43 43 Interactive script runner, type: %s
44 44
45 45 runner [opts] script_name
46 46 """
47 47
48 48 # The generic runner class
49 49 class InteractiveRunner(object):
50 50 """Class to run a sequence of commands through an interactive program."""
51 51
52 52 def __init__(self,program,prompts,args=None):
53 53 """Construct a runner.
54 54
55 55 Inputs:
56 56
57 57 - program: command to execute the given program.
58 58
59 59 - prompts: a list of patterns to match as valid prompts, in the
60 60 format used by pexpect. This basically means that it can be either
61 61 a string (to be compiled as a regular expression) or a list of such
62 62 (it must be a true list, as pexpect does type checks).
63 63
64 64 If more than one prompt is given, the first is treated as the main
65 65 program prompt and the others as 'continuation' prompts, like
66 66 python's. This means that blank lines in the input source are
67 67 ommitted when the first prompt is matched, but are NOT ommitted when
68 68 the continuation one matches, since this is how python signals the
69 69 end of multiline input interactively.
70 70
71 71 Optional inputs:
72 72
73 73 - args(None): optional list of strings to pass as arguments to the
74 74 child program.
75 75
76 76 Public members not parameterized in the constructor:
77 77
78 78 - delaybeforesend(0): Newer versions of pexpect have a delay before
79 79 sending each new input. For our purposes here, it's typically best
80 80 to just set this to zero, but if you encounter reliability problems
81 81 or want an interactive run to pause briefly at each prompt, just
82 82 increase this value (it is measured in seconds). Note that this
83 83 variable is not honored at all by older versions of pexpect.
84 84 """
85 85
86 86 self.program = program
87 87 self.prompts = prompts
88 88 if args is None: args = []
89 89 self.args = args
90 90 # Other public members which we don't make as parameters, but which
91 91 # users may occasionally want to tweak
92 92 self.delaybeforesend = 0
93 93
94 94 def run_file(self,fname,interact=False):
95 95 """Run the given file interactively.
96 96
97 97 Inputs:
98 98
99 99 -fname: name of the file to execute.
100 100
101 101 See the run_source docstring for the meaning of the optional
102 102 arguments."""
103 103
104 104 fobj = open(fname,'r')
105 105 try:
106 106 self.run_source(fobj,interact)
107 107 finally:
108 108 fobj.close()
109 109
110 110 def run_source(self,source,interact=False):
111 111 """Run the given source code interactively.
112 112
113 113 Inputs:
114 114
115 115 - source: a string of code to be executed, or an open file object we
116 116 can iterate over.
117 117
118 118 Optional inputs:
119 119
120 120 - interact(False): if true, start to interact with the running
121 121 program at the end of the script. Otherwise, just exit.
122 122 """
123 123
124 124 # if the source is a string, chop it up in lines so we can iterate
125 125 # over it just as if it were an open file.
126 126 if not isinstance(source,file):
127 127 source = source.splitlines(True)
128 128
129 129 # grab the true write method of stdout, in case anything later
130 130 # reassigns sys.stdout, so that we really are writing to the true
131 131 # stdout and not to something else. We also normalize all strings we
132 132 # write to use the native OS line separators.
133 133 linesep = os.linesep
134 134 stdwrite = sys.stdout.write
135 135 write = lambda s: stdwrite(s.replace('\r\n',linesep))
136 136
137 137 c = pexpect.spawn(self.program,self.args,timeout=None)
138 138 c.delaybeforesend = self.delaybeforesend
139 139
140 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
141 # This causes problems because any line longer than 80 characters gets
142 # completely overwrapped on the printed outptut (even though
143 # internally the code runs fine). We reset this to 99 rows X 200
144 # columns (arbitrarily chosen), which should avoid problems in all
145 # reasonable cases.
146 c.setwinsize(99,200)
147
140 148 prompts = c.compile_pattern_list(self.prompts)
141 149
142 150 prompt_idx = c.expect_list(prompts)
143 151 # Flag whether the script ends normally or not, to know whether we can
144 152 # do anything further with the underlying process.
145 153 end_normal = True
146 154 for cmd in source:
147 155 # skip blank lines for all matches to the 'main' prompt, while the
148 156 # secondary prompts do not
149 157 if prompt_idx==0 and \
150 158 (cmd.isspace() or cmd.lstrip().startswith('#')):
151 159 print cmd,
152 160 continue
153 161
154 162 write(c.after)
155 163 c.send(cmd)
156 164 try:
157 165 prompt_idx = c.expect_list(prompts)
158 166 except pexpect.EOF:
159 167 # this will happen if the child dies unexpectedly
160 168 write(c.before)
161 169 end_normal = False
162 170 break
163 171 write(c.before)
164 172
165 173 if end_normal:
166 174 if interact:
167 175 c.send('\n')
168 176 print '<< Starting interactive mode >>',
169 177 try:
170 178 c.interact()
171 179 except OSError:
172 180 # This is what fires when the child stops. Simply print a
173 181 # newline so the system prompt is aligned. The extra
174 182 # space is there to make sure it gets printed, otherwise
175 183 # OS buffering sometimes just suppresses it.
176 184 write(' \n')
177 185 sys.stdout.flush()
178 186 else:
179 187 c.close()
180 188 else:
181 189 if interact:
182 190 e="Further interaction is not possible: child process is dead."
183 191 print >> sys.stderr, e
184 192
185 193 def main(self,argv=None):
186 194 """Run as a command-line script."""
187 195
188 196 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
189 197 newopt = parser.add_option
190 198 newopt('-i','--interact',action='store_true',default=False,
191 199 help='Interact with the program after the script is run.')
192 200
193 201 opts,args = parser.parse_args(argv)
194 202
195 203 if len(args) != 1:
196 204 print >> sys.stderr,"You must supply exactly one file to run."
197 205 sys.exit(1)
198 206
199 207 self.run_file(args[0],opts.interact)
200 208
201 209
202 210 # Specific runners for particular programs
203 211 class IPythonRunner(InteractiveRunner):
204 212 """Interactive IPython runner.
205 213
206 214 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
207 215 avoid having to write a regexp that matches ANSI sequences, though pexpect
208 216 does support them. If anyone contributes patches for ANSI color support,
209 217 they will be welcome.
210 218
211 219 It also sets the prompts manually, since the prompt regexps for
212 220 pexpect need to be matched to the actual prompts, so user-customized
213 221 prompts would break this.
214 222 """
215 223
216 224 def __init__(self,program = 'ipython',args=None):
217 225 """New runner, optionally passing the ipython command to use."""
218 226
219 227 args0 = ['-colors','NoColor',
220 228 '-pi1','In [\\#]: ',
221 229 '-pi2',' .\\D.: ']
222 230 if args is None: args = args0
223 231 else: args = args0 + args
224 232 prompts = [r'In \[\d+\]: ',r' \.*: ']
225 233 InteractiveRunner.__init__(self,program,prompts,args)
226 234
227 235
228 236 class PythonRunner(InteractiveRunner):
229 237 """Interactive Python runner."""
230 238
231 239 def __init__(self,program='python',args=None):
232 240 """New runner, optionally passing the python command to use."""
233 241
234 242 prompts = [r'>>> ',r'\.\.\. ']
235 243 InteractiveRunner.__init__(self,program,prompts,args)
236 244
237 245
238 246 class SAGERunner(InteractiveRunner):
239 247 """Interactive SAGE runner.
240 248
241 249 WARNING: this runner only works if you manually configure your SAGE copy
242 250 to use 'colors NoColor' in the ipythonrc config file, since currently the
243 251 prompt matching regexp does not identify color sequences."""
244 252
245 253 def __init__(self,program='sage',args=None):
246 254 """New runner, optionally passing the sage command to use."""
247 255
248 256 prompts = ['sage: ',r'\s*\.\.\. ']
249 257 InteractiveRunner.__init__(self,program,prompts,args)
250 258
251 259 # Global usage string, to avoid indentation issues if typed in a function def.
252 260 MAIN_USAGE = """
253 261 %prog [options] file_to_run
254 262
255 263 This is an interface to the various interactive runners available in this
256 264 module. If you want to pass specific options to one of the runners, you need
257 265 to first terminate the main options with a '--', and then provide the runner's
258 266 options. For example:
259 267
260 268 irunner.py --python -- --help
261 269
262 270 will pass --help to the python runner. Similarly,
263 271
264 272 irunner.py --ipython -- --interact script.ipy
265 273
266 274 will run the script.ipy file under the IPython runner, and then will start to
267 275 interact with IPython at the end of the script (instead of exiting).
268 276
269 277 The already implemented runners are listed below; adding one for a new program
270 278 is a trivial task, see the source for examples.
271 279
272 280 WARNING: the SAGE runner only works if you manually configure your SAGE copy
273 281 to use 'colors NoColor' in the ipythonrc config file, since currently the
274 282 prompt matching regexp does not identify color sequences.
275 283 """
276 284
277 285 def main():
278 286 """Run as a command-line script."""
279 287
280 288 parser = optparse.OptionParser(usage=MAIN_USAGE)
281 289 newopt = parser.add_option
282 290 parser.set_defaults(mode='ipython')
283 291 newopt('--ipython',action='store_const',dest='mode',const='ipython',
284 292 help='IPython interactive runner (default).')
285 293 newopt('--python',action='store_const',dest='mode',const='python',
286 294 help='Python interactive runner.')
287 295 newopt('--sage',action='store_const',dest='mode',const='sage',
288 296 help='SAGE interactive runner.')
289 297
290 298 opts,args = parser.parse_args()
291 299 runners = dict(ipython=IPythonRunner,
292 300 python=PythonRunner,
293 301 sage=SAGERunner)
294 302 runners[opts.mode]().main(args)
295 303
296 304 if __name__ == '__main__':
297 305 main()
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now