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