##// END OF EJS Templates
Fix extra newlines in autocalling.
fperez -
Show More

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

@@ -1,2047 +1,2047 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 802 2005-09-06 03:49:12Z fperez $
9 $Id: iplib.py 807 2005-09-07 01:55:33Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2004 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, much of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 23 # nice to acknowledge credit where credit is due.
24 24 #*****************************************************************************
25 25
26 26 #****************************************************************************
27 27 # Modules and globals
28 28
29 29 from __future__ import generators # for 2.2 backwards-compatibility
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 exceptions
41 41 import keyword
42 42 import new
43 43 import os, sys, shutil
44 44 import code, glob, types, re
45 45 import string, StringIO
46 46 import inspect, pydoc
47 47 import bdb, pdb
48 48 import UserList # don't subclass list so this works with Python2.1
49 49 from pprint import pprint, pformat
50 50 import cPickle as pickle
51 51 import traceback
52 52
53 53 # IPython's own modules
54 54 import IPython
55 55 from IPython import OInspect,PyColorize,ultraTB
56 56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
57 57 from IPython.Logger import Logger
58 58 from IPython.Magic import Magic,magic2python,shlex_split
59 59 from IPython.usage import cmd_line_usage,interactive_usage
60 60 from IPython.Struct import Struct
61 61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 62 from IPython.FakeModule import FakeModule
63 63 from IPython.background_jobs import BackgroundJobManager
64 64 from IPython.genutils import *
65 65
66 66 # Global pointer to the running
67 67
68 68 # store the builtin raw_input globally, and use this always, in case user code
69 69 # overwrites it (like wx.py.PyShell does)
70 70 raw_input_original = raw_input
71 71
72 72 #****************************************************************************
73 73 # Some utility function definitions
74 74
75 75 class Bunch: pass
76 76
77 77 def esc_quotes(strng):
78 78 """Return the input string with single and double quotes escaped out"""
79 79
80 80 return strng.replace('"','\\"').replace("'","\\'")
81 81
82 82 def import_fail_info(mod_name,fns=None):
83 83 """Inform load failure for a module."""
84 84
85 85 if fns == None:
86 86 warn("Loading of %s failed.\n" % (mod_name,))
87 87 else:
88 88 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
89 89
90 90 def qw_lol(indata):
91 91 """qw_lol('a b') -> [['a','b']],
92 92 otherwise it's just a call to qw().
93 93
94 94 We need this to make sure the modules_some keys *always* end up as a
95 95 list of lists."""
96 96
97 97 if type(indata) in StringTypes:
98 98 return [qw(indata)]
99 99 else:
100 100 return qw(indata)
101 101
102 102 def ipmagic(arg_s):
103 103 """Call a magic function by name.
104 104
105 105 Input: a string containing the name of the magic function to call and any
106 106 additional arguments to be passed to the magic.
107 107
108 108 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
109 109 prompt:
110 110
111 111 In[1]: %name -opt foo bar
112 112
113 113 To call a magic without arguments, simply use ipmagic('name').
114 114
115 115 This provides a proper Python function to call IPython's magics in any
116 116 valid Python code you can type at the interpreter, including loops and
117 117 compound statements. It is added by IPython to the Python builtin
118 118 namespace upon initialization."""
119 119
120 120 args = arg_s.split(' ',1)
121 121 magic_name = args[0]
122 122 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
123 123 magic_name = magic_name[1:]
124 124 try:
125 125 magic_args = args[1]
126 126 except IndexError:
127 127 magic_args = ''
128 128 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
129 129 if fn is None:
130 130 error("Magic function `%s` not found." % magic_name)
131 131 else:
132 132 magic_args = __IPYTHON__.var_expand(magic_args)
133 133 return fn(magic_args)
134 134
135 135 def ipalias(arg_s):
136 136 """Call an alias by name.
137 137
138 138 Input: a string containing the name of the alias to call and any
139 139 additional arguments to be passed to the magic.
140 140
141 141 ipalias('name -opt foo bar') is equivalent to typing at the ipython
142 142 prompt:
143 143
144 144 In[1]: name -opt foo bar
145 145
146 146 To call an alias without arguments, simply use ipalias('name').
147 147
148 148 This provides a proper Python function to call IPython's aliases in any
149 149 valid Python code you can type at the interpreter, including loops and
150 150 compound statements. It is added by IPython to the Python builtin
151 151 namespace upon initialization."""
152 152
153 153 args = arg_s.split(' ',1)
154 154 alias_name = args[0]
155 155 try:
156 156 alias_args = args[1]
157 157 except IndexError:
158 158 alias_args = ''
159 159 if alias_name in __IPYTHON__.alias_table:
160 160 __IPYTHON__.call_alias(alias_name,alias_args)
161 161 else:
162 162 error("Alias `%s` not found." % alias_name)
163 163
164 164 #-----------------------------------------------------------------------------
165 165 # Local use classes
166 166 try:
167 167 from IPython import FlexCompleter
168 168
169 169 class MagicCompleter(FlexCompleter.Completer):
170 170 """Extension of the completer class to work on %-prefixed lines."""
171 171
172 172 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
173 173 """MagicCompleter() -> completer
174 174
175 175 Return a completer object suitable for use by the readline library
176 176 via readline.set_completer().
177 177
178 178 Inputs:
179 179
180 180 - shell: a pointer to the ipython shell itself. This is needed
181 181 because this completer knows about magic functions, and those can
182 182 only be accessed via the ipython instance.
183 183
184 184 - namespace: an optional dict where completions are performed.
185 185
186 186 - The optional omit__names parameter sets the completer to omit the
187 187 'magic' names (__magicname__) for python objects unless the text
188 188 to be completed explicitly starts with one or more underscores.
189 189
190 190 - If alias_table is supplied, it should be a dictionary of aliases
191 191 to complete. """
192 192
193 193 FlexCompleter.Completer.__init__(self,namespace)
194 194 self.magic_prefix = shell.name+'.magic_'
195 195 self.magic_escape = shell.ESC_MAGIC
196 196 self.readline = FlexCompleter.readline
197 197 delims = self.readline.get_completer_delims()
198 198 delims = delims.replace(self.magic_escape,'')
199 199 self.readline.set_completer_delims(delims)
200 200 self.get_line_buffer = self.readline.get_line_buffer
201 201 self.omit__names = omit__names
202 202 self.merge_completions = shell.rc.readline_merge_completions
203 203
204 204 if alias_table is None:
205 205 alias_table = {}
206 206 self.alias_table = alias_table
207 207 # Regexp to split filenames with spaces in them
208 208 self.space_name_re = re.compile(r'([^\\] )')
209 209 # Hold a local ref. to glob.glob for speed
210 210 self.glob = glob.glob
211 211 # Special handling of backslashes needed in win32 platforms
212 212 if sys.platform == "win32":
213 213 self.clean_glob = self._clean_glob_win32
214 214 else:
215 215 self.clean_glob = self._clean_glob
216 216 self.matchers = [self.python_matches,
217 217 self.file_matches,
218 218 self.alias_matches,
219 219 self.python_func_kw_matches]
220 220
221 221 # Code contributed by Alex Schmolck, for ipython/emacs integration
222 222 def all_completions(self, text):
223 223 """Return all possible completions for the benefit of emacs."""
224 224
225 225 completions = []
226 226 try:
227 227 for i in xrange(sys.maxint):
228 228 res = self.complete(text, i)
229 229
230 230 if not res: break
231 231
232 232 completions.append(res)
233 233 #XXX workaround for ``notDefined.<tab>``
234 234 except NameError:
235 235 pass
236 236 return completions
237 237 # /end Alex Schmolck code.
238 238
239 239 def _clean_glob(self,text):
240 240 return self.glob("%s*" % text)
241 241
242 242 def _clean_glob_win32(self,text):
243 243 return [f.replace("\\","/")
244 244 for f in self.glob("%s*" % text)]
245 245
246 246 def file_matches(self, text):
247 247 """Match filneames, expanding ~USER type strings.
248 248
249 249 Most of the seemingly convoluted logic in this completer is an
250 250 attempt to handle filenames with spaces in them. And yet it's not
251 251 quite perfect, because Python's readline doesn't expose all of the
252 252 GNU readline details needed for this to be done correctly.
253 253
254 254 For a filename with a space in it, the printed completions will be
255 255 only the parts after what's already been typed (instead of the
256 256 full completions, as is normally done). I don't think with the
257 257 current (as of Python 2.3) Python readline it's possible to do
258 258 better."""
259 259
260 260 #print 'Completer->file_matches: <%s>' % text # dbg
261 261
262 262 # chars that require escaping with backslash - i.e. chars
263 263 # that readline treats incorrectly as delimiters, but we
264 264 # don't want to treat as delimiters in filename matching
265 265 # when escaped with backslash
266 266
267 267 protectables = ' ()[]{}'
268 268
269 269 def protect_filename(s):
270 270 return "".join([(ch in protectables and '\\' + ch or ch)
271 271 for ch in s])
272 272
273 273 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
274 274 open_quotes = 0 # track strings with open quotes
275 275 try:
276 276 lsplit = shlex_split(lbuf)[-1]
277 277 except ValueError:
278 278 # typically an unmatched ", or backslash without escaped char.
279 279 if lbuf.count('"')==1:
280 280 open_quotes = 1
281 281 lsplit = lbuf.split('"')[-1]
282 282 elif lbuf.count("'")==1:
283 283 open_quotes = 1
284 284 lsplit = lbuf.split("'")[-1]
285 285 else:
286 286 return None
287 287 except IndexError:
288 288 # tab pressed on empty line
289 289 lsplit = ""
290 290
291 291 if lsplit != protect_filename(lsplit):
292 292 # if protectables are found, do matching on the whole escaped
293 293 # name
294 294 has_protectables = 1
295 295 text0,text = text,lsplit
296 296 else:
297 297 has_protectables = 0
298 298 text = os.path.expanduser(text)
299 299
300 300 if text == "":
301 301 return [protect_filename(f) for f in self.glob("*")]
302 302
303 303 m0 = self.clean_glob(text.replace('\\',''))
304 304 if has_protectables:
305 305 # If we had protectables, we need to revert our changes to the
306 306 # beginning of filename so that we don't double-write the part
307 307 # of the filename we have so far
308 308 len_lsplit = len(lsplit)
309 309 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
310 310 else:
311 311 if open_quotes:
312 312 # if we have a string with an open quote, we don't need to
313 313 # protect the names at all (and we _shouldn't_, as it
314 314 # would cause bugs when the filesystem call is made).
315 315 matches = m0
316 316 else:
317 317 matches = [protect_filename(f) for f in m0]
318 318 if len(matches) == 1 and os.path.isdir(matches[0]):
319 319 # Takes care of links to directories also. Use '/'
320 320 # explicitly, even under Windows, so that name completions
321 321 # don't end up escaped.
322 322 matches[0] += '/'
323 323 return matches
324 324
325 325 def alias_matches(self, text):
326 326 """Match internal system aliases"""
327 327 #print 'Completer->alias_matches:',text # dbg
328 328 text = os.path.expanduser(text)
329 329 aliases = self.alias_table.keys()
330 330 if text == "":
331 331 return aliases
332 332 else:
333 333 return [alias for alias in aliases if alias.startswith(text)]
334 334
335 335 def python_matches(self,text):
336 336 """Match attributes or global python names"""
337 337 #print 'Completer->python_matches' # dbg
338 338 if "." in text:
339 339 try:
340 340 matches = self.attr_matches(text)
341 341 if text.endswith('.') and self.omit__names:
342 342 if self.omit__names == 1:
343 343 # true if txt is _not_ a __ name, false otherwise:
344 344 no__name = (lambda txt:
345 345 re.match(r'.*\.__.*?__',txt) is None)
346 346 else:
347 347 # true if txt is _not_ a _ name, false otherwise:
348 348 no__name = (lambda txt:
349 349 re.match(r'.*\._.*?',txt) is None)
350 350 matches = filter(no__name, matches)
351 351 except NameError:
352 352 # catches <undefined attributes>.<tab>
353 353 matches = []
354 354 else:
355 355 matches = self.global_matches(text)
356 356 # this is so completion finds magics when automagic is on:
357 357 if matches == [] and not text.startswith(os.sep):
358 358 matches = self.attr_matches(self.magic_prefix+text)
359 359 return matches
360 360
361 361 def _default_arguments(self, obj):
362 362 """Return the list of default arguments of obj if it is callable,
363 363 or empty list otherwise."""
364 364
365 365 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
366 366 # for classes, check for __init__,__new__
367 367 if inspect.isclass(obj):
368 368 obj = (getattr(obj,'__init__',None) or
369 369 getattr(obj,'__new__',None))
370 370 # for all others, check if they are __call__able
371 371 elif hasattr(obj, '__call__'):
372 372 obj = obj.__call__
373 373 # XXX: is there a way to handle the builtins ?
374 374 try:
375 375 args,_,_1,defaults = inspect.getargspec(obj)
376 376 if defaults:
377 377 return args[-len(defaults):]
378 378 except TypeError: pass
379 379 return []
380 380
381 381 def python_func_kw_matches(self,text):
382 382 """Match named parameters (kwargs) of the last open function"""
383 383
384 384 if "." in text: # a parameter cannot be dotted
385 385 return []
386 386 try: regexp = self.__funcParamsRegex
387 387 except AttributeError:
388 388 regexp = self.__funcParamsRegex = re.compile(r'''
389 389 '.*?' | # single quoted strings or
390 390 ".*?" | # double quoted strings or
391 391 \w+ | # identifier
392 392 \S # other characters
393 393 ''', re.VERBOSE | re.DOTALL)
394 394 # 1. find the nearest identifier that comes before an unclosed
395 395 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
396 396 tokens = regexp.findall(self.get_line_buffer())
397 397 tokens.reverse()
398 398 iterTokens = iter(tokens); openPar = 0
399 399 for token in iterTokens:
400 400 if token == ')':
401 401 openPar -= 1
402 402 elif token == '(':
403 403 openPar += 1
404 404 if openPar > 0:
405 405 # found the last unclosed parenthesis
406 406 break
407 407 else:
408 408 return []
409 409 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
410 410 ids = []
411 411 isId = re.compile(r'\w+$').match
412 412 while True:
413 413 try:
414 414 ids.append(iterTokens.next())
415 415 if not isId(ids[-1]):
416 416 ids.pop(); break
417 417 if not iterTokens.next() == '.':
418 418 break
419 419 except StopIteration:
420 420 break
421 421 # lookup the candidate callable matches either using global_matches
422 422 # or attr_matches for dotted names
423 423 if len(ids) == 1:
424 424 callableMatches = self.global_matches(ids[0])
425 425 else:
426 426 callableMatches = self.attr_matches('.'.join(ids[::-1]))
427 427 argMatches = []
428 428 for callableMatch in callableMatches:
429 429 try: namedArgs = self._default_arguments(eval(callableMatch,
430 430 self.namespace))
431 431 except: continue
432 432 for namedArg in namedArgs:
433 433 if namedArg.startswith(text):
434 434 argMatches.append("%s=" %namedArg)
435 435 return argMatches
436 436
437 437 def complete(self, text, state):
438 438 """Return the next possible completion for 'text'.
439 439
440 440 This is called successively with state == 0, 1, 2, ... until it
441 441 returns None. The completion should begin with 'text'. """
442 442
443 443 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
444 444 magic_escape = self.magic_escape
445 445 magic_prefix = self.magic_prefix
446 446
447 447 try:
448 448 if text.startswith(magic_escape):
449 449 text = text.replace(magic_escape,magic_prefix)
450 450 elif text.startswith('~'):
451 451 text = os.path.expanduser(text)
452 452 if state == 0:
453 453 # Extend the list of completions with the results of each
454 454 # matcher, so we return results to the user from all
455 455 # namespaces.
456 456 if self.merge_completions:
457 457 self.matches = []
458 458 for matcher in self.matchers:
459 459 self.matches.extend(matcher(text))
460 460 else:
461 461 for matcher in self.matchers:
462 462 self.matches = matcher(text)
463 463 if self.matches:
464 464 break
465 465
466 466 try:
467 467 return self.matches[state].replace(magic_prefix,magic_escape)
468 468 except IndexError:
469 469 return None
470 470 except:
471 471 # If completion fails, don't annoy the user.
472 472 pass
473 473
474 474 except ImportError:
475 475 pass # no readline support
476 476
477 477 except KeyError:
478 478 pass # Windows doesn't set TERM, it doesn't matter
479 479
480 480
481 481 class InputList(UserList.UserList):
482 482 """Class to store user input.
483 483
484 484 It's basically a list, but slices return a string instead of a list, thus
485 485 allowing things like (assuming 'In' is an instance):
486 486
487 487 exec In[4:7]
488 488
489 489 or
490 490
491 491 exec In[5:9] + In[14] + In[21:25]"""
492 492
493 493 def __getslice__(self,i,j):
494 494 return ''.join(UserList.UserList.__getslice__(self,i,j))
495 495
496 496 #****************************************************************************
497 497 # Local use exceptions
498 498 class SpaceInInput(exceptions.Exception):
499 499 pass
500 500
501 501 #****************************************************************************
502 502 # Main IPython class
503 503
504 504 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
505 505 """An enhanced console for Python."""
506 506
507 507 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
508 508 user_ns = None,banner2='',
509 509 custom_exceptions=((),None)):
510 510
511 511 # Put a reference to self in builtins so that any form of embedded or
512 512 # imported code can test for being inside IPython.
513 513 __builtin__.__IPYTHON__ = self
514 514
515 515 # And load into builtins ipmagic/ipalias as well
516 516 __builtin__.ipmagic = ipmagic
517 517 __builtin__.ipalias = ipalias
518 518
519 519 # Add to __builtin__ other parts of IPython's public API
520 520 __builtin__.ip_set_hook = self.set_hook
521 521
522 522 # Keep in the builtins a flag for when IPython is active. We set it
523 523 # with setdefault so that multiple nested IPythons don't clobber one
524 524 # another. Each will increase its value by one upon being activated,
525 525 # which also gives us a way to determine the nesting level.
526 526 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
527 527
528 528 # Inform the user of ipython's fast exit magics.
529 529 _exit = ' Use %Exit or %Quit to exit without confirmation.'
530 530 __builtin__.exit += _exit
531 531 __builtin__.quit += _exit
532 532
533 533 # Create the namespace where the user will operate:
534 534
535 535 # FIXME. For some strange reason, __builtins__ is showing up at user
536 536 # level as a dict instead of a module. This is a manual fix, but I
537 537 # should really track down where the problem is coming from. Alex
538 538 # Schmolck reported this problem first.
539 539
540 540 # A useful post by Alex Martelli on this topic:
541 541 # Re: inconsistent value from __builtins__
542 542 # Von: Alex Martelli <aleaxit@yahoo.com>
543 543 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
544 544 # Gruppen: comp.lang.python
545 545 # Referenzen: 1
546 546
547 547 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
548 548 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
549 549 # > <type 'dict'>
550 550 # > >>> print type(__builtins__)
551 551 # > <type 'module'>
552 552 # > Is this difference in return value intentional?
553 553
554 554 # Well, it's documented that '__builtins__' can be either a dictionary
555 555 # or a module, and it's been that way for a long time. Whether it's
556 556 # intentional (or sensible), I don't know. In any case, the idea is that
557 557 # if you need to access the built-in namespace directly, you should start
558 558 # with "import __builtin__" (note, no 's') which will definitely give you
559 559 # a module. Yeah, it's somewhat confusing:-(.
560 560
561 561 if user_ns is None:
562 562 # Set __name__ to __main__ to better match the behavior of the
563 563 # normal interpreter.
564 564 self.user_ns = {'__name__' :'__main__',
565 565 '__builtins__' : __builtin__,
566 566 }
567 567 else:
568 568 self.user_ns = user_ns
569 569
570 570 # The user namespace MUST have a pointer to the shell itself.
571 571 self.user_ns[name] = self
572 572
573 573 # We need to insert into sys.modules something that looks like a
574 574 # module but which accesses the IPython namespace, for shelve and
575 575 # pickle to work interactively. Normally they rely on getting
576 576 # everything out of __main__, but for embedding purposes each IPython
577 577 # instance has its own private namespace, so we can't go shoving
578 578 # everything into __main__.
579 579
580 580 try:
581 581 main_name = self.user_ns['__name__']
582 582 except KeyError:
583 583 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
584 584 else:
585 585 #print "pickle hack in place" # dbg
586 586 sys.modules[main_name] = FakeModule(self.user_ns)
587 587
588 588 # List of input with multi-line handling.
589 589 # Fill its zero entry, user counter starts at 1
590 590 self.input_hist = InputList(['\n'])
591 591
592 592 # list of visited directories
593 593 try:
594 594 self.dir_hist = [os.getcwd()]
595 595 except IOError, e:
596 596 self.dir_hist = []
597 597
598 598 # dict of output history
599 599 self.output_hist = {}
600 600
601 601 # dict of names to be treated as system aliases. Each entry in the
602 602 # alias table must be a 2-tuple of the form (N,name), where N is the
603 603 # number of positional arguments of the alias.
604 604 self.alias_table = {}
605 605
606 606 # dict of things NOT to alias (keywords, builtins and some special magics)
607 607 no_alias = {}
608 608 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
609 609 for key in keyword.kwlist + no_alias_magics:
610 610 no_alias[key] = 1
611 611 no_alias.update(__builtin__.__dict__)
612 612 self.no_alias = no_alias
613 613
614 614
615 615 # make global variables for user access to these
616 616 self.user_ns['_ih'] = self.input_hist
617 617 self.user_ns['_oh'] = self.output_hist
618 618 self.user_ns['_dh'] = self.dir_hist
619 619
620 620 # user aliases to input and output histories
621 621 self.user_ns['In'] = self.input_hist
622 622 self.user_ns['Out'] = self.output_hist
623 623
624 624 # Store the actual shell's name
625 625 self.name = name
626 626
627 627 # Object variable to store code object waiting execution. This is
628 628 # used mainly by the multithreaded shells, but it can come in handy in
629 629 # other situations. No need to use a Queue here, since it's a single
630 630 # item which gets cleared once run.
631 631 self.code_to_run = None
632 632
633 633 # Job manager (for jobs run as background threads)
634 634 self.jobs = BackgroundJobManager()
635 635 # Put the job manager into builtins so it's always there.
636 636 __builtin__.jobs = self.jobs
637 637
638 638 # escapes for automatic behavior on the command line
639 639 self.ESC_SHELL = '!'
640 640 self.ESC_HELP = '?'
641 641 self.ESC_MAGIC = '%'
642 642 self.ESC_QUOTE = ','
643 643 self.ESC_QUOTE2 = ';'
644 644 self.ESC_PAREN = '/'
645 645
646 646 # And their associated handlers
647 647 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
648 648 self.ESC_QUOTE:self.handle_auto,
649 649 self.ESC_QUOTE2:self.handle_auto,
650 650 self.ESC_MAGIC:self.handle_magic,
651 651 self.ESC_HELP:self.handle_help,
652 652 self.ESC_SHELL:self.handle_shell_escape,
653 653 }
654 654
655 655 # class initializations
656 656 code.InteractiveConsole.__init__(self,locals = self.user_ns)
657 657 Logger.__init__(self,log_ns = self.user_ns)
658 658 Magic.__init__(self,self)
659 659
660 660 # an ugly hack to get a pointer to the shell, so I can start writing
661 661 # magic code via this pointer instead of the current mixin salad.
662 662 Magic.set_shell(self,self)
663 663
664 664 # hooks holds pointers used for user-side customizations
665 665 self.hooks = Struct()
666 666
667 667 # Set all default hooks, defined in the IPython.hooks module.
668 668 hooks = IPython.hooks
669 669 for hook_name in hooks.__all__:
670 670 self.set_hook(hook_name,getattr(hooks,hook_name))
671 671
672 672 # Flag to mark unconditional exit
673 673 self.exit_now = False
674 674
675 675 self.usage_min = """\
676 676 An enhanced console for Python.
677 677 Some of its features are:
678 678 - Readline support if the readline library is present.
679 679 - Tab completion in the local namespace.
680 680 - Logging of input, see command-line options.
681 681 - System shell escape via ! , eg !ls.
682 682 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
683 683 - Keeps track of locally defined variables via %who, %whos.
684 684 - Show object information with a ? eg ?x or x? (use ?? for more info).
685 685 """
686 686 if usage: self.usage = usage
687 687 else: self.usage = self.usage_min
688 688
689 689 # Storage
690 690 self.rc = rc # This will hold all configuration information
691 691 self.inputcache = []
692 692 self._boundcache = []
693 693 self.pager = 'less'
694 694 # temporary files used for various purposes. Deleted at exit.
695 695 self.tempfiles = []
696 696
697 697 # Keep track of readline usage (later set by init_readline)
698 698 self.has_readline = 0
699 699
700 700 # for pushd/popd management
701 701 try:
702 702 self.home_dir = get_home_dir()
703 703 except HomeDirError,msg:
704 704 fatal(msg)
705 705
706 706 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
707 707
708 708 # Functions to call the underlying shell.
709 709
710 710 # utility to expand user variables via Itpl
711 711 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
712 712 self.user_ns))
713 713 # The first is similar to os.system, but it doesn't return a value,
714 714 # and it allows interpolation of variables in the user's namespace.
715 715 self.system = lambda cmd: shell(self.var_expand(cmd),
716 716 header='IPython system call: ',
717 717 verbose=self.rc.system_verbose)
718 718 # These are for getoutput and getoutputerror:
719 719 self.getoutput = lambda cmd: \
720 720 getoutput(self.var_expand(cmd),
721 721 header='IPython system call: ',
722 722 verbose=self.rc.system_verbose)
723 723 self.getoutputerror = lambda cmd: \
724 724 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
725 725 self.user_ns)),
726 726 header='IPython system call: ',
727 727 verbose=self.rc.system_verbose)
728 728
729 729 # RegExp for splitting line contents into pre-char//first
730 730 # word-method//rest. For clarity, each group in on one line.
731 731
732 732 # WARNING: update the regexp if the above escapes are changed, as they
733 733 # are hardwired in.
734 734
735 735 # Don't get carried away with trying to make the autocalling catch too
736 736 # much: it's better to be conservative rather than to trigger hidden
737 737 # evals() somewhere and end up causing side effects.
738 738
739 739 self.line_split = re.compile(r'^([\s*,;/])'
740 740 r'([\?\w\.]+\w*\s*)'
741 741 r'(\(?.*$)')
742 742
743 743 # Original re, keep around for a while in case changes break something
744 744 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
745 745 # r'(\s*[\?\w\.]+\w*\s*)'
746 746 # r'(\(?.*$)')
747 747
748 748 # RegExp to identify potential function names
749 749 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
750 750 # RegExp to exclude strings with this start from autocalling
751 751 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
752 752 # try to catch also methods for stuff in lists/tuples/dicts: off
753 753 # (experimental). For this to work, the line_split regexp would need
754 754 # to be modified so it wouldn't break things at '['. That line is
755 755 # nasty enough that I shouldn't change it until I can test it _well_.
756 756 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
757 757
758 758 # keep track of where we started running (mainly for crash post-mortem)
759 759 self.starting_dir = os.getcwd()
760 760
761 761 # Attributes for Logger mixin class, make defaults here
762 762 self._dolog = 0
763 763 self.LOG = ''
764 764 self.LOGDEF = '.InteractiveShell.log'
765 765 self.LOGMODE = 'over'
766 766 self.LOGHEAD = Itpl(
767 767 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
768 768 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
769 769 #log# opts = $self.rc.opts
770 770 #log# args = $self.rc.args
771 771 #log# It is safe to make manual edits below here.
772 772 #log#-----------------------------------------------------------------------
773 773 """)
774 774 # Various switches which can be set
775 775 self.CACHELENGTH = 5000 # this is cheap, it's just text
776 776 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
777 777 self.banner2 = banner2
778 778
779 779 # TraceBack handlers:
780 780 # Need two, one for syntax errors and one for other exceptions.
781 781 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
782 782 # This one is initialized with an offset, meaning we always want to
783 783 # remove the topmost item in the traceback, which is our own internal
784 784 # code. Valid modes: ['Plain','Context','Verbose']
785 785 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
786 786 color_scheme='NoColor',
787 787 tb_offset = 1)
788 788 # and add any custom exception handlers the user may have specified
789 789 self.set_custom_exc(*custom_exceptions)
790 790
791 791 # Object inspector
792 792 ins_colors = OInspect.InspectColors
793 793 code_colors = PyColorize.ANSICodeColors
794 794 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
795 795 self.autoindent = 0
796 796
797 797 # Make some aliases automatically
798 798 # Prepare list of shell aliases to auto-define
799 799 if os.name == 'posix':
800 800 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
801 801 'mv mv -i','rm rm -i','cp cp -i',
802 802 'cat cat','less less','clear clear',
803 803 # a better ls
804 804 'ls ls -F',
805 805 # long ls
806 806 'll ls -lF',
807 807 # color ls
808 808 'lc ls -F -o --color',
809 809 # ls normal files only
810 810 'lf ls -F -o --color %l | grep ^-',
811 811 # ls symbolic links
812 812 'lk ls -F -o --color %l | grep ^l',
813 813 # directories or links to directories,
814 814 'ldir ls -F -o --color %l | grep /$',
815 815 # things which are executable
816 816 'lx ls -F -o --color %l | grep ^-..x',
817 817 )
818 818 elif os.name in ['nt','dos']:
819 819 auto_alias = ('dir dir /on', 'ls dir /on',
820 820 'ddir dir /ad /on', 'ldir dir /ad /on',
821 821 'mkdir mkdir','rmdir rmdir','echo echo',
822 822 'ren ren','cls cls','copy copy')
823 823 else:
824 824 auto_alias = ()
825 825 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
826 826 # Call the actual (public) initializer
827 827 self.init_auto_alias()
828 828 # end __init__
829 829
830 830 def set_hook(self,name,hook):
831 831 """set_hook(name,hook) -> sets an internal IPython hook.
832 832
833 833 IPython exposes some of its internal API as user-modifiable hooks. By
834 834 resetting one of these hooks, you can modify IPython's behavior to
835 835 call at runtime your own routines."""
836 836
837 837 # At some point in the future, this should validate the hook before it
838 838 # accepts it. Probably at least check that the hook takes the number
839 839 # of args it's supposed to.
840 840 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
841 841
842 842 def set_custom_exc(self,exc_tuple,handler):
843 843 """set_custom_exc(exc_tuple,handler)
844 844
845 845 Set a custom exception handler, which will be called if any of the
846 846 exceptions in exc_tuple occur in the mainloop (specifically, in the
847 847 runcode() method.
848 848
849 849 Inputs:
850 850
851 851 - exc_tuple: a *tuple* of valid exceptions to call the defined
852 852 handler for. It is very important that you use a tuple, and NOT A
853 853 LIST here, because of the way Python's except statement works. If
854 854 you only want to trap a single exception, use a singleton tuple:
855 855
856 856 exc_tuple == (MyCustomException,)
857 857
858 858 - handler: this must be defined as a function with the following
859 859 basic interface: def my_handler(self,etype,value,tb).
860 860
861 861 This will be made into an instance method (via new.instancemethod)
862 862 of IPython itself, and it will be called if any of the exceptions
863 863 listed in the exc_tuple are caught. If the handler is None, an
864 864 internal basic one is used, which just prints basic info.
865 865
866 866 WARNING: by putting in your own exception handler into IPython's main
867 867 execution loop, you run a very good chance of nasty crashes. This
868 868 facility should only be used if you really know what you are doing."""
869 869
870 870 assert type(exc_tuple)==type(()) , \
871 871 "The custom exceptions must be given AS A TUPLE."
872 872
873 873 def dummy_handler(self,etype,value,tb):
874 874 print '*** Simple custom exception handler ***'
875 875 print 'Exception type :',etype
876 876 print 'Exception value:',value
877 877 print 'Traceback :',tb
878 878 print 'Source code :','\n'.join(self.buffer)
879 879
880 880 if handler is None: handler = dummy_handler
881 881
882 882 self.CustomTB = new.instancemethod(handler,self,self.__class__)
883 883 self.custom_exceptions = exc_tuple
884 884
885 885 def set_custom_completer(self,completer,pos=0):
886 886 """set_custom_completer(completer,pos=0)
887 887
888 888 Adds a new custom completer function.
889 889
890 890 The position argument (defaults to 0) is the index in the completers
891 891 list where you want the completer to be inserted."""
892 892
893 893 newcomp = new.instancemethod(completer,self.Completer,
894 894 self.Completer.__class__)
895 895 self.Completer.matchers.insert(pos,newcomp)
896 896
897 897 def complete(self,text):
898 898 """Return a sorted list of all possible completions on text.
899 899
900 900 Inputs:
901 901
902 902 - text: a string of text to be completed on.
903 903
904 904 This is a wrapper around the completion mechanism, similar to what
905 905 readline does at the command line when the TAB key is hit. By
906 906 exposing it as a method, it can be used by other non-readline
907 907 environments (such as GUIs) for text completion.
908 908
909 909 Simple usage example:
910 910
911 911 In [1]: x = 'hello'
912 912
913 913 In [2]: __IP.complete('x.l')
914 914 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
915 915
916 916 complete = self.Completer.complete
917 917 state = 0
918 918 # use a dict so we get unique keys, since ipyhton's multiple
919 919 # completers can return duplicates.
920 920 comps = {}
921 921 while True:
922 922 newcomp = complete(text,state)
923 923 if newcomp is None:
924 924 break
925 925 comps[newcomp] = 1
926 926 state += 1
927 927 outcomps = comps.keys()
928 928 outcomps.sort()
929 929 return outcomps
930 930
931 931 def post_config_initialization(self):
932 932 """Post configuration init method
933 933
934 934 This is called after the configuration files have been processed to
935 935 'finalize' the initialization."""
936 936
937 937 # dynamic data that survives through sessions
938 938 # XXX make the filename a config option?
939 939 persist_base = 'persist'
940 940 if self.rc.profile:
941 941 persist_base += '_%s' % self.rc.profile
942 942 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
943 943
944 944 try:
945 945 self.persist = pickle.load(file(self.persist_fname))
946 946 except:
947 947 self.persist = {}
948 948
949 949 def init_auto_alias(self):
950 950 """Define some aliases automatically.
951 951
952 952 These are ALL parameter-less aliases"""
953 953 for alias,cmd in self.auto_alias:
954 954 self.alias_table[alias] = (0,cmd)
955 955
956 956 def alias_table_validate(self,verbose=0):
957 957 """Update information about the alias table.
958 958
959 959 In particular, make sure no Python keywords/builtins are in it."""
960 960
961 961 no_alias = self.no_alias
962 962 for k in self.alias_table:
963 963 if k in no_alias:
964 964 del self.alias_table[k]
965 965 if verbose:
966 966 print ("Deleting alias <%s>, it's a Python "
967 967 "keyword or builtin." % k)
968 968
969 969 def set_autoindent(self,value=None):
970 970 """Set the autoindent flag, checking for readline support.
971 971
972 972 If called with no arguments, it acts as a toggle."""
973 973
974 974 if not self.has_readline:
975 975 if os.name == 'posix':
976 976 warn("The auto-indent feature requires the readline library")
977 977 self.autoindent = 0
978 978 return
979 979 if value is None:
980 980 self.autoindent = not self.autoindent
981 981 else:
982 982 self.autoindent = value
983 983
984 984 def rc_set_toggle(self,rc_field,value=None):
985 985 """Set or toggle a field in IPython's rc config. structure.
986 986
987 987 If called with no arguments, it acts as a toggle.
988 988
989 989 If called with a non-existent field, the resulting AttributeError
990 990 exception will propagate out."""
991 991
992 992 rc_val = getattr(self.rc,rc_field)
993 993 if value is None:
994 994 value = not rc_val
995 995 setattr(self.rc,rc_field,value)
996 996
997 997 def user_setup(self,ipythondir,rc_suffix,mode='install'):
998 998 """Install the user configuration directory.
999 999
1000 1000 Can be called when running for the first time or to upgrade the user's
1001 1001 .ipython/ directory with the mode parameter. Valid modes are 'install'
1002 1002 and 'upgrade'."""
1003 1003
1004 1004 def wait():
1005 1005 try:
1006 1006 raw_input("Please press <RETURN> to start IPython.")
1007 1007 except EOFError:
1008 1008 print >> Term.cout
1009 1009 print '*'*70
1010 1010
1011 1011 cwd = os.getcwd() # remember where we started
1012 1012 glb = glob.glob
1013 1013 print '*'*70
1014 1014 if mode == 'install':
1015 1015 print \
1016 1016 """Welcome to IPython. I will try to create a personal configuration directory
1017 1017 where you can customize many aspects of IPython's functionality in:\n"""
1018 1018 else:
1019 1019 print 'I am going to upgrade your configuration in:'
1020 1020
1021 1021 print ipythondir
1022 1022
1023 1023 rcdirend = os.path.join('IPython','UserConfig')
1024 1024 cfg = lambda d: os.path.join(d,rcdirend)
1025 1025 try:
1026 1026 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1027 1027 except IOError:
1028 1028 warning = """
1029 1029 Installation error. IPython's directory was not found.
1030 1030
1031 1031 Check the following:
1032 1032
1033 1033 The ipython/IPython directory should be in a directory belonging to your
1034 1034 PYTHONPATH environment variable (that is, it should be in a directory
1035 1035 belonging to sys.path). You can copy it explicitly there or just link to it.
1036 1036
1037 1037 IPython will proceed with builtin defaults.
1038 1038 """
1039 1039 warn(warning)
1040 1040 wait()
1041 1041 return
1042 1042
1043 1043 if mode == 'install':
1044 1044 try:
1045 1045 shutil.copytree(rcdir,ipythondir)
1046 1046 os.chdir(ipythondir)
1047 1047 rc_files = glb("ipythonrc*")
1048 1048 for rc_file in rc_files:
1049 1049 os.rename(rc_file,rc_file+rc_suffix)
1050 1050 except:
1051 1051 warning = """
1052 1052
1053 1053 There was a problem with the installation:
1054 1054 %s
1055 1055 Try to correct it or contact the developers if you think it's a bug.
1056 1056 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1057 1057 warn(warning)
1058 1058 wait()
1059 1059 return
1060 1060
1061 1061 elif mode == 'upgrade':
1062 1062 try:
1063 1063 os.chdir(ipythondir)
1064 1064 except:
1065 1065 print """
1066 1066 Can not upgrade: changing to directory %s failed. Details:
1067 1067 %s
1068 1068 """ % (ipythondir,sys.exc_info()[1])
1069 1069 wait()
1070 1070 return
1071 1071 else:
1072 1072 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1073 1073 for new_full_path in sources:
1074 1074 new_filename = os.path.basename(new_full_path)
1075 1075 if new_filename.startswith('ipythonrc'):
1076 1076 new_filename = new_filename + rc_suffix
1077 1077 # The config directory should only contain files, skip any
1078 1078 # directories which may be there (like CVS)
1079 1079 if os.path.isdir(new_full_path):
1080 1080 continue
1081 1081 if os.path.exists(new_filename):
1082 1082 old_file = new_filename+'.old'
1083 1083 if os.path.exists(old_file):
1084 1084 os.remove(old_file)
1085 1085 os.rename(new_filename,old_file)
1086 1086 shutil.copy(new_full_path,new_filename)
1087 1087 else:
1088 1088 raise ValueError,'unrecognized mode for install:',`mode`
1089 1089
1090 1090 # Fix line-endings to those native to each platform in the config
1091 1091 # directory.
1092 1092 try:
1093 1093 os.chdir(ipythondir)
1094 1094 except:
1095 1095 print """
1096 1096 Problem: changing to directory %s failed.
1097 1097 Details:
1098 1098 %s
1099 1099
1100 1100 Some configuration files may have incorrect line endings. This should not
1101 1101 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1102 1102 wait()
1103 1103 else:
1104 1104 for fname in glb('ipythonrc*'):
1105 1105 try:
1106 1106 native_line_ends(fname,backup=0)
1107 1107 except IOError:
1108 1108 pass
1109 1109
1110 1110 if mode == 'install':
1111 1111 print """
1112 1112 Successful installation!
1113 1113
1114 1114 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1115 1115 IPython manual (there are both HTML and PDF versions supplied with the
1116 1116 distribution) to make sure that your system environment is properly configured
1117 1117 to take advantage of IPython's features."""
1118 1118 else:
1119 1119 print """
1120 1120 Successful upgrade!
1121 1121
1122 1122 All files in your directory:
1123 1123 %(ipythondir)s
1124 1124 which would have been overwritten by the upgrade were backed up with a .old
1125 1125 extension. If you had made particular customizations in those files you may
1126 1126 want to merge them back into the new files.""" % locals()
1127 1127 wait()
1128 1128 os.chdir(cwd)
1129 1129 # end user_setup()
1130 1130
1131 1131 def atexit_operations(self):
1132 1132 """This will be executed at the time of exit.
1133 1133
1134 1134 Saving of persistent data should be performed here. """
1135 1135
1136 1136 # input history
1137 1137 self.savehist()
1138 1138
1139 1139 # Cleanup all tempfiles left around
1140 1140 for tfile in self.tempfiles:
1141 1141 try:
1142 1142 os.unlink(tfile)
1143 1143 except OSError:
1144 1144 pass
1145 1145
1146 1146 # save the "persistent data" catch-all dictionary
1147 1147 try:
1148 1148 pickle.dump(self.persist, open(self.persist_fname,"w"))
1149 1149 except:
1150 1150 print "*** ERROR *** persistent data saving failed."
1151 1151
1152 1152 def savehist(self):
1153 1153 """Save input history to a file (via readline library)."""
1154 1154 try:
1155 1155 self.readline.write_history_file(self.histfile)
1156 1156 except:
1157 1157 print 'Unable to save IPython command history to file: ' + \
1158 1158 `self.histfile`
1159 1159
1160 1160 def pre_readline(self):
1161 1161 """readline hook to be used at the start of each line.
1162 1162
1163 1163 Currently it handles auto-indent only."""
1164 1164
1165 1165 self.readline.insert_text(' '* self.readline_indent)
1166 1166
1167 1167 def init_readline(self):
1168 1168 """Command history completion/saving/reloading."""
1169 1169 try:
1170 1170 import readline
1171 1171 self.Completer = MagicCompleter(self,
1172 1172 self.user_ns,
1173 1173 self.rc.readline_omit__names,
1174 1174 self.alias_table)
1175 1175 except ImportError,NameError:
1176 1176 # If FlexCompleter failed to import, MagicCompleter won't be
1177 1177 # defined. This can happen because of a problem with readline
1178 1178 self.has_readline = 0
1179 1179 # no point in bugging windows users with this every time:
1180 1180 if os.name == 'posix':
1181 1181 warn('Readline services not available on this platform.')
1182 1182 else:
1183 1183 import atexit
1184 1184
1185 1185 # Platform-specific configuration
1186 1186 if os.name == 'nt':
1187 1187 # readline under Windows modifies the default exit behavior
1188 1188 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1189 1189 __builtin__.exit = __builtin__.quit = \
1190 1190 ('Use Ctrl-D (i.e. EOF) to exit. '
1191 1191 'Use %Exit or %Quit to exit without confirmation.')
1192 1192 self.readline_startup_hook = readline.set_pre_input_hook
1193 1193 else:
1194 1194 self.readline_startup_hook = readline.set_startup_hook
1195 1195
1196 1196 # Load user's initrc file (readline config)
1197 1197 inputrc_name = os.environ.get('INPUTRC')
1198 1198 if inputrc_name is None:
1199 1199 home_dir = get_home_dir()
1200 1200 if home_dir is not None:
1201 1201 inputrc_name = os.path.join(home_dir,'.inputrc')
1202 1202 if os.path.isfile(inputrc_name):
1203 1203 try:
1204 1204 readline.read_init_file(inputrc_name)
1205 1205 except:
1206 1206 warn('Problems reading readline initialization file <%s>'
1207 1207 % inputrc_name)
1208 1208
1209 1209 self.has_readline = 1
1210 1210 self.readline = readline
1211 1211 self.readline_indent = 0 # for auto-indenting via readline
1212 1212 # save this in sys so embedded copies can restore it properly
1213 1213 sys.ipcompleter = self.Completer.complete
1214 1214 readline.set_completer(self.Completer.complete)
1215 1215
1216 1216 # Configure readline according to user's prefs
1217 1217 for rlcommand in self.rc.readline_parse_and_bind:
1218 1218 readline.parse_and_bind(rlcommand)
1219 1219
1220 1220 # remove some chars from the delimiters list
1221 1221 delims = readline.get_completer_delims()
1222 1222 delims = delims.translate(string._idmap,
1223 1223 self.rc.readline_remove_delims)
1224 1224 readline.set_completer_delims(delims)
1225 1225 # otherwise we end up with a monster history after a while:
1226 1226 readline.set_history_length(1000)
1227 1227 try:
1228 1228 #print '*** Reading readline history' # dbg
1229 1229 readline.read_history_file(self.histfile)
1230 1230 except IOError:
1231 1231 pass # It doesn't exist yet.
1232 1232
1233 1233 atexit.register(self.atexit_operations)
1234 1234 del atexit
1235 1235
1236 1236 # Configure auto-indent for all platforms
1237 1237 self.set_autoindent(self.rc.autoindent)
1238 1238
1239 1239 def showsyntaxerror(self, filename=None):
1240 1240 """Display the syntax error that just occurred.
1241 1241
1242 1242 This doesn't display a stack trace because there isn't one.
1243 1243
1244 1244 If a filename is given, it is stuffed in the exception instead
1245 1245 of what was there before (because Python's parser always uses
1246 1246 "<string>" when reading from a string).
1247 1247 """
1248 1248 type, value, sys.last_traceback = sys.exc_info()
1249 1249 sys.last_type = type
1250 1250 sys.last_value = value
1251 1251 if filename and type is SyntaxError:
1252 1252 # Work hard to stuff the correct filename in the exception
1253 1253 try:
1254 1254 msg, (dummy_filename, lineno, offset, line) = value
1255 1255 except:
1256 1256 # Not the format we expect; leave it alone
1257 1257 pass
1258 1258 else:
1259 1259 # Stuff in the right filename
1260 1260 try:
1261 1261 # Assume SyntaxError is a class exception
1262 1262 value = SyntaxError(msg, (filename, lineno, offset, line))
1263 1263 except:
1264 1264 # If that failed, assume SyntaxError is a string
1265 1265 value = msg, (filename, lineno, offset, line)
1266 1266 self.SyntaxTB(type,value,[])
1267 1267
1268 1268 def debugger(self):
1269 1269 """Call the pdb debugger."""
1270 1270
1271 1271 if not self.rc.pdb:
1272 1272 return
1273 1273 pdb.pm()
1274 1274
1275 1275 def showtraceback(self,exc_tuple = None):
1276 1276 """Display the exception that just occurred."""
1277 1277
1278 1278 # Though this won't be called by syntax errors in the input line,
1279 1279 # there may be SyntaxError cases whith imported code.
1280 1280 if exc_tuple is None:
1281 1281 type, value, tb = sys.exc_info()
1282 1282 else:
1283 1283 type, value, tb = exc_tuple
1284 1284 if type is SyntaxError:
1285 1285 self.showsyntaxerror()
1286 1286 else:
1287 1287 sys.last_type = type
1288 1288 sys.last_value = value
1289 1289 sys.last_traceback = tb
1290 1290 self.InteractiveTB()
1291 1291 if self.InteractiveTB.call_pdb and self.has_readline:
1292 1292 # pdb mucks up readline, fix it back
1293 1293 self.readline.set_completer(self.Completer.complete)
1294 1294
1295 1295 def update_cache(self, line):
1296 1296 """puts line into cache"""
1297 1297 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1298 1298 if len(self.inputcache) >= self.CACHELENGTH:
1299 1299 self.inputcache.pop() # This not :-)
1300 1300
1301 1301 def name_space_init(self):
1302 1302 """Create local namespace."""
1303 1303 # We want this to be a method to facilitate embedded initialization.
1304 1304 code.InteractiveConsole.__init__(self,self.user_ns)
1305 1305
1306 1306 def mainloop(self,banner=None):
1307 1307 """Creates the local namespace and starts the mainloop.
1308 1308
1309 1309 If an optional banner argument is given, it will override the
1310 1310 internally created default banner."""
1311 1311
1312 1312 self.name_space_init()
1313 1313 if self.rc.c: # Emulate Python's -c option
1314 1314 self.exec_init_cmd()
1315 1315 if banner is None:
1316 1316 if self.rc.banner:
1317 1317 banner = self.BANNER+self.banner2
1318 1318 else:
1319 1319 banner = ''
1320 1320 self.interact(banner)
1321 1321
1322 1322 def exec_init_cmd(self):
1323 1323 """Execute a command given at the command line.
1324 1324
1325 1325 This emulates Python's -c option."""
1326 1326
1327 1327 sys.argv = ['-c']
1328 1328 self.push(self.rc.c)
1329 1329
1330 1330 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1331 1331 """Embeds IPython into a running python program.
1332 1332
1333 1333 Input:
1334 1334
1335 1335 - header: An optional header message can be specified.
1336 1336
1337 1337 - local_ns, global_ns: working namespaces. If given as None, the
1338 1338 IPython-initialized one is updated with __main__.__dict__, so that
1339 1339 program variables become visible but user-specific configuration
1340 1340 remains possible.
1341 1341
1342 1342 - stack_depth: specifies how many levels in the stack to go to
1343 1343 looking for namespaces (when local_ns and global_ns are None). This
1344 1344 allows an intermediate caller to make sure that this function gets
1345 1345 the namespace from the intended level in the stack. By default (0)
1346 1346 it will get its locals and globals from the immediate caller.
1347 1347
1348 1348 Warning: it's possible to use this in a program which is being run by
1349 1349 IPython itself (via %run), but some funny things will happen (a few
1350 1350 globals get overwritten). In the future this will be cleaned up, as
1351 1351 there is no fundamental reason why it can't work perfectly."""
1352 1352
1353 1353 # Patch for global embedding to make sure that things don't overwrite
1354 1354 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1355 1355 # FIXME. Test this a bit more carefully (the if.. is new)
1356 1356 if local_ns is None and global_ns is None:
1357 1357 self.user_ns.update(__main__.__dict__)
1358 1358
1359 1359 # Get locals and globals from caller
1360 1360 if local_ns is None or global_ns is None:
1361 1361 call_frame = sys._getframe(stack_depth).f_back
1362 1362
1363 1363 if local_ns is None:
1364 1364 local_ns = call_frame.f_locals
1365 1365 if global_ns is None:
1366 1366 global_ns = call_frame.f_globals
1367 1367
1368 1368 # Update namespaces and fire up interpreter
1369 1369 self.user_ns.update(local_ns)
1370 1370 self.interact(header)
1371 1371
1372 1372 # Remove locals from namespace
1373 1373 for k in local_ns:
1374 1374 del self.user_ns[k]
1375 1375
1376 1376 def interact(self, banner=None):
1377 1377 """Closely emulate the interactive Python console.
1378 1378
1379 1379 The optional banner argument specify the banner to print
1380 1380 before the first interaction; by default it prints a banner
1381 1381 similar to the one printed by the real Python interpreter,
1382 1382 followed by the current class name in parentheses (so as not
1383 1383 to confuse this with the real interpreter -- since it's so
1384 1384 close!).
1385 1385
1386 1386 """
1387 1387 cprt = 'Type "copyright", "credits" or "license" for more information.'
1388 1388 if banner is None:
1389 1389 self.write("Python %s on %s\n%s\n(%s)\n" %
1390 1390 (sys.version, sys.platform, cprt,
1391 1391 self.__class__.__name__))
1392 1392 else:
1393 1393 self.write(banner)
1394 1394
1395 1395 more = 0
1396 1396
1397 1397 # Mark activity in the builtins
1398 1398 __builtin__.__dict__['__IPYTHON__active'] += 1
1399 1399
1400 1400 # exit_now is set by a call to %Exit or %Quit
1401 1401 while not self.exit_now:
1402 1402 try:
1403 1403 if more:
1404 1404 prompt = self.outputcache.prompt2
1405 1405 if self.autoindent:
1406 1406 self.readline_startup_hook(self.pre_readline)
1407 1407 else:
1408 1408 prompt = self.outputcache.prompt1
1409 1409 try:
1410 1410 line = self.raw_input(prompt)
1411 1411 if self.autoindent:
1412 1412 self.readline_startup_hook(None)
1413 1413 except EOFError:
1414 1414 if self.autoindent:
1415 1415 self.readline_startup_hook(None)
1416 1416 self.write("\n")
1417 1417 if self.rc.confirm_exit:
1418 1418 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1419 1419 break
1420 1420 else:
1421 1421 break
1422 1422 else:
1423 1423 more = self.push(line)
1424 1424 # Auto-indent management
1425 1425 if self.autoindent:
1426 1426 if line:
1427 1427 ini_spaces = re.match('^(\s+)',line)
1428 1428 if ini_spaces:
1429 1429 nspaces = ini_spaces.end()
1430 1430 else:
1431 1431 nspaces = 0
1432 1432 self.readline_indent = nspaces
1433 1433
1434 1434 if line[-1] == ':':
1435 1435 self.readline_indent += 4
1436 1436 elif re.match(r'^\s+raise|^\s+return',line):
1437 1437 self.readline_indent -= 4
1438 1438 else:
1439 1439 self.readline_indent = 0
1440 1440
1441 1441 except KeyboardInterrupt:
1442 1442 self.write("\nKeyboardInterrupt\n")
1443 1443 self.resetbuffer()
1444 1444 more = 0
1445 1445 # keep cache in sync with the prompt counter:
1446 1446 self.outputcache.prompt_count -= 1
1447 1447
1448 1448 if self.autoindent:
1449 1449 self.readline_indent = 0
1450 1450
1451 1451 except bdb.BdbQuit:
1452 1452 warn("The Python debugger has exited with a BdbQuit exception.\n"
1453 1453 "Because of how pdb handles the stack, it is impossible\n"
1454 1454 "for IPython to properly format this particular exception.\n"
1455 1455 "IPython will resume normal operation.")
1456 1456
1457 1457 # We are off again...
1458 1458 __builtin__.__dict__['__IPYTHON__active'] -= 1
1459 1459
1460 1460 def excepthook(self, type, value, tb):
1461 1461 """One more defense for GUI apps that call sys.excepthook.
1462 1462
1463 1463 GUI frameworks like wxPython trap exceptions and call
1464 1464 sys.excepthook themselves. I guess this is a feature that
1465 1465 enables them to keep running after exceptions that would
1466 1466 otherwise kill their mainloop. This is a bother for IPython
1467 1467 which excepts to catch all of the program exceptions with a try:
1468 1468 except: statement.
1469 1469
1470 1470 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1471 1471 any app directly invokes sys.excepthook, it will look to the user like
1472 1472 IPython crashed. In order to work around this, we can disable the
1473 1473 CrashHandler and replace it with this excepthook instead, which prints a
1474 1474 regular traceback using our InteractiveTB. In this fashion, apps which
1475 1475 call sys.excepthook will generate a regular-looking exception from
1476 1476 IPython, and the CrashHandler will only be triggered by real IPython
1477 1477 crashes.
1478 1478
1479 1479 This hook should be used sparingly, only in places which are not likely
1480 1480 to be true IPython errors.
1481 1481 """
1482 1482
1483 1483 self.InteractiveTB(type, value, tb, tb_offset=0)
1484 1484 if self.InteractiveTB.call_pdb and self.has_readline:
1485 1485 self.readline.set_completer(self.Completer.complete)
1486 1486
1487 1487 def call_alias(self,alias,rest=''):
1488 1488 """Call an alias given its name and the rest of the line.
1489 1489
1490 1490 This function MUST be given a proper alias, because it doesn't make
1491 1491 any checks when looking up into the alias table. The caller is
1492 1492 responsible for invoking it only with a valid alias."""
1493 1493
1494 1494 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1495 1495 nargs,cmd = self.alias_table[alias]
1496 1496 # Expand the %l special to be the user's input line
1497 1497 if cmd.find('%l') >= 0:
1498 1498 cmd = cmd.replace('%l',rest)
1499 1499 rest = ''
1500 1500 if nargs==0:
1501 1501 # Simple, argument-less aliases
1502 1502 cmd = '%s %s' % (cmd,rest)
1503 1503 else:
1504 1504 # Handle aliases with positional arguments
1505 1505 args = rest.split(None,nargs)
1506 1506 if len(args)< nargs:
1507 1507 error('Alias <%s> requires %s arguments, %s given.' %
1508 1508 (alias,nargs,len(args)))
1509 1509 return
1510 1510 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1511 1511 # Now call the macro, evaluating in the user's namespace
1512 1512 try:
1513 1513 self.system(cmd)
1514 1514 except:
1515 1515 self.showtraceback()
1516 1516
1517 1517 def runlines(self,lines):
1518 1518 """Run a string of one or more lines of source.
1519 1519
1520 1520 This method is capable of running a string containing multiple source
1521 1521 lines, as if they had been entered at the IPython prompt. Since it
1522 1522 exposes IPython's processing machinery, the given strings can contain
1523 1523 magic calls (%magic), special shell access (!cmd), etc."""
1524 1524
1525 1525 # We must start with a clean buffer, in case this is run from an
1526 1526 # interactive IPython session (via a magic, for example).
1527 1527 self.resetbuffer()
1528 1528 lines = lines.split('\n')
1529 1529 more = 0
1530 1530 for line in lines:
1531 1531 # skip blank lines so we don't mess up the prompt counter, but do
1532 1532 # NOT skip even a blank line if we are in a code block (more is
1533 1533 # true)
1534 1534 if line or more:
1535 1535 more = self.push((self.prefilter(line,more)))
1536 1536 # IPython's runsource returns None if there was an error
1537 1537 # compiling the code. This allows us to stop processing right
1538 1538 # away, so the user gets the error message at the right place.
1539 1539 if more is None:
1540 1540 break
1541 1541 # final newline in case the input didn't have it, so that the code
1542 1542 # actually does get executed
1543 1543 if more:
1544 1544 self.push('\n')
1545 1545
1546 1546 def runsource(self, source, filename="<input>", symbol="single"):
1547 1547 """Compile and run some source in the interpreter.
1548 1548
1549 1549 Arguments are as for compile_command().
1550 1550
1551 1551 One several things can happen:
1552 1552
1553 1553 1) The input is incorrect; compile_command() raised an
1554 1554 exception (SyntaxError or OverflowError). A syntax traceback
1555 1555 will be printed by calling the showsyntaxerror() method.
1556 1556
1557 1557 2) The input is incomplete, and more input is required;
1558 1558 compile_command() returned None. Nothing happens.
1559 1559
1560 1560 3) The input is complete; compile_command() returned a code
1561 1561 object. The code is executed by calling self.runcode() (which
1562 1562 also handles run-time exceptions, except for SystemExit).
1563 1563
1564 1564 The return value is:
1565 1565
1566 1566 - True in case 2
1567 1567
1568 1568 - False in the other cases, unless an exception is raised, where
1569 1569 None is returned instead. This can be used by external callers to
1570 1570 know whether to continue feeding input or not.
1571 1571
1572 1572 The return value can be used to decide whether to use sys.ps1 or
1573 1573 sys.ps2 to prompt the next line."""
1574 1574
1575 1575 try:
1576 1576 code = self.compile(source, filename, symbol)
1577 1577 except (OverflowError, SyntaxError, ValueError):
1578 1578 # Case 1
1579 1579 self.showsyntaxerror(filename)
1580 1580 return None
1581 1581
1582 1582 if code is None:
1583 1583 # Case 2
1584 1584 return True
1585 1585
1586 1586 # Case 3
1587 1587 # We store the code object so that threaded shells and
1588 1588 # custom exception handlers can access all this info if needed.
1589 1589 # The source corresponding to this can be obtained from the
1590 1590 # buffer attribute as '\n'.join(self.buffer).
1591 1591 self.code_to_run = code
1592 1592 # now actually execute the code object
1593 1593 if self.runcode(code) == 0:
1594 1594 return False
1595 1595 else:
1596 1596 return None
1597 1597
1598 1598 def runcode(self,code_obj):
1599 1599 """Execute a code object.
1600 1600
1601 1601 When an exception occurs, self.showtraceback() is called to display a
1602 1602 traceback.
1603 1603
1604 1604 Return value: a flag indicating whether the code to be run completed
1605 1605 successfully:
1606 1606
1607 1607 - 0: successful execution.
1608 1608 - 1: an error occurred.
1609 1609 """
1610 1610
1611 1611 # Set our own excepthook in case the user code tries to call it
1612 1612 # directly, so that the IPython crash handler doesn't get triggered
1613 1613 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1614 1614 outflag = 1 # happens in more places, so it's easier as default
1615 1615 try:
1616 1616 try:
1617 1617 exec code_obj in self.locals
1618 1618 finally:
1619 1619 # Reset our crash handler in place
1620 1620 sys.excepthook = old_excepthook
1621 1621 except SystemExit:
1622 1622 self.resetbuffer()
1623 1623 self.showtraceback()
1624 1624 warn( __builtin__.exit,level=1)
1625 1625 except self.custom_exceptions:
1626 1626 etype,value,tb = sys.exc_info()
1627 1627 self.CustomTB(etype,value,tb)
1628 1628 except:
1629 1629 self.showtraceback()
1630 1630 else:
1631 1631 outflag = 0
1632 1632 if code.softspace(sys.stdout, 0):
1633 1633 print
1634 1634 # Flush out code object which has been run (and source)
1635 1635 self.code_to_run = None
1636 1636 return outflag
1637 1637
1638 1638 def raw_input(self, prompt=""):
1639 1639 """Write a prompt and read a line.
1640 1640
1641 1641 The returned line does not include the trailing newline.
1642 1642 When the user enters the EOF key sequence, EOFError is raised.
1643 1643
1644 1644 The base implementation uses the built-in function
1645 1645 raw_input(); a subclass may replace this with a different
1646 1646 implementation.
1647 1647 """
1648 1648 return self.prefilter(raw_input_original(prompt),
1649 1649 prompt==self.outputcache.prompt2)
1650 1650
1651 1651 def split_user_input(self,line):
1652 1652 """Split user input into pre-char, function part and rest."""
1653 1653
1654 1654 lsplit = self.line_split.match(line)
1655 1655 if lsplit is None: # no regexp match returns None
1656 1656 try:
1657 1657 iFun,theRest = line.split(None,1)
1658 1658 except ValueError:
1659 1659 iFun,theRest = line,''
1660 1660 pre = re.match('^(\s*)(.*)',line).groups()[0]
1661 1661 else:
1662 1662 pre,iFun,theRest = lsplit.groups()
1663 1663
1664 1664 #print 'line:<%s>' % line # dbg
1665 1665 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1666 1666 return pre,iFun.strip(),theRest
1667 1667
1668 1668 def _prefilter(self, line, continue_prompt):
1669 1669 """Calls different preprocessors, depending on the form of line."""
1670 1670
1671 1671 # All handlers *must* return a value, even if it's blank ('').
1672 1672
1673 1673 # Lines are NOT logged here. Handlers should process the line as
1674 1674 # needed, update the cache AND log it (so that the input cache array
1675 1675 # stays synced).
1676 1676
1677 1677 # This function is _very_ delicate, and since it's also the one which
1678 1678 # determines IPython's response to user input, it must be as efficient
1679 1679 # as possible. For this reason it has _many_ returns in it, trying
1680 1680 # always to exit as quickly as it can figure out what it needs to do.
1681 1681
1682 1682 # This function is the main responsible for maintaining IPython's
1683 1683 # behavior respectful of Python's semantics. So be _very_ careful if
1684 1684 # making changes to anything here.
1685 1685
1686 1686 #.....................................................................
1687 1687 # Code begins
1688 1688
1689 1689 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1690 1690
1691 1691 # save the line away in case we crash, so the post-mortem handler can
1692 1692 # record it
1693 1693 self._last_input_line = line
1694 1694
1695 1695 #print '***line: <%s>' % line # dbg
1696 1696
1697 1697 # the input history needs to track even empty lines
1698 1698 if not line.strip():
1699 1699 if not continue_prompt:
1700 1700 self.outputcache.prompt_count -= 1
1701 1701 return self.handle_normal('',continue_prompt)
1702 1702
1703 1703 # print '***cont',continue_prompt # dbg
1704 1704 # special handlers are only allowed for single line statements
1705 1705 if continue_prompt and not self.rc.multi_line_specials:
1706 1706 return self.handle_normal(line,continue_prompt)
1707 1707
1708 1708 # For the rest, we need the structure of the input
1709 1709 pre,iFun,theRest = self.split_user_input(line)
1710 1710 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1711 1711
1712 1712 # First check for explicit escapes in the last/first character
1713 1713 handler = None
1714 1714 if line[-1] == self.ESC_HELP:
1715 1715 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1716 1716 if handler is None:
1717 1717 # look at the first character of iFun, NOT of line, so we skip
1718 1718 # leading whitespace in multiline input
1719 1719 handler = self.esc_handlers.get(iFun[0:1])
1720 1720 if handler is not None:
1721 1721 return handler(line,continue_prompt,pre,iFun,theRest)
1722 1722 # Emacs ipython-mode tags certain input lines
1723 1723 if line.endswith('# PYTHON-MODE'):
1724 1724 return self.handle_emacs(line,continue_prompt)
1725 1725
1726 1726 # Next, check if we can automatically execute this thing
1727 1727
1728 1728 # Allow ! in multi-line statements if multi_line_specials is on:
1729 1729 if continue_prompt and self.rc.multi_line_specials and \
1730 1730 iFun.startswith(self.ESC_SHELL):
1731 1731 return self.handle_shell_escape(line,continue_prompt,
1732 1732 pre=pre,iFun=iFun,
1733 1733 theRest=theRest)
1734 1734
1735 1735 # Let's try to find if the input line is a magic fn
1736 1736 oinfo = None
1737 1737 if hasattr(self,'magic_'+iFun):
1738 1738 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1739 1739 if oinfo['ismagic']:
1740 1740 # Be careful not to call magics when a variable assignment is
1741 1741 # being made (ls='hi', for example)
1742 1742 if self.rc.automagic and \
1743 1743 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1744 1744 (self.rc.multi_line_specials or not continue_prompt):
1745 1745 return self.handle_magic(line,continue_prompt,
1746 1746 pre,iFun,theRest)
1747 1747 else:
1748 1748 return self.handle_normal(line,continue_prompt)
1749 1749
1750 1750 # If the rest of the line begins with an (in)equality, assginment or
1751 1751 # function call, we should not call _ofind but simply execute it.
1752 1752 # This avoids spurious geattr() accesses on objects upon assignment.
1753 1753 #
1754 1754 # It also allows users to assign to either alias or magic names true
1755 1755 # python variables (the magic/alias systems always take second seat to
1756 1756 # true python code).
1757 1757 if theRest and theRest[0] in '!=()':
1758 1758 return self.handle_normal(line,continue_prompt)
1759 1759
1760 1760 if oinfo is None:
1761 1761 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1762 1762
1763 1763 if not oinfo['found']:
1764 1764 return self.handle_normal(line,continue_prompt)
1765 1765 else:
1766 1766 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1767 1767 if oinfo['isalias']:
1768 1768 return self.handle_alias(line,continue_prompt,
1769 1769 pre,iFun,theRest)
1770 1770
1771 1771 if self.rc.autocall and \
1772 1772 not self.re_exclude_auto.match(theRest) and \
1773 1773 self.re_fun_name.match(iFun) and \
1774 1774 callable(oinfo['obj']) :
1775 1775 #print 'going auto' # dbg
1776 1776 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1777 1777 else:
1778 1778 #print 'was callable?', callable(oinfo['obj']) # dbg
1779 1779 return self.handle_normal(line,continue_prompt)
1780 1780
1781 1781 # If we get here, we have a normal Python line. Log and return.
1782 1782 return self.handle_normal(line,continue_prompt)
1783 1783
1784 1784 def _prefilter_dumb(self, line, continue_prompt):
1785 1785 """simple prefilter function, for debugging"""
1786 1786 return self.handle_normal(line,continue_prompt)
1787 1787
1788 1788 # Set the default prefilter() function (this can be user-overridden)
1789 1789 prefilter = _prefilter
1790 1790
1791 1791 def handle_normal(self,line,continue_prompt=None,
1792 1792 pre=None,iFun=None,theRest=None):
1793 1793 """Handle normal input lines. Use as a template for handlers."""
1794 1794
1795 1795 self.log(line,continue_prompt)
1796 1796 self.update_cache(line)
1797 1797 return line
1798 1798
1799 1799 def handle_alias(self,line,continue_prompt=None,
1800 1800 pre=None,iFun=None,theRest=None):
1801 1801 """Handle alias input lines. """
1802 1802
1803 1803 theRest = esc_quotes(theRest)
1804 1804 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1805 1805 self.log(line_out,continue_prompt)
1806 1806 self.update_cache(line_out)
1807 1807 return line_out
1808 1808
1809 1809 def handle_shell_escape(self, line, continue_prompt=None,
1810 1810 pre=None,iFun=None,theRest=None):
1811 1811 """Execute the line in a shell, empty return value"""
1812 1812
1813 1813 #print 'line in :', `line` # dbg
1814 1814 # Example of a special handler. Others follow a similar pattern.
1815 1815 if continue_prompt: # multi-line statements
1816 1816 if iFun.startswith('!!'):
1817 1817 print 'SyntaxError: !! is not allowed in multiline statements'
1818 1818 return pre
1819 1819 else:
1820 1820 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1821 1821 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1822 1822 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1823 1823 else: # single-line input
1824 1824 if line.startswith('!!'):
1825 1825 # rewrite iFun/theRest to properly hold the call to %sx and
1826 1826 # the actual command to be executed, so handle_magic can work
1827 1827 # correctly
1828 1828 theRest = '%s %s' % (iFun[2:],theRest)
1829 1829 iFun = 'sx'
1830 1830 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1831 1831 continue_prompt,pre,iFun,theRest)
1832 1832 else:
1833 1833 cmd = esc_quotes(line[1:])
1834 1834 line_out = '%s.system("%s")' % (self.name,cmd)
1835 1835 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1836 1836 # update cache/log and return
1837 1837 self.log(line_out,continue_prompt)
1838 1838 self.update_cache(line_out) # readline cache gets normal line
1839 1839 #print 'line out r:', `line_out` # dbg
1840 1840 #print 'line out s:', line_out # dbg
1841 1841 return line_out
1842 1842
1843 1843 def handle_magic(self, line, continue_prompt=None,
1844 1844 pre=None,iFun=None,theRest=None):
1845 1845 """Execute magic functions.
1846 1846
1847 1847 Also log them with a prepended # so the log is clean Python."""
1848 1848
1849 1849 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1850 1850 self.log(cmd,continue_prompt)
1851 1851 self.update_cache(line)
1852 1852 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1853 1853 return cmd
1854 1854
1855 1855 def handle_auto(self, line, continue_prompt=None,
1856 1856 pre=None,iFun=None,theRest=None):
1857 1857 """Hande lines which can be auto-executed, quoting if requested."""
1858 1858
1859 1859 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1860 1860
1861 1861 # This should only be active for single-line input!
1862 1862 if continue_prompt:
1863 1863 return line
1864 1864
1865 1865 if pre == self.ESC_QUOTE:
1866 1866 # Auto-quote splitting on whitespace
1867 newcmd = '%s("%s")\n' % (iFun,'", "'.join(theRest.split()) )
1867 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1868 1868 elif pre == self.ESC_QUOTE2:
1869 1869 # Auto-quote whole string
1870 newcmd = '%s("%s")\n' % (iFun,theRest)
1870 newcmd = '%s("%s")' % (iFun,theRest)
1871 1871 else:
1872 1872 # Auto-paren
1873 1873 if theRest[0:1] in ('=','['):
1874 1874 # Don't autocall in these cases. They can be either
1875 1875 # rebindings of an existing callable's name, or item access
1876 1876 # for an object which is BOTH callable and implements
1877 1877 # __getitem__.
1878 return '%s %s\n' % (iFun,theRest)
1878 return '%s %s' % (iFun,theRest)
1879 1879 if theRest.endswith(';'):
1880 newcmd = '%s(%s);\n' % (iFun.rstrip(),theRest[:-1])
1880 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1881 1881 else:
1882 newcmd = '%s(%s)\n' % (iFun.rstrip(),theRest)
1882 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1883 1883
1884 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd,
1884 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1885 1885 # log what is now valid Python, not the actual user input (without the
1886 1886 # final newline)
1887 self.log(newcmd.strip(),continue_prompt)
1887 self.log(newcmd,continue_prompt)
1888 1888 return newcmd
1889 1889
1890 1890 def handle_help(self, line, continue_prompt=None,
1891 1891 pre=None,iFun=None,theRest=None):
1892 1892 """Try to get some help for the object.
1893 1893
1894 1894 obj? or ?obj -> basic information.
1895 1895 obj?? or ??obj -> more details.
1896 1896 """
1897 1897
1898 1898 # We need to make sure that we don't process lines which would be
1899 1899 # otherwise valid python, such as "x=1 # what?"
1900 1900 try:
1901 1901 code.compile_command(line)
1902 1902 except SyntaxError:
1903 1903 # We should only handle as help stuff which is NOT valid syntax
1904 1904 if line[0]==self.ESC_HELP:
1905 1905 line = line[1:]
1906 1906 elif line[-1]==self.ESC_HELP:
1907 1907 line = line[:-1]
1908 1908 self.log('#?'+line)
1909 1909 self.update_cache(line)
1910 1910 if line:
1911 1911 self.magic_pinfo(line)
1912 1912 else:
1913 1913 page(self.usage,screen_lines=self.rc.screen_length)
1914 1914 return '' # Empty string is needed here!
1915 1915 except:
1916 1916 # Pass any other exceptions through to the normal handler
1917 1917 return self.handle_normal(line,continue_prompt)
1918 1918 else:
1919 1919 # If the code compiles ok, we should handle it normally
1920 1920 return self.handle_normal(line,continue_prompt)
1921 1921
1922 1922 def handle_emacs(self,line,continue_prompt=None,
1923 1923 pre=None,iFun=None,theRest=None):
1924 1924 """Handle input lines marked by python-mode."""
1925 1925
1926 1926 # Currently, nothing is done. Later more functionality can be added
1927 1927 # here if needed.
1928 1928
1929 1929 # The input cache shouldn't be updated
1930 1930
1931 1931 return line
1932 1932
1933 1933 def write(self,data):
1934 1934 """Write a string to the default output"""
1935 1935 Term.cout.write(data)
1936 1936
1937 1937 def write_err(self,data):
1938 1938 """Write a string to the default error output"""
1939 1939 Term.cerr.write(data)
1940 1940
1941 1941 def safe_execfile(self,fname,*where,**kw):
1942 1942 fname = os.path.expanduser(fname)
1943 1943
1944 1944 # find things also in current directory
1945 1945 dname = os.path.dirname(fname)
1946 1946 if not sys.path.count(dname):
1947 1947 sys.path.append(dname)
1948 1948
1949 1949 try:
1950 1950 xfile = open(fname)
1951 1951 except:
1952 1952 print >> Term.cerr, \
1953 1953 'Could not open file <%s> for safe execution.' % fname
1954 1954 return None
1955 1955
1956 1956 kw.setdefault('islog',0)
1957 1957 kw.setdefault('quiet',1)
1958 1958 kw.setdefault('exit_ignore',0)
1959 1959 first = xfile.readline()
1960 1960 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1961 1961 xfile.close()
1962 1962 # line by line execution
1963 1963 if first.startswith(_LOGHEAD) or kw['islog']:
1964 1964 print 'Loading log file <%s> one line at a time...' % fname
1965 1965 if kw['quiet']:
1966 1966 stdout_save = sys.stdout
1967 1967 sys.stdout = StringIO.StringIO()
1968 1968 try:
1969 1969 globs,locs = where[0:2]
1970 1970 except:
1971 1971 try:
1972 1972 globs = locs = where[0]
1973 1973 except:
1974 1974 globs = locs = globals()
1975 1975 badblocks = []
1976 1976
1977 1977 # we also need to identify indented blocks of code when replaying
1978 1978 # logs and put them together before passing them to an exec
1979 1979 # statement. This takes a bit of regexp and look-ahead work in the
1980 1980 # file. It's easiest if we swallow the whole thing in memory
1981 1981 # first, and manually walk through the lines list moving the
1982 1982 # counter ourselves.
1983 1983 indent_re = re.compile('\s+\S')
1984 1984 xfile = open(fname)
1985 1985 filelines = xfile.readlines()
1986 1986 xfile.close()
1987 1987 nlines = len(filelines)
1988 1988 lnum = 0
1989 1989 while lnum < nlines:
1990 1990 line = filelines[lnum]
1991 1991 lnum += 1
1992 1992 # don't re-insert logger status info into cache
1993 1993 if line.startswith('#log#'):
1994 1994 continue
1995 1995 elif line.startswith('#%s'% self.ESC_MAGIC):
1996 1996 self.update_cache(line[1:])
1997 1997 line = magic2python(line)
1998 1998 elif line.startswith('#!'):
1999 1999 self.update_cache(line[1:])
2000 2000 else:
2001 2001 # build a block of code (maybe a single line) for execution
2002 2002 block = line
2003 2003 try:
2004 2004 next = filelines[lnum] # lnum has already incremented
2005 2005 except:
2006 2006 next = None
2007 2007 while next and indent_re.match(next):
2008 2008 block += next
2009 2009 lnum += 1
2010 2010 try:
2011 2011 next = filelines[lnum]
2012 2012 except:
2013 2013 next = None
2014 2014 # now execute the block of one or more lines
2015 2015 try:
2016 2016 exec block in globs,locs
2017 2017 self.update_cache(block.rstrip())
2018 2018 except SystemExit:
2019 2019 pass
2020 2020 except:
2021 2021 badblocks.append(block.rstrip())
2022 2022 if kw['quiet']: # restore stdout
2023 2023 sys.stdout.close()
2024 2024 sys.stdout = stdout_save
2025 2025 print 'Finished replaying log file <%s>' % fname
2026 2026 if badblocks:
2027 2027 print >> sys.stderr, \
2028 2028 '\nThe following lines/blocks in file <%s> reported errors:' \
2029 2029 % fname
2030 2030 for badline in badblocks:
2031 2031 print >> sys.stderr, badline
2032 2032 else: # regular file execution
2033 2033 try:
2034 2034 execfile(fname,*where)
2035 2035 except SyntaxError:
2036 2036 etype, evalue = sys.exc_info()[0:2]
2037 2037 self.SyntaxTB(etype,evalue,[])
2038 2038 warn('Failure executing file: <%s>' % fname)
2039 2039 except SystemExit,status:
2040 2040 if not kw['exit_ignore']:
2041 2041 self.InteractiveTB()
2042 2042 warn('Failure executing file: <%s>' % fname)
2043 2043 except:
2044 2044 self.InteractiveTB()
2045 2045 warn('Failure executing file: <%s>' % fname)
2046 2046
2047 2047 #************************* 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