##// END OF EJS Templates
Fix crash with a naked 'alias' call in ipythonrc file.
fperez -
Show More

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

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