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