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