##// END OF EJS Templates
implement callable (i.e. straight python) aliases and _sh shadow namespace
vivainio -
Show More

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

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