##// END OF EJS Templates
add .meta namespace for extension writers.
fperez -
Show More

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

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