##// END OF EJS Templates
Remove alias machinery from IPCompleter
Thomas Kluyver -
Show More
@@ -1,979 +1,955 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 Original rlcompleter documentation:
9 Original rlcompleter documentation:
10
10
11 This requires the latest extension to the readline module (the
11 This requires the latest extension to the readline module (the
12 completes keywords, built-ins and globals in __main__; when completing
12 completes keywords, built-ins and globals in __main__; when completing
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 completes its attributes.
14 completes its attributes.
15
15
16 It's very cool to do "import string" type "string.", hit the
16 It's very cool to do "import string" type "string.", hit the
17 completion key (twice), and see the list of names defined by the
17 completion key (twice), and see the list of names defined by the
18 string module!
18 string module!
19
19
20 Tip: to use the tab key as the completion key, call
20 Tip: to use the tab key as the completion key, call
21
21
22 readline.parse_and_bind("tab: complete")
22 readline.parse_and_bind("tab: complete")
23
23
24 Notes:
24 Notes:
25
25
26 - Exceptions raised by the completer function are *ignored* (and
26 - Exceptions raised by the completer function are *ignored* (and
27 generally cause the completion to fail). This is a feature -- since
27 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
30 reset and restore the tty state.
31
31
32 - The evaluation of the NAME.NAME... form may cause arbitrary
32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 application defined code to be executed if an object with a
33 application defined code to be executed if an object with a
34 ``__getattr__`` hook is found. Since it is the responsibility of the
34 ``__getattr__`` hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
37 indexing operations) are *not* evaluated.
38
38
39 - GNU readline is also used by the built-in functions input() and
39 - GNU readline is also used by the built-in functions input() and
40 raw_input(), and thus these also benefit/suffer from the completer
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
42 specifying its own completer function and using raw_input() for all
43 its input.
43 its input.
44
44
45 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
47 """
47 """
48
48
49 #*****************************************************************************
49 #*****************************************************************************
50 #
50 #
51 # Since this file is essentially a minimally modified copy of the rlcompleter
51 # Since this file is essentially a minimally modified copy of the rlcompleter
52 # module which is part of the standard Python distribution, I assume that the
52 # module which is part of the standard Python distribution, I assume that the
53 # proper procedure is to maintain its copyright as belonging to the Python
53 # proper procedure is to maintain its copyright as belonging to the Python
54 # Software Foundation (in addition to my own, for all new code).
54 # Software Foundation (in addition to my own, for all new code).
55 #
55 #
56 # Copyright (C) 2008 IPython Development Team
56 # Copyright (C) 2008 IPython Development Team
57 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
57 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #
62 #
63 #*****************************************************************************
63 #*****************************************************************************
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Imports
66 # Imports
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 import __builtin__
69 import __builtin__
70 import __main__
70 import __main__
71 import glob
71 import glob
72 import inspect
72 import inspect
73 import itertools
73 import itertools
74 import keyword
74 import keyword
75 import os
75 import os
76 import re
76 import re
77 import sys
77 import sys
78
78
79 from IPython.config.configurable import Configurable
79 from IPython.config.configurable import Configurable
80 from IPython.core.error import TryNext
80 from IPython.core.error import TryNext
81 from IPython.core.inputsplitter import ESC_MAGIC
81 from IPython.core.inputsplitter import ESC_MAGIC
82 from IPython.utils import generics
82 from IPython.utils import generics
83 from IPython.utils import io
83 from IPython.utils import io
84 from IPython.utils.dir2 import dir2
84 from IPython.utils.dir2 import dir2
85 from IPython.utils.process import arg_split
85 from IPython.utils.process import arg_split
86 from IPython.utils.traitlets import CBool, Enum
86 from IPython.utils.traitlets import CBool, Enum
87
87
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89 # Globals
89 # Globals
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91
91
92 # Public API
92 # Public API
93 __all__ = ['Completer','IPCompleter']
93 __all__ = ['Completer','IPCompleter']
94
94
95 if sys.platform == 'win32':
95 if sys.platform == 'win32':
96 PROTECTABLES = ' '
96 PROTECTABLES = ' '
97 else:
97 else:
98 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
98 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
99
99
100 #-----------------------------------------------------------------------------
100 #-----------------------------------------------------------------------------
101 # Main functions and classes
101 # Main functions and classes
102 #-----------------------------------------------------------------------------
102 #-----------------------------------------------------------------------------
103
103
104 def has_open_quotes(s):
104 def has_open_quotes(s):
105 """Return whether a string has open quotes.
105 """Return whether a string has open quotes.
106
106
107 This simply counts whether the number of quote characters of either type in
107 This simply counts whether the number of quote characters of either type in
108 the string is odd.
108 the string is odd.
109
109
110 Returns
110 Returns
111 -------
111 -------
112 If there is an open quote, the quote character is returned. Else, return
112 If there is an open quote, the quote character is returned. Else, return
113 False.
113 False.
114 """
114 """
115 # We check " first, then ', so complex cases with nested quotes will get
115 # We check " first, then ', so complex cases with nested quotes will get
116 # the " to take precedence.
116 # the " to take precedence.
117 if s.count('"') % 2:
117 if s.count('"') % 2:
118 return '"'
118 return '"'
119 elif s.count("'") % 2:
119 elif s.count("'") % 2:
120 return "'"
120 return "'"
121 else:
121 else:
122 return False
122 return False
123
123
124
124
125 def protect_filename(s):
125 def protect_filename(s):
126 """Escape a string to protect certain characters."""
126 """Escape a string to protect certain characters."""
127
127
128 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
128 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
129 for ch in s])
129 for ch in s])
130
130
131 def expand_user(path):
131 def expand_user(path):
132 """Expand '~'-style usernames in strings.
132 """Expand '~'-style usernames in strings.
133
133
134 This is similar to :func:`os.path.expanduser`, but it computes and returns
134 This is similar to :func:`os.path.expanduser`, but it computes and returns
135 extra information that will be useful if the input was being used in
135 extra information that will be useful if the input was being used in
136 computing completions, and you wish to return the completions with the
136 computing completions, and you wish to return the completions with the
137 original '~' instead of its expanded value.
137 original '~' instead of its expanded value.
138
138
139 Parameters
139 Parameters
140 ----------
140 ----------
141 path : str
141 path : str
142 String to be expanded. If no ~ is present, the output is the same as the
142 String to be expanded. If no ~ is present, the output is the same as the
143 input.
143 input.
144
144
145 Returns
145 Returns
146 -------
146 -------
147 newpath : str
147 newpath : str
148 Result of ~ expansion in the input path.
148 Result of ~ expansion in the input path.
149 tilde_expand : bool
149 tilde_expand : bool
150 Whether any expansion was performed or not.
150 Whether any expansion was performed or not.
151 tilde_val : str
151 tilde_val : str
152 The value that ~ was replaced with.
152 The value that ~ was replaced with.
153 """
153 """
154 # Default values
154 # Default values
155 tilde_expand = False
155 tilde_expand = False
156 tilde_val = ''
156 tilde_val = ''
157 newpath = path
157 newpath = path
158
158
159 if path.startswith('~'):
159 if path.startswith('~'):
160 tilde_expand = True
160 tilde_expand = True
161 rest = len(path)-1
161 rest = len(path)-1
162 newpath = os.path.expanduser(path)
162 newpath = os.path.expanduser(path)
163 if rest:
163 if rest:
164 tilde_val = newpath[:-rest]
164 tilde_val = newpath[:-rest]
165 else:
165 else:
166 tilde_val = newpath
166 tilde_val = newpath
167
167
168 return newpath, tilde_expand, tilde_val
168 return newpath, tilde_expand, tilde_val
169
169
170
170
171 def compress_user(path, tilde_expand, tilde_val):
171 def compress_user(path, tilde_expand, tilde_val):
172 """Does the opposite of expand_user, with its outputs.
172 """Does the opposite of expand_user, with its outputs.
173 """
173 """
174 if tilde_expand:
174 if tilde_expand:
175 return path.replace(tilde_val, '~')
175 return path.replace(tilde_val, '~')
176 else:
176 else:
177 return path
177 return path
178
178
179
179
180 class Bunch(object): pass
180 class Bunch(object): pass
181
181
182
182
183 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
183 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
184 GREEDY_DELIMS = ' =\r\n'
184 GREEDY_DELIMS = ' =\r\n'
185
185
186
186
187 class CompletionSplitter(object):
187 class CompletionSplitter(object):
188 """An object to split an input line in a manner similar to readline.
188 """An object to split an input line in a manner similar to readline.
189
189
190 By having our own implementation, we can expose readline-like completion in
190 By having our own implementation, we can expose readline-like completion in
191 a uniform manner to all frontends. This object only needs to be given the
191 a uniform manner to all frontends. This object only needs to be given the
192 line of text to be split and the cursor position on said line, and it
192 line of text to be split and the cursor position on said line, and it
193 returns the 'word' to be completed on at the cursor after splitting the
193 returns the 'word' to be completed on at the cursor after splitting the
194 entire line.
194 entire line.
195
195
196 What characters are used as splitting delimiters can be controlled by
196 What characters are used as splitting delimiters can be controlled by
197 setting the `delims` attribute (this is a property that internally
197 setting the `delims` attribute (this is a property that internally
198 automatically builds the necessary regular expression)"""
198 automatically builds the necessary regular expression)"""
199
199
200 # Private interface
200 # Private interface
201
201
202 # A string of delimiter characters. The default value makes sense for
202 # A string of delimiter characters. The default value makes sense for
203 # IPython's most typical usage patterns.
203 # IPython's most typical usage patterns.
204 _delims = DELIMS
204 _delims = DELIMS
205
205
206 # The expression (a normal string) to be compiled into a regular expression
206 # The expression (a normal string) to be compiled into a regular expression
207 # for actual splitting. We store it as an attribute mostly for ease of
207 # for actual splitting. We store it as an attribute mostly for ease of
208 # debugging, since this type of code can be so tricky to debug.
208 # debugging, since this type of code can be so tricky to debug.
209 _delim_expr = None
209 _delim_expr = None
210
210
211 # The regular expression that does the actual splitting
211 # The regular expression that does the actual splitting
212 _delim_re = None
212 _delim_re = None
213
213
214 def __init__(self, delims=None):
214 def __init__(self, delims=None):
215 delims = CompletionSplitter._delims if delims is None else delims
215 delims = CompletionSplitter._delims if delims is None else delims
216 self.delims = delims
216 self.delims = delims
217
217
218 @property
218 @property
219 def delims(self):
219 def delims(self):
220 """Return the string of delimiter characters."""
220 """Return the string of delimiter characters."""
221 return self._delims
221 return self._delims
222
222
223 @delims.setter
223 @delims.setter
224 def delims(self, delims):
224 def delims(self, delims):
225 """Set the delimiters for line splitting."""
225 """Set the delimiters for line splitting."""
226 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
226 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
227 self._delim_re = re.compile(expr)
227 self._delim_re = re.compile(expr)
228 self._delims = delims
228 self._delims = delims
229 self._delim_expr = expr
229 self._delim_expr = expr
230
230
231 def split_line(self, line, cursor_pos=None):
231 def split_line(self, line, cursor_pos=None):
232 """Split a line of text with a cursor at the given position.
232 """Split a line of text with a cursor at the given position.
233 """
233 """
234 l = line if cursor_pos is None else line[:cursor_pos]
234 l = line if cursor_pos is None else line[:cursor_pos]
235 return self._delim_re.split(l)[-1]
235 return self._delim_re.split(l)[-1]
236
236
237
237
238 class Completer(Configurable):
238 class Completer(Configurable):
239
239
240 greedy = CBool(False, config=True,
240 greedy = CBool(False, config=True,
241 help="""Activate greedy completion
241 help="""Activate greedy completion
242
242
243 This will enable completion on elements of lists, results of function calls, etc.,
243 This will enable completion on elements of lists, results of function calls, etc.,
244 but can be unsafe because the code is actually evaluated on TAB.
244 but can be unsafe because the code is actually evaluated on TAB.
245 """
245 """
246 )
246 )
247
247
248
248
249 def __init__(self, namespace=None, global_namespace=None, **kwargs):
249 def __init__(self, namespace=None, global_namespace=None, **kwargs):
250 """Create a new completer for the command line.
250 """Create a new completer for the command line.
251
251
252 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
252 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
253
253
254 If unspecified, the default namespace where completions are performed
254 If unspecified, the default namespace where completions are performed
255 is __main__ (technically, __main__.__dict__). Namespaces should be
255 is __main__ (technically, __main__.__dict__). Namespaces should be
256 given as dictionaries.
256 given as dictionaries.
257
257
258 An optional second namespace can be given. This allows the completer
258 An optional second namespace can be given. This allows the completer
259 to handle cases where both the local and global scopes need to be
259 to handle cases where both the local and global scopes need to be
260 distinguished.
260 distinguished.
261
261
262 Completer instances should be used as the completion mechanism of
262 Completer instances should be used as the completion mechanism of
263 readline via the set_completer() call:
263 readline via the set_completer() call:
264
264
265 readline.set_completer(Completer(my_namespace).complete)
265 readline.set_completer(Completer(my_namespace).complete)
266 """
266 """
267
267
268 # Don't bind to namespace quite yet, but flag whether the user wants a
268 # Don't bind to namespace quite yet, but flag whether the user wants a
269 # specific namespace or to use __main__.__dict__. This will allow us
269 # specific namespace or to use __main__.__dict__. This will allow us
270 # to bind to __main__.__dict__ at completion time, not now.
270 # to bind to __main__.__dict__ at completion time, not now.
271 if namespace is None:
271 if namespace is None:
272 self.use_main_ns = 1
272 self.use_main_ns = 1
273 else:
273 else:
274 self.use_main_ns = 0
274 self.use_main_ns = 0
275 self.namespace = namespace
275 self.namespace = namespace
276
276
277 # The global namespace, if given, can be bound directly
277 # The global namespace, if given, can be bound directly
278 if global_namespace is None:
278 if global_namespace is None:
279 self.global_namespace = {}
279 self.global_namespace = {}
280 else:
280 else:
281 self.global_namespace = global_namespace
281 self.global_namespace = global_namespace
282
282
283 super(Completer, self).__init__(**kwargs)
283 super(Completer, self).__init__(**kwargs)
284
284
285 def complete(self, text, state):
285 def complete(self, text, state):
286 """Return the next possible completion for 'text'.
286 """Return the next possible completion for 'text'.
287
287
288 This is called successively with state == 0, 1, 2, ... until it
288 This is called successively with state == 0, 1, 2, ... until it
289 returns None. The completion should begin with 'text'.
289 returns None. The completion should begin with 'text'.
290
290
291 """
291 """
292 if self.use_main_ns:
292 if self.use_main_ns:
293 self.namespace = __main__.__dict__
293 self.namespace = __main__.__dict__
294
294
295 if state == 0:
295 if state == 0:
296 if "." in text:
296 if "." in text:
297 self.matches = self.attr_matches(text)
297 self.matches = self.attr_matches(text)
298 else:
298 else:
299 self.matches = self.global_matches(text)
299 self.matches = self.global_matches(text)
300 try:
300 try:
301 return self.matches[state]
301 return self.matches[state]
302 except IndexError:
302 except IndexError:
303 return None
303 return None
304
304
305 def global_matches(self, text):
305 def global_matches(self, text):
306 """Compute matches when text is a simple name.
306 """Compute matches when text is a simple name.
307
307
308 Return a list of all keywords, built-in functions and names currently
308 Return a list of all keywords, built-in functions and names currently
309 defined in self.namespace or self.global_namespace that match.
309 defined in self.namespace or self.global_namespace that match.
310
310
311 """
311 """
312 #print 'Completer->global_matches, txt=%r' % text # dbg
312 #print 'Completer->global_matches, txt=%r' % text # dbg
313 matches = []
313 matches = []
314 match_append = matches.append
314 match_append = matches.append
315 n = len(text)
315 n = len(text)
316 for lst in [keyword.kwlist,
316 for lst in [keyword.kwlist,
317 __builtin__.__dict__.keys(),
317 __builtin__.__dict__.keys(),
318 self.namespace.keys(),
318 self.namespace.keys(),
319 self.global_namespace.keys()]:
319 self.global_namespace.keys()]:
320 for word in lst:
320 for word in lst:
321 if word[:n] == text and word != "__builtins__":
321 if word[:n] == text and word != "__builtins__":
322 match_append(word)
322 match_append(word)
323 return matches
323 return matches
324
324
325 def attr_matches(self, text):
325 def attr_matches(self, text):
326 """Compute matches when text contains a dot.
326 """Compute matches when text contains a dot.
327
327
328 Assuming the text is of the form NAME.NAME....[NAME], and is
328 Assuming the text is of the form NAME.NAME....[NAME], and is
329 evaluatable in self.namespace or self.global_namespace, it will be
329 evaluatable in self.namespace or self.global_namespace, it will be
330 evaluated and its attributes (as revealed by dir()) are used as
330 evaluated and its attributes (as revealed by dir()) are used as
331 possible completions. (For class instances, class members are are
331 possible completions. (For class instances, class members are are
332 also considered.)
332 also considered.)
333
333
334 WARNING: this can still invoke arbitrary C code, if an object
334 WARNING: this can still invoke arbitrary C code, if an object
335 with a __getattr__ hook is evaluated.
335 with a __getattr__ hook is evaluated.
336
336
337 """
337 """
338
338
339 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
339 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
340 # Another option, seems to work great. Catches things like ''.<tab>
340 # Another option, seems to work great. Catches things like ''.<tab>
341 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
341 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
342
342
343 if m:
343 if m:
344 expr, attr = m.group(1, 3)
344 expr, attr = m.group(1, 3)
345 elif self.greedy:
345 elif self.greedy:
346 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
346 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
347 if not m2:
347 if not m2:
348 return []
348 return []
349 expr, attr = m2.group(1,2)
349 expr, attr = m2.group(1,2)
350 else:
350 else:
351 return []
351 return []
352
352
353 try:
353 try:
354 obj = eval(expr, self.namespace)
354 obj = eval(expr, self.namespace)
355 except:
355 except:
356 try:
356 try:
357 obj = eval(expr, self.global_namespace)
357 obj = eval(expr, self.global_namespace)
358 except:
358 except:
359 return []
359 return []
360
360
361 if self.limit_to__all__ and hasattr(obj, '__all__'):
361 if self.limit_to__all__ and hasattr(obj, '__all__'):
362 words = get__all__entries(obj)
362 words = get__all__entries(obj)
363 else:
363 else:
364 words = dir2(obj)
364 words = dir2(obj)
365
365
366 try:
366 try:
367 words = generics.complete_object(obj, words)
367 words = generics.complete_object(obj, words)
368 except TryNext:
368 except TryNext:
369 pass
369 pass
370 except Exception:
370 except Exception:
371 # Silence errors from completion function
371 # Silence errors from completion function
372 #raise # dbg
372 #raise # dbg
373 pass
373 pass
374 # Build match list to return
374 # Build match list to return
375 n = len(attr)
375 n = len(attr)
376 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
376 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
377 return res
377 return res
378
378
379
379
380 def get__all__entries(obj):
380 def get__all__entries(obj):
381 """returns the strings in the __all__ attribute"""
381 """returns the strings in the __all__ attribute"""
382 try:
382 try:
383 words = getattr(obj, '__all__')
383 words = getattr(obj, '__all__')
384 except:
384 except:
385 return []
385 return []
386
386
387 return [w for w in words if isinstance(w, basestring)]
387 return [w for w in words if isinstance(w, basestring)]
388
388
389
389
390 class IPCompleter(Completer):
390 class IPCompleter(Completer):
391 """Extension of the completer class with IPython-specific features"""
391 """Extension of the completer class with IPython-specific features"""
392
392
393 def _greedy_changed(self, name, old, new):
393 def _greedy_changed(self, name, old, new):
394 """update the splitter and readline delims when greedy is changed"""
394 """update the splitter and readline delims when greedy is changed"""
395 if new:
395 if new:
396 self.splitter.delims = GREEDY_DELIMS
396 self.splitter.delims = GREEDY_DELIMS
397 else:
397 else:
398 self.splitter.delims = DELIMS
398 self.splitter.delims = DELIMS
399
399
400 if self.readline:
400 if self.readline:
401 self.readline.set_completer_delims(self.splitter.delims)
401 self.readline.set_completer_delims(self.splitter.delims)
402
402
403 merge_completions = CBool(True, config=True,
403 merge_completions = CBool(True, config=True,
404 help="""Whether to merge completion results into a single list
404 help="""Whether to merge completion results into a single list
405
405
406 If False, only the completion results from the first non-empty
406 If False, only the completion results from the first non-empty
407 completer will be returned.
407 completer will be returned.
408 """
408 """
409 )
409 )
410 omit__names = Enum((0,1,2), default_value=2, config=True,
410 omit__names = Enum((0,1,2), default_value=2, config=True,
411 help="""Instruct the completer to omit private method names
411 help="""Instruct the completer to omit private method names
412
412
413 Specifically, when completing on ``object.<tab>``.
413 Specifically, when completing on ``object.<tab>``.
414
414
415 When 2 [default]: all names that start with '_' will be excluded.
415 When 2 [default]: all names that start with '_' will be excluded.
416
416
417 When 1: all 'magic' names (``__foo__``) will be excluded.
417 When 1: all 'magic' names (``__foo__``) will be excluded.
418
418
419 When 0: nothing will be excluded.
419 When 0: nothing will be excluded.
420 """
420 """
421 )
421 )
422 limit_to__all__ = CBool(default_value=False, config=True,
422 limit_to__all__ = CBool(default_value=False, config=True,
423 help="""Instruct the completer to use __all__ for the completion
423 help="""Instruct the completer to use __all__ for the completion
424
424
425 Specifically, when completing on ``object.<tab>``.
425 Specifically, when completing on ``object.<tab>``.
426
426
427 When True: only those names in obj.__all__ will be included.
427 When True: only those names in obj.__all__ will be included.
428
428
429 When False [default]: the __all__ attribute is ignored
429 When False [default]: the __all__ attribute is ignored
430 """
430 """
431 )
431 )
432
432
433 def __init__(self, shell=None, namespace=None, global_namespace=None,
433 def __init__(self, shell=None, namespace=None, global_namespace=None,
434 alias_table=None, use_readline=True,
434 use_readline=True, config=None, **kwargs):
435 config=None, **kwargs):
436 """IPCompleter() -> completer
435 """IPCompleter() -> completer
437
436
438 Return a completer object suitable for use by the readline library
437 Return a completer object suitable for use by the readline library
439 via readline.set_completer().
438 via readline.set_completer().
440
439
441 Inputs:
440 Inputs:
442
441
443 - shell: a pointer to the ipython shell itself. This is needed
442 - shell: a pointer to the ipython shell itself. This is needed
444 because this completer knows about magic functions, and those can
443 because this completer knows about magic functions, and those can
445 only be accessed via the ipython instance.
444 only be accessed via the ipython instance.
446
445
447 - namespace: an optional dict where completions are performed.
446 - namespace: an optional dict where completions are performed.
448
447
449 - global_namespace: secondary optional dict for completions, to
448 - global_namespace: secondary optional dict for completions, to
450 handle cases (such as IPython embedded inside functions) where
449 handle cases (such as IPython embedded inside functions) where
451 both Python scopes are visible.
450 both Python scopes are visible.
452
451
453 - If alias_table is supplied, it should be a dictionary of aliases
454 to complete.
455
456 use_readline : bool, optional
452 use_readline : bool, optional
457 If true, use the readline library. This completer can still function
453 If true, use the readline library. This completer can still function
458 without readline, though in that case callers must provide some extra
454 without readline, though in that case callers must provide some extra
459 information on each call about the current line."""
455 information on each call about the current line."""
460
456
461 self.magic_escape = ESC_MAGIC
457 self.magic_escape = ESC_MAGIC
462 self.splitter = CompletionSplitter()
458 self.splitter = CompletionSplitter()
463
459
464 # Readline configuration, only used by the rlcompleter method.
460 # Readline configuration, only used by the rlcompleter method.
465 if use_readline:
461 if use_readline:
466 # We store the right version of readline so that later code
462 # We store the right version of readline so that later code
467 import IPython.utils.rlineimpl as readline
463 import IPython.utils.rlineimpl as readline
468 self.readline = readline
464 self.readline = readline
469 else:
465 else:
470 self.readline = None
466 self.readline = None
471
467
472 # _greedy_changed() depends on splitter and readline being defined:
468 # _greedy_changed() depends on splitter and readline being defined:
473 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
469 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
474 config=config, **kwargs)
470 config=config, **kwargs)
475
471
476 # List where completion matches will be stored
472 # List where completion matches will be stored
477 self.matches = []
473 self.matches = []
478 self.shell = shell
474 self.shell = shell
479 if alias_table is None:
480 alias_table = {}
481 self.alias_table = alias_table
482 # Regexp to split filenames with spaces in them
475 # Regexp to split filenames with spaces in them
483 self.space_name_re = re.compile(r'([^\\] )')
476 self.space_name_re = re.compile(r'([^\\] )')
484 # Hold a local ref. to glob.glob for speed
477 # Hold a local ref. to glob.glob for speed
485 self.glob = glob.glob
478 self.glob = glob.glob
486
479
487 # Determine if we are running on 'dumb' terminals, like (X)Emacs
480 # Determine if we are running on 'dumb' terminals, like (X)Emacs
488 # buffers, to avoid completion problems.
481 # buffers, to avoid completion problems.
489 term = os.environ.get('TERM','xterm')
482 term = os.environ.get('TERM','xterm')
490 self.dumb_terminal = term in ['dumb','emacs']
483 self.dumb_terminal = term in ['dumb','emacs']
491
484
492 # Special handling of backslashes needed in win32 platforms
485 # Special handling of backslashes needed in win32 platforms
493 if sys.platform == "win32":
486 if sys.platform == "win32":
494 self.clean_glob = self._clean_glob_win32
487 self.clean_glob = self._clean_glob_win32
495 else:
488 else:
496 self.clean_glob = self._clean_glob
489 self.clean_glob = self._clean_glob
497
490
498 #regexp to parse docstring for function signature
491 #regexp to parse docstring for function signature
499 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
492 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
500 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
493 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
501 #use this if positional argument name is also needed
494 #use this if positional argument name is also needed
502 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
495 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
503
496
504 # All active matcher routines for completion
497 # All active matcher routines for completion
505 self.matchers = [self.python_matches,
498 self.matchers = [self.python_matches,
506 self.file_matches,
499 self.file_matches,
507 self.magic_matches,
500 self.magic_matches,
508 self.alias_matches,
509 self.python_func_kw_matches,
501 self.python_func_kw_matches,
510 ]
502 ]
511
503
512 def all_completions(self, text):
504 def all_completions(self, text):
513 """
505 """
514 Wrapper around the complete method for the benefit of emacs
506 Wrapper around the complete method for the benefit of emacs
515 and pydb.
507 and pydb.
516 """
508 """
517 return self.complete(text)[1]
509 return self.complete(text)[1]
518
510
519 def _clean_glob(self,text):
511 def _clean_glob(self,text):
520 return self.glob("%s*" % text)
512 return self.glob("%s*" % text)
521
513
522 def _clean_glob_win32(self,text):
514 def _clean_glob_win32(self,text):
523 return [f.replace("\\","/")
515 return [f.replace("\\","/")
524 for f in self.glob("%s*" % text)]
516 for f in self.glob("%s*" % text)]
525
517
526 def file_matches(self, text):
518 def file_matches(self, text):
527 """Match filenames, expanding ~USER type strings.
519 """Match filenames, expanding ~USER type strings.
528
520
529 Most of the seemingly convoluted logic in this completer is an
521 Most of the seemingly convoluted logic in this completer is an
530 attempt to handle filenames with spaces in them. And yet it's not
522 attempt to handle filenames with spaces in them. And yet it's not
531 quite perfect, because Python's readline doesn't expose all of the
523 quite perfect, because Python's readline doesn't expose all of the
532 GNU readline details needed for this to be done correctly.
524 GNU readline details needed for this to be done correctly.
533
525
534 For a filename with a space in it, the printed completions will be
526 For a filename with a space in it, the printed completions will be
535 only the parts after what's already been typed (instead of the
527 only the parts after what's already been typed (instead of the
536 full completions, as is normally done). I don't think with the
528 full completions, as is normally done). I don't think with the
537 current (as of Python 2.3) Python readline it's possible to do
529 current (as of Python 2.3) Python readline it's possible to do
538 better."""
530 better."""
539
531
540 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
532 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
541
533
542 # chars that require escaping with backslash - i.e. chars
534 # chars that require escaping with backslash - i.e. chars
543 # that readline treats incorrectly as delimiters, but we
535 # that readline treats incorrectly as delimiters, but we
544 # don't want to treat as delimiters in filename matching
536 # don't want to treat as delimiters in filename matching
545 # when escaped with backslash
537 # when escaped with backslash
546 if text.startswith('!'):
538 if text.startswith('!'):
547 text = text[1:]
539 text = text[1:]
548 text_prefix = '!'
540 text_prefix = '!'
549 else:
541 else:
550 text_prefix = ''
542 text_prefix = ''
551
543
552 text_until_cursor = self.text_until_cursor
544 text_until_cursor = self.text_until_cursor
553 # track strings with open quotes
545 # track strings with open quotes
554 open_quotes = has_open_quotes(text_until_cursor)
546 open_quotes = has_open_quotes(text_until_cursor)
555
547
556 if '(' in text_until_cursor or '[' in text_until_cursor:
548 if '(' in text_until_cursor or '[' in text_until_cursor:
557 lsplit = text
549 lsplit = text
558 else:
550 else:
559 try:
551 try:
560 # arg_split ~ shlex.split, but with unicode bugs fixed by us
552 # arg_split ~ shlex.split, but with unicode bugs fixed by us
561 lsplit = arg_split(text_until_cursor)[-1]
553 lsplit = arg_split(text_until_cursor)[-1]
562 except ValueError:
554 except ValueError:
563 # typically an unmatched ", or backslash without escaped char.
555 # typically an unmatched ", or backslash without escaped char.
564 if open_quotes:
556 if open_quotes:
565 lsplit = text_until_cursor.split(open_quotes)[-1]
557 lsplit = text_until_cursor.split(open_quotes)[-1]
566 else:
558 else:
567 return []
559 return []
568 except IndexError:
560 except IndexError:
569 # tab pressed on empty line
561 # tab pressed on empty line
570 lsplit = ""
562 lsplit = ""
571
563
572 if not open_quotes and lsplit != protect_filename(lsplit):
564 if not open_quotes and lsplit != protect_filename(lsplit):
573 # if protectables are found, do matching on the whole escaped name
565 # if protectables are found, do matching on the whole escaped name
574 has_protectables = True
566 has_protectables = True
575 text0,text = text,lsplit
567 text0,text = text,lsplit
576 else:
568 else:
577 has_protectables = False
569 has_protectables = False
578 text = os.path.expanduser(text)
570 text = os.path.expanduser(text)
579
571
580 if text == "":
572 if text == "":
581 return [text_prefix + protect_filename(f) for f in self.glob("*")]
573 return [text_prefix + protect_filename(f) for f in self.glob("*")]
582
574
583 # Compute the matches from the filesystem
575 # Compute the matches from the filesystem
584 m0 = self.clean_glob(text.replace('\\',''))
576 m0 = self.clean_glob(text.replace('\\',''))
585
577
586 if has_protectables:
578 if has_protectables:
587 # If we had protectables, we need to revert our changes to the
579 # If we had protectables, we need to revert our changes to the
588 # beginning of filename so that we don't double-write the part
580 # beginning of filename so that we don't double-write the part
589 # of the filename we have so far
581 # of the filename we have so far
590 len_lsplit = len(lsplit)
582 len_lsplit = len(lsplit)
591 matches = [text_prefix + text0 +
583 matches = [text_prefix + text0 +
592 protect_filename(f[len_lsplit:]) for f in m0]
584 protect_filename(f[len_lsplit:]) for f in m0]
593 else:
585 else:
594 if open_quotes:
586 if open_quotes:
595 # if we have a string with an open quote, we don't need to
587 # if we have a string with an open quote, we don't need to
596 # protect the names at all (and we _shouldn't_, as it
588 # protect the names at all (and we _shouldn't_, as it
597 # would cause bugs when the filesystem call is made).
589 # would cause bugs when the filesystem call is made).
598 matches = m0
590 matches = m0
599 else:
591 else:
600 matches = [text_prefix +
592 matches = [text_prefix +
601 protect_filename(f) for f in m0]
593 protect_filename(f) for f in m0]
602
594
603 #io.rprint('mm', matches) # dbg
595 #io.rprint('mm', matches) # dbg
604
596
605 # Mark directories in input list by appending '/' to their names.
597 # Mark directories in input list by appending '/' to their names.
606 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
598 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
607 return matches
599 return matches
608
600
609 def magic_matches(self, text):
601 def magic_matches(self, text):
610 """Match magics"""
602 """Match magics"""
611 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
603 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
612 # Get all shell magics now rather than statically, so magics loaded at
604 # Get all shell magics now rather than statically, so magics loaded at
613 # runtime show up too.
605 # runtime show up too.
614 lsm = self.shell.magics_manager.lsmagic()
606 lsm = self.shell.magics_manager.lsmagic()
615 line_magics = lsm['line']
607 line_magics = lsm['line']
616 cell_magics = lsm['cell']
608 cell_magics = lsm['cell']
617 pre = self.magic_escape
609 pre = self.magic_escape
618 pre2 = pre+pre
610 pre2 = pre+pre
619
611
620 # Completion logic:
612 # Completion logic:
621 # - user gives %%: only do cell magics
613 # - user gives %%: only do cell magics
622 # - user gives %: do both line and cell magics
614 # - user gives %: do both line and cell magics
623 # - no prefix: do both
615 # - no prefix: do both
624 # In other words, line magics are skipped if the user gives %% explicitly
616 # In other words, line magics are skipped if the user gives %% explicitly
625 bare_text = text.lstrip(pre)
617 bare_text = text.lstrip(pre)
626 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
618 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
627 if not text.startswith(pre2):
619 if not text.startswith(pre2):
628 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
620 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
629 return comp
621 return comp
630
622
631 def alias_matches(self, text):
632 """Match internal system aliases"""
633 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
634
635 # if we are not in the first 'item', alias matching
636 # doesn't make sense - unless we are starting with 'sudo' command.
637 main_text = self.text_until_cursor.lstrip()
638 if ' ' in main_text and not main_text.startswith('sudo'):
639 return []
640 text = os.path.expanduser(text)
641 aliases = self.alias_table.keys()
642 if text == '':
643 return aliases
644 else:
645 return [a for a in aliases if a.startswith(text)]
646
647 def python_matches(self,text):
623 def python_matches(self,text):
648 """Match attributes or global python names"""
624 """Match attributes or global python names"""
649
625
650 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
626 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
651 if "." in text:
627 if "." in text:
652 try:
628 try:
653 matches = self.attr_matches(text)
629 matches = self.attr_matches(text)
654 if text.endswith('.') and self.omit__names:
630 if text.endswith('.') and self.omit__names:
655 if self.omit__names == 1:
631 if self.omit__names == 1:
656 # true if txt is _not_ a __ name, false otherwise:
632 # true if txt is _not_ a __ name, false otherwise:
657 no__name = (lambda txt:
633 no__name = (lambda txt:
658 re.match(r'.*\.__.*?__',txt) is None)
634 re.match(r'.*\.__.*?__',txt) is None)
659 else:
635 else:
660 # true if txt is _not_ a _ name, false otherwise:
636 # true if txt is _not_ a _ name, false otherwise:
661 no__name = (lambda txt:
637 no__name = (lambda txt:
662 re.match(r'.*\._.*?',txt) is None)
638 re.match(r'.*\._.*?',txt) is None)
663 matches = filter(no__name, matches)
639 matches = filter(no__name, matches)
664 except NameError:
640 except NameError:
665 # catches <undefined attributes>.<tab>
641 # catches <undefined attributes>.<tab>
666 matches = []
642 matches = []
667 else:
643 else:
668 matches = self.global_matches(text)
644 matches = self.global_matches(text)
669
645
670 return matches
646 return matches
671
647
672 def _default_arguments_from_docstring(self, doc):
648 def _default_arguments_from_docstring(self, doc):
673 """Parse the first line of docstring for call signature.
649 """Parse the first line of docstring for call signature.
674
650
675 Docstring should be of the form 'min(iterable[, key=func])\n'.
651 Docstring should be of the form 'min(iterable[, key=func])\n'.
676 It can also parse cython docstring of the form
652 It can also parse cython docstring of the form
677 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
653 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
678 """
654 """
679 if doc is None:
655 if doc is None:
680 return []
656 return []
681
657
682 #care only the firstline
658 #care only the firstline
683 line = doc.lstrip().splitlines()[0]
659 line = doc.lstrip().splitlines()[0]
684
660
685 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
661 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
686 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
662 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
687 sig = self.docstring_sig_re.search(line)
663 sig = self.docstring_sig_re.search(line)
688 if sig is None:
664 if sig is None:
689 return []
665 return []
690 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
666 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
691 sig = sig.groups()[0].split(',')
667 sig = sig.groups()[0].split(',')
692 ret = []
668 ret = []
693 for s in sig:
669 for s in sig:
694 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
670 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
695 ret += self.docstring_kwd_re.findall(s)
671 ret += self.docstring_kwd_re.findall(s)
696 return ret
672 return ret
697
673
698 def _default_arguments(self, obj):
674 def _default_arguments(self, obj):
699 """Return the list of default arguments of obj if it is callable,
675 """Return the list of default arguments of obj if it is callable,
700 or empty list otherwise."""
676 or empty list otherwise."""
701 call_obj = obj
677 call_obj = obj
702 ret = []
678 ret = []
703 if inspect.isbuiltin(obj):
679 if inspect.isbuiltin(obj):
704 pass
680 pass
705 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
681 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
706 if inspect.isclass(obj):
682 if inspect.isclass(obj):
707 #for cython embededsignature=True the constructor docstring
683 #for cython embededsignature=True the constructor docstring
708 #belongs to the object itself not __init__
684 #belongs to the object itself not __init__
709 ret += self._default_arguments_from_docstring(
685 ret += self._default_arguments_from_docstring(
710 getattr(obj, '__doc__', ''))
686 getattr(obj, '__doc__', ''))
711 # for classes, check for __init__,__new__
687 # for classes, check for __init__,__new__
712 call_obj = (getattr(obj, '__init__', None) or
688 call_obj = (getattr(obj, '__init__', None) or
713 getattr(obj, '__new__', None))
689 getattr(obj, '__new__', None))
714 # for all others, check if they are __call__able
690 # for all others, check if they are __call__able
715 elif hasattr(obj, '__call__'):
691 elif hasattr(obj, '__call__'):
716 call_obj = obj.__call__
692 call_obj = obj.__call__
717
693
718 ret += self._default_arguments_from_docstring(
694 ret += self._default_arguments_from_docstring(
719 getattr(call_obj, '__doc__', ''))
695 getattr(call_obj, '__doc__', ''))
720
696
721 try:
697 try:
722 args,_,_1,defaults = inspect.getargspec(call_obj)
698 args,_,_1,defaults = inspect.getargspec(call_obj)
723 if defaults:
699 if defaults:
724 ret+=args[-len(defaults):]
700 ret+=args[-len(defaults):]
725 except TypeError:
701 except TypeError:
726 pass
702 pass
727
703
728 return list(set(ret))
704 return list(set(ret))
729
705
730 def python_func_kw_matches(self,text):
706 def python_func_kw_matches(self,text):
731 """Match named parameters (kwargs) of the last open function"""
707 """Match named parameters (kwargs) of the last open function"""
732
708
733 if "." in text: # a parameter cannot be dotted
709 if "." in text: # a parameter cannot be dotted
734 return []
710 return []
735 try: regexp = self.__funcParamsRegex
711 try: regexp = self.__funcParamsRegex
736 except AttributeError:
712 except AttributeError:
737 regexp = self.__funcParamsRegex = re.compile(r'''
713 regexp = self.__funcParamsRegex = re.compile(r'''
738 '.*?(?<!\\)' | # single quoted strings or
714 '.*?(?<!\\)' | # single quoted strings or
739 ".*?(?<!\\)" | # double quoted strings or
715 ".*?(?<!\\)" | # double quoted strings or
740 \w+ | # identifier
716 \w+ | # identifier
741 \S # other characters
717 \S # other characters
742 ''', re.VERBOSE | re.DOTALL)
718 ''', re.VERBOSE | re.DOTALL)
743 # 1. find the nearest identifier that comes before an unclosed
719 # 1. find the nearest identifier that comes before an unclosed
744 # parenthesis before the cursor
720 # parenthesis before the cursor
745 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
721 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
746 tokens = regexp.findall(self.text_until_cursor)
722 tokens = regexp.findall(self.text_until_cursor)
747 tokens.reverse()
723 tokens.reverse()
748 iterTokens = iter(tokens); openPar = 0
724 iterTokens = iter(tokens); openPar = 0
749
725
750 for token in iterTokens:
726 for token in iterTokens:
751 if token == ')':
727 if token == ')':
752 openPar -= 1
728 openPar -= 1
753 elif token == '(':
729 elif token == '(':
754 openPar += 1
730 openPar += 1
755 if openPar > 0:
731 if openPar > 0:
756 # found the last unclosed parenthesis
732 # found the last unclosed parenthesis
757 break
733 break
758 else:
734 else:
759 return []
735 return []
760 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
736 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
761 ids = []
737 ids = []
762 isId = re.compile(r'\w+$').match
738 isId = re.compile(r'\w+$').match
763
739
764 while True:
740 while True:
765 try:
741 try:
766 ids.append(next(iterTokens))
742 ids.append(next(iterTokens))
767 if not isId(ids[-1]):
743 if not isId(ids[-1]):
768 ids.pop(); break
744 ids.pop(); break
769 if not next(iterTokens) == '.':
745 if not next(iterTokens) == '.':
770 break
746 break
771 except StopIteration:
747 except StopIteration:
772 break
748 break
773 # lookup the candidate callable matches either using global_matches
749 # lookup the candidate callable matches either using global_matches
774 # or attr_matches for dotted names
750 # or attr_matches for dotted names
775 if len(ids) == 1:
751 if len(ids) == 1:
776 callableMatches = self.global_matches(ids[0])
752 callableMatches = self.global_matches(ids[0])
777 else:
753 else:
778 callableMatches = self.attr_matches('.'.join(ids[::-1]))
754 callableMatches = self.attr_matches('.'.join(ids[::-1]))
779 argMatches = []
755 argMatches = []
780 for callableMatch in callableMatches:
756 for callableMatch in callableMatches:
781 try:
757 try:
782 namedArgs = self._default_arguments(eval(callableMatch,
758 namedArgs = self._default_arguments(eval(callableMatch,
783 self.namespace))
759 self.namespace))
784 except:
760 except:
785 continue
761 continue
786
762
787 for namedArg in namedArgs:
763 for namedArg in namedArgs:
788 if namedArg.startswith(text):
764 if namedArg.startswith(text):
789 argMatches.append("%s=" %namedArg)
765 argMatches.append("%s=" %namedArg)
790 return argMatches
766 return argMatches
791
767
792 def dispatch_custom_completer(self, text):
768 def dispatch_custom_completer(self, text):
793 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
769 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
794 line = self.line_buffer
770 line = self.line_buffer
795 if not line.strip():
771 if not line.strip():
796 return None
772 return None
797
773
798 # Create a little structure to pass all the relevant information about
774 # Create a little structure to pass all the relevant information about
799 # the current completion to any custom completer.
775 # the current completion to any custom completer.
800 event = Bunch()
776 event = Bunch()
801 event.line = line
777 event.line = line
802 event.symbol = text
778 event.symbol = text
803 cmd = line.split(None,1)[0]
779 cmd = line.split(None,1)[0]
804 event.command = cmd
780 event.command = cmd
805 event.text_until_cursor = self.text_until_cursor
781 event.text_until_cursor = self.text_until_cursor
806
782
807 #print "\ncustom:{%s]\n" % event # dbg
783 #print "\ncustom:{%s]\n" % event # dbg
808
784
809 # for foo etc, try also to find completer for %foo
785 # for foo etc, try also to find completer for %foo
810 if not cmd.startswith(self.magic_escape):
786 if not cmd.startswith(self.magic_escape):
811 try_magic = self.custom_completers.s_matches(
787 try_magic = self.custom_completers.s_matches(
812 self.magic_escape + cmd)
788 self.magic_escape + cmd)
813 else:
789 else:
814 try_magic = []
790 try_magic = []
815
791
816 for c in itertools.chain(self.custom_completers.s_matches(cmd),
792 for c in itertools.chain(self.custom_completers.s_matches(cmd),
817 try_magic,
793 try_magic,
818 self.custom_completers.flat_matches(self.text_until_cursor)):
794 self.custom_completers.flat_matches(self.text_until_cursor)):
819 #print "try",c # dbg
795 #print "try",c # dbg
820 try:
796 try:
821 res = c(event)
797 res = c(event)
822 if res:
798 if res:
823 # first, try case sensitive match
799 # first, try case sensitive match
824 withcase = [r for r in res if r.startswith(text)]
800 withcase = [r for r in res if r.startswith(text)]
825 if withcase:
801 if withcase:
826 return withcase
802 return withcase
827 # if none, then case insensitive ones are ok too
803 # if none, then case insensitive ones are ok too
828 text_low = text.lower()
804 text_low = text.lower()
829 return [r for r in res if r.lower().startswith(text_low)]
805 return [r for r in res if r.lower().startswith(text_low)]
830 except TryNext:
806 except TryNext:
831 pass
807 pass
832
808
833 return None
809 return None
834
810
835 def complete(self, text=None, line_buffer=None, cursor_pos=None):
811 def complete(self, text=None, line_buffer=None, cursor_pos=None):
836 """Find completions for the given text and line context.
812 """Find completions for the given text and line context.
837
813
838 This is called successively with state == 0, 1, 2, ... until it
814 This is called successively with state == 0, 1, 2, ... until it
839 returns None. The completion should begin with 'text'.
815 returns None. The completion should begin with 'text'.
840
816
841 Note that both the text and the line_buffer are optional, but at least
817 Note that both the text and the line_buffer are optional, but at least
842 one of them must be given.
818 one of them must be given.
843
819
844 Parameters
820 Parameters
845 ----------
821 ----------
846 text : string, optional
822 text : string, optional
847 Text to perform the completion on. If not given, the line buffer
823 Text to perform the completion on. If not given, the line buffer
848 is split using the instance's CompletionSplitter object.
824 is split using the instance's CompletionSplitter object.
849
825
850 line_buffer : string, optional
826 line_buffer : string, optional
851 If not given, the completer attempts to obtain the current line
827 If not given, the completer attempts to obtain the current line
852 buffer via readline. This keyword allows clients which are
828 buffer via readline. This keyword allows clients which are
853 requesting for text completions in non-readline contexts to inform
829 requesting for text completions in non-readline contexts to inform
854 the completer of the entire text.
830 the completer of the entire text.
855
831
856 cursor_pos : int, optional
832 cursor_pos : int, optional
857 Index of the cursor in the full line buffer. Should be provided by
833 Index of the cursor in the full line buffer. Should be provided by
858 remote frontends where kernel has no access to frontend state.
834 remote frontends where kernel has no access to frontend state.
859
835
860 Returns
836 Returns
861 -------
837 -------
862 text : str
838 text : str
863 Text that was actually used in the completion.
839 Text that was actually used in the completion.
864
840
865 matches : list
841 matches : list
866 A list of completion matches.
842 A list of completion matches.
867 """
843 """
868 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
844 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
869
845
870 # if the cursor position isn't given, the only sane assumption we can
846 # if the cursor position isn't given, the only sane assumption we can
871 # make is that it's at the end of the line (the common case)
847 # make is that it's at the end of the line (the common case)
872 if cursor_pos is None:
848 if cursor_pos is None:
873 cursor_pos = len(line_buffer) if text is None else len(text)
849 cursor_pos = len(line_buffer) if text is None else len(text)
874
850
875 # if text is either None or an empty string, rely on the line buffer
851 # if text is either None or an empty string, rely on the line buffer
876 if not text:
852 if not text:
877 text = self.splitter.split_line(line_buffer, cursor_pos)
853 text = self.splitter.split_line(line_buffer, cursor_pos)
878
854
879 # If no line buffer is given, assume the input text is all there was
855 # If no line buffer is given, assume the input text is all there was
880 if line_buffer is None:
856 if line_buffer is None:
881 line_buffer = text
857 line_buffer = text
882
858
883 self.line_buffer = line_buffer
859 self.line_buffer = line_buffer
884 self.text_until_cursor = self.line_buffer[:cursor_pos]
860 self.text_until_cursor = self.line_buffer[:cursor_pos]
885 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
861 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
886
862
887 # Start with a clean slate of completions
863 # Start with a clean slate of completions
888 self.matches[:] = []
864 self.matches[:] = []
889 custom_res = self.dispatch_custom_completer(text)
865 custom_res = self.dispatch_custom_completer(text)
890 if custom_res is not None:
866 if custom_res is not None:
891 # did custom completers produce something?
867 # did custom completers produce something?
892 self.matches = custom_res
868 self.matches = custom_res
893 else:
869 else:
894 # Extend the list of completions with the results of each
870 # Extend the list of completions with the results of each
895 # matcher, so we return results to the user from all
871 # matcher, so we return results to the user from all
896 # namespaces.
872 # namespaces.
897 if self.merge_completions:
873 if self.merge_completions:
898 self.matches = []
874 self.matches = []
899 for matcher in self.matchers:
875 for matcher in self.matchers:
900 try:
876 try:
901 self.matches.extend(matcher(text))
877 self.matches.extend(matcher(text))
902 except:
878 except:
903 # Show the ugly traceback if the matcher causes an
879 # Show the ugly traceback if the matcher causes an
904 # exception, but do NOT crash the kernel!
880 # exception, but do NOT crash the kernel!
905 sys.excepthook(*sys.exc_info())
881 sys.excepthook(*sys.exc_info())
906 else:
882 else:
907 for matcher in self.matchers:
883 for matcher in self.matchers:
908 self.matches = matcher(text)
884 self.matches = matcher(text)
909 if self.matches:
885 if self.matches:
910 break
886 break
911 # FIXME: we should extend our api to return a dict with completions for
887 # FIXME: we should extend our api to return a dict with completions for
912 # different types of objects. The rlcomplete() method could then
888 # different types of objects. The rlcomplete() method could then
913 # simply collapse the dict into a list for readline, but we'd have
889 # simply collapse the dict into a list for readline, but we'd have
914 # richer completion semantics in other evironments.
890 # richer completion semantics in other evironments.
915 self.matches = sorted(set(self.matches))
891 self.matches = sorted(set(self.matches))
916 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
892 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
917 return text, self.matches
893 return text, self.matches
918
894
919 def rlcomplete(self, text, state):
895 def rlcomplete(self, text, state):
920 """Return the state-th possible completion for 'text'.
896 """Return the state-th possible completion for 'text'.
921
897
922 This is called successively with state == 0, 1, 2, ... until it
898 This is called successively with state == 0, 1, 2, ... until it
923 returns None. The completion should begin with 'text'.
899 returns None. The completion should begin with 'text'.
924
900
925 Parameters
901 Parameters
926 ----------
902 ----------
927 text : string
903 text : string
928 Text to perform the completion on.
904 Text to perform the completion on.
929
905
930 state : int
906 state : int
931 Counter used by readline.
907 Counter used by readline.
932 """
908 """
933 if state==0:
909 if state==0:
934
910
935 self.line_buffer = line_buffer = self.readline.get_line_buffer()
911 self.line_buffer = line_buffer = self.readline.get_line_buffer()
936 cursor_pos = self.readline.get_endidx()
912 cursor_pos = self.readline.get_endidx()
937
913
938 #io.rprint("\nRLCOMPLETE: %r %r %r" %
914 #io.rprint("\nRLCOMPLETE: %r %r %r" %
939 # (text, line_buffer, cursor_pos) ) # dbg
915 # (text, line_buffer, cursor_pos) ) # dbg
940
916
941 # if there is only a tab on a line with only whitespace, instead of
917 # if there is only a tab on a line with only whitespace, instead of
942 # the mostly useless 'do you want to see all million completions'
918 # the mostly useless 'do you want to see all million completions'
943 # message, just do the right thing and give the user his tab!
919 # message, just do the right thing and give the user his tab!
944 # Incidentally, this enables pasting of tabbed text from an editor
920 # Incidentally, this enables pasting of tabbed text from an editor
945 # (as long as autoindent is off).
921 # (as long as autoindent is off).
946
922
947 # It should be noted that at least pyreadline still shows file
923 # It should be noted that at least pyreadline still shows file
948 # completions - is there a way around it?
924 # completions - is there a way around it?
949
925
950 # don't apply this on 'dumb' terminals, such as emacs buffers, so
926 # don't apply this on 'dumb' terminals, such as emacs buffers, so
951 # we don't interfere with their own tab-completion mechanism.
927 # we don't interfere with their own tab-completion mechanism.
952 if not (self.dumb_terminal or line_buffer.strip()):
928 if not (self.dumb_terminal or line_buffer.strip()):
953 self.readline.insert_text('\t')
929 self.readline.insert_text('\t')
954 sys.stdout.flush()
930 sys.stdout.flush()
955 return None
931 return None
956
932
957 # Note: debugging exceptions that may occur in completion is very
933 # Note: debugging exceptions that may occur in completion is very
958 # tricky, because readline unconditionally silences them. So if
934 # tricky, because readline unconditionally silences them. So if
959 # during development you suspect a bug in the completion code, turn
935 # during development you suspect a bug in the completion code, turn
960 # this flag on temporarily by uncommenting the second form (don't
936 # this flag on temporarily by uncommenting the second form (don't
961 # flip the value in the first line, as the '# dbg' marker can be
937 # flip the value in the first line, as the '# dbg' marker can be
962 # automatically detected and is used elsewhere).
938 # automatically detected and is used elsewhere).
963 DEBUG = False
939 DEBUG = False
964 #DEBUG = True # dbg
940 #DEBUG = True # dbg
965 if DEBUG:
941 if DEBUG:
966 try:
942 try:
967 self.complete(text, line_buffer, cursor_pos)
943 self.complete(text, line_buffer, cursor_pos)
968 except:
944 except:
969 import traceback; traceback.print_exc()
945 import traceback; traceback.print_exc()
970 else:
946 else:
971 # The normal production version is here
947 # The normal production version is here
972
948
973 # This method computes the self.matches array
949 # This method computes the self.matches array
974 self.complete(text, line_buffer, cursor_pos)
950 self.complete(text, line_buffer, cursor_pos)
975
951
976 try:
952 try:
977 return self.matches[state]
953 return self.matches[state]
978 except IndexError:
954 except IndexError:
979 return None
955 return None
@@ -1,3155 +1,3154 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import absolute_import
17 from __future__ import absolute_import
18 from __future__ import print_function
18 from __future__ import print_function
19
19
20 import __builtin__ as builtin_mod
20 import __builtin__ as builtin_mod
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import functools
25 import functools
26 import os
26 import os
27 import re
27 import re
28 import runpy
28 import runpy
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32 from io import open as io_open
32 from io import open as io_open
33
33
34 from IPython.config.configurable import SingletonConfigurable
34 from IPython.config.configurable import SingletonConfigurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import magic
36 from IPython.core import magic
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager, AliasError
41 from IPython.core.alias import AliasManager, AliasError
42 from IPython.core.autocall import ExitAutocall
42 from IPython.core.autocall import ExitAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import UsageError
48 from IPython.core.error import UsageError
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.formatters import DisplayFormatter
50 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.history import HistoryManager
51 from IPython.core.history import HistoryManager
52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.logger import Logger
53 from IPython.core.logger import Logger
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.payload import PayloadManager
55 from IPython.core.payload import PayloadManager
56 from IPython.core.prefilter import PrefilterManager
56 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.profiledir import ProfileDir
57 from IPython.core.profiledir import ProfileDir
58 from IPython.core.prompts import PromptManager
58 from IPython.core.prompts import PromptManager
59 from IPython.lib.latextools import LaTeXTool
59 from IPython.lib.latextools import LaTeXTool
60 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest
61 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils import py3compat
63 from IPython.utils import py3compat
64 from IPython.utils import openpy
64 from IPython.utils import openpy
65 from IPython.utils.decorators import undoc
65 from IPython.utils.decorators import undoc
66 from IPython.utils.io import ask_yes_no
66 from IPython.utils.io import ask_yes_no
67 from IPython.utils.ipstruct import Struct
67 from IPython.utils.ipstruct import Struct
68 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
68 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
69 from IPython.utils.pickleshare import PickleShareDB
69 from IPython.utils.pickleshare import PickleShareDB
70 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
71 from IPython.utils.strdispatch import StrDispatch
71 from IPython.utils.strdispatch import StrDispatch
72 from IPython.utils.syspathcontext import prepended_to_syspath
72 from IPython.utils.syspathcontext import prepended_to_syspath
73 from IPython.utils.text import (format_screen, LSString, SList,
73 from IPython.utils.text import (format_screen, LSString, SList,
74 DollarFormatter)
74 DollarFormatter)
75 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
75 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
76 List, Unicode, Instance, Type)
76 List, Unicode, Instance, Type)
77 from IPython.utils.warn import warn, error
77 from IPython.utils.warn import warn, error
78 import IPython.core.hooks
78 import IPython.core.hooks
79
79
80 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81 # Globals
81 # Globals
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
88 # Utilities
88 # Utilities
89 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
90
90
91 @undoc
91 @undoc
92 def softspace(file, newvalue):
92 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
93 """Copied from code.py, to remove the dependency"""
94
94
95 oldvalue = 0
95 oldvalue = 0
96 try:
96 try:
97 oldvalue = file.softspace
97 oldvalue = file.softspace
98 except AttributeError:
98 except AttributeError:
99 pass
99 pass
100 try:
100 try:
101 file.softspace = newvalue
101 file.softspace = newvalue
102 except (AttributeError, TypeError):
102 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
103 # "attribute-less object" or "read-only attributes"
104 pass
104 pass
105 return oldvalue
105 return oldvalue
106
106
107 @undoc
107 @undoc
108 def no_op(*a, **kw): pass
108 def no_op(*a, **kw): pass
109
109
110 @undoc
110 @undoc
111 class NoOpContext(object):
111 class NoOpContext(object):
112 def __enter__(self): pass
112 def __enter__(self): pass
113 def __exit__(self, type, value, traceback): pass
113 def __exit__(self, type, value, traceback): pass
114 no_op_context = NoOpContext()
114 no_op_context = NoOpContext()
115
115
116 class SpaceInInput(Exception): pass
116 class SpaceInInput(Exception): pass
117
117
118 @undoc
118 @undoc
119 class Bunch: pass
119 class Bunch: pass
120
120
121
121
122 def get_default_colors():
122 def get_default_colors():
123 if sys.platform=='darwin':
123 if sys.platform=='darwin':
124 return "LightBG"
124 return "LightBG"
125 elif os.name=='nt':
125 elif os.name=='nt':
126 return 'Linux'
126 return 'Linux'
127 else:
127 else:
128 return 'Linux'
128 return 'Linux'
129
129
130
130
131 class SeparateUnicode(Unicode):
131 class SeparateUnicode(Unicode):
132 """A Unicode subclass to validate separate_in, separate_out, etc.
132 """A Unicode subclass to validate separate_in, separate_out, etc.
133
133
134 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
134 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
135 """
135 """
136
136
137 def validate(self, obj, value):
137 def validate(self, obj, value):
138 if value == '0': value = ''
138 if value == '0': value = ''
139 value = value.replace('\\n','\n')
139 value = value.replace('\\n','\n')
140 return super(SeparateUnicode, self).validate(obj, value)
140 return super(SeparateUnicode, self).validate(obj, value)
141
141
142
142
143 class ReadlineNoRecord(object):
143 class ReadlineNoRecord(object):
144 """Context manager to execute some code, then reload readline history
144 """Context manager to execute some code, then reload readline history
145 so that interactive input to the code doesn't appear when pressing up."""
145 so that interactive input to the code doesn't appear when pressing up."""
146 def __init__(self, shell):
146 def __init__(self, shell):
147 self.shell = shell
147 self.shell = shell
148 self._nested_level = 0
148 self._nested_level = 0
149
149
150 def __enter__(self):
150 def __enter__(self):
151 if self._nested_level == 0:
151 if self._nested_level == 0:
152 try:
152 try:
153 self.orig_length = self.current_length()
153 self.orig_length = self.current_length()
154 self.readline_tail = self.get_readline_tail()
154 self.readline_tail = self.get_readline_tail()
155 except (AttributeError, IndexError): # Can fail with pyreadline
155 except (AttributeError, IndexError): # Can fail with pyreadline
156 self.orig_length, self.readline_tail = 999999, []
156 self.orig_length, self.readline_tail = 999999, []
157 self._nested_level += 1
157 self._nested_level += 1
158
158
159 def __exit__(self, type, value, traceback):
159 def __exit__(self, type, value, traceback):
160 self._nested_level -= 1
160 self._nested_level -= 1
161 if self._nested_level == 0:
161 if self._nested_level == 0:
162 # Try clipping the end if it's got longer
162 # Try clipping the end if it's got longer
163 try:
163 try:
164 e = self.current_length() - self.orig_length
164 e = self.current_length() - self.orig_length
165 if e > 0:
165 if e > 0:
166 for _ in range(e):
166 for _ in range(e):
167 self.shell.readline.remove_history_item(self.orig_length)
167 self.shell.readline.remove_history_item(self.orig_length)
168
168
169 # If it still doesn't match, just reload readline history.
169 # If it still doesn't match, just reload readline history.
170 if self.current_length() != self.orig_length \
170 if self.current_length() != self.orig_length \
171 or self.get_readline_tail() != self.readline_tail:
171 or self.get_readline_tail() != self.readline_tail:
172 self.shell.refill_readline_hist()
172 self.shell.refill_readline_hist()
173 except (AttributeError, IndexError):
173 except (AttributeError, IndexError):
174 pass
174 pass
175 # Returning False will cause exceptions to propagate
175 # Returning False will cause exceptions to propagate
176 return False
176 return False
177
177
178 def current_length(self):
178 def current_length(self):
179 return self.shell.readline.get_current_history_length()
179 return self.shell.readline.get_current_history_length()
180
180
181 def get_readline_tail(self, n=10):
181 def get_readline_tail(self, n=10):
182 """Get the last n items in readline history."""
182 """Get the last n items in readline history."""
183 end = self.shell.readline.get_current_history_length() + 1
183 end = self.shell.readline.get_current_history_length() + 1
184 start = max(end-n, 1)
184 start = max(end-n, 1)
185 ghi = self.shell.readline.get_history_item
185 ghi = self.shell.readline.get_history_item
186 return [ghi(x) for x in range(start, end)]
186 return [ghi(x) for x in range(start, end)]
187
187
188
188
189 @undoc
189 @undoc
190 class DummyMod(object):
190 class DummyMod(object):
191 """A dummy module used for IPython's interactive module when
191 """A dummy module used for IPython's interactive module when
192 a namespace must be assigned to the module's __dict__."""
192 a namespace must be assigned to the module's __dict__."""
193 pass
193 pass
194
194
195 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
196 # Main IPython class
196 # Main IPython class
197 #-----------------------------------------------------------------------------
197 #-----------------------------------------------------------------------------
198
198
199 class InteractiveShell(SingletonConfigurable):
199 class InteractiveShell(SingletonConfigurable):
200 """An enhanced, interactive shell for Python."""
200 """An enhanced, interactive shell for Python."""
201
201
202 _instance = None
202 _instance = None
203
203
204 ast_transformers = List([], config=True, help=
204 ast_transformers = List([], config=True, help=
205 """
205 """
206 A list of ast.NodeTransformer subclass instances, which will be applied
206 A list of ast.NodeTransformer subclass instances, which will be applied
207 to user input before code is run.
207 to user input before code is run.
208 """
208 """
209 )
209 )
210
210
211 autocall = Enum((0,1,2), default_value=0, config=True, help=
211 autocall = Enum((0,1,2), default_value=0, config=True, help=
212 """
212 """
213 Make IPython automatically call any callable object even if you didn't
213 Make IPython automatically call any callable object even if you didn't
214 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
215 automatically. The value can be '0' to disable the feature, '1' for
215 automatically. The value can be '0' to disable the feature, '1' for
216 'smart' autocall, where it is not applied if there are no more
216 'smart' autocall, where it is not applied if there are no more
217 arguments on the line, and '2' for 'full' autocall, where all callable
217 arguments on the line, and '2' for 'full' autocall, where all callable
218 objects are automatically called (even if no arguments are present).
218 objects are automatically called (even if no arguments are present).
219 """
219 """
220 )
220 )
221 # TODO: remove all autoindent logic and put into frontends.
221 # TODO: remove all autoindent logic and put into frontends.
222 # We can't do this yet because even runlines uses the autoindent.
222 # We can't do this yet because even runlines uses the autoindent.
223 autoindent = CBool(True, config=True, help=
223 autoindent = CBool(True, config=True, help=
224 """
224 """
225 Autoindent IPython code entered interactively.
225 Autoindent IPython code entered interactively.
226 """
226 """
227 )
227 )
228 automagic = CBool(True, config=True, help=
228 automagic = CBool(True, config=True, help=
229 """
229 """
230 Enable magic commands to be called without the leading %.
230 Enable magic commands to be called without the leading %.
231 """
231 """
232 )
232 )
233 cache_size = Integer(1000, config=True, help=
233 cache_size = Integer(1000, config=True, help=
234 """
234 """
235 Set the size of the output cache. The default is 1000, you can
235 Set the size of the output cache. The default is 1000, you can
236 change it permanently in your config file. Setting it to 0 completely
236 change it permanently in your config file. Setting it to 0 completely
237 disables the caching system, and the minimum value accepted is 20 (if
237 disables the caching system, and the minimum value accepted is 20 (if
238 you provide a value less than 20, it is reset to 0 and a warning is
238 you provide a value less than 20, it is reset to 0 and a warning is
239 issued). This limit is defined because otherwise you'll spend more
239 issued). This limit is defined because otherwise you'll spend more
240 time re-flushing a too small cache than working
240 time re-flushing a too small cache than working
241 """
241 """
242 )
242 )
243 color_info = CBool(True, config=True, help=
243 color_info = CBool(True, config=True, help=
244 """
244 """
245 Use colors for displaying information about objects. Because this
245 Use colors for displaying information about objects. Because this
246 information is passed through a pager (like 'less'), and some pagers
246 information is passed through a pager (like 'less'), and some pagers
247 get confused with color codes, this capability can be turned off.
247 get confused with color codes, this capability can be turned off.
248 """
248 """
249 )
249 )
250 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
250 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
251 default_value=get_default_colors(), config=True,
251 default_value=get_default_colors(), config=True,
252 help="Set the color scheme (NoColor, Linux, or LightBG)."
252 help="Set the color scheme (NoColor, Linux, or LightBG)."
253 )
253 )
254 colors_force = CBool(False, help=
254 colors_force = CBool(False, help=
255 """
255 """
256 Force use of ANSI color codes, regardless of OS and readline
256 Force use of ANSI color codes, regardless of OS and readline
257 availability.
257 availability.
258 """
258 """
259 # FIXME: This is essentially a hack to allow ZMQShell to show colors
259 # FIXME: This is essentially a hack to allow ZMQShell to show colors
260 # without readline on Win32. When the ZMQ formatting system is
260 # without readline on Win32. When the ZMQ formatting system is
261 # refactored, this should be removed.
261 # refactored, this should be removed.
262 )
262 )
263 debug = CBool(False, config=True)
263 debug = CBool(False, config=True)
264 deep_reload = CBool(False, config=True, help=
264 deep_reload = CBool(False, config=True, help=
265 """
265 """
266 Enable deep (recursive) reloading by default. IPython can use the
266 Enable deep (recursive) reloading by default. IPython can use the
267 deep_reload module which reloads changes in modules recursively (it
267 deep_reload module which reloads changes in modules recursively (it
268 replaces the reload() function, so you don't need to change anything to
268 replaces the reload() function, so you don't need to change anything to
269 use it). deep_reload() forces a full reload of modules whose code may
269 use it). deep_reload() forces a full reload of modules whose code may
270 have changed, which the default reload() function does not. When
270 have changed, which the default reload() function does not. When
271 deep_reload is off, IPython will use the normal reload(), but
271 deep_reload is off, IPython will use the normal reload(), but
272 deep_reload will still be available as dreload().
272 deep_reload will still be available as dreload().
273 """
273 """
274 )
274 )
275 disable_failing_post_execute = CBool(False, config=True,
275 disable_failing_post_execute = CBool(False, config=True,
276 help="Don't call post-execute functions that have failed in the past."
276 help="Don't call post-execute functions that have failed in the past."
277 )
277 )
278 display_formatter = Instance(DisplayFormatter)
278 display_formatter = Instance(DisplayFormatter)
279 displayhook_class = Type(DisplayHook)
279 displayhook_class = Type(DisplayHook)
280 display_pub_class = Type(DisplayPublisher)
280 display_pub_class = Type(DisplayPublisher)
281 data_pub_class = None
281 data_pub_class = None
282
282
283 exit_now = CBool(False)
283 exit_now = CBool(False)
284 exiter = Instance(ExitAutocall)
284 exiter = Instance(ExitAutocall)
285 def _exiter_default(self):
285 def _exiter_default(self):
286 return ExitAutocall(self)
286 return ExitAutocall(self)
287 # Monotonically increasing execution counter
287 # Monotonically increasing execution counter
288 execution_count = Integer(1)
288 execution_count = Integer(1)
289 filename = Unicode("<ipython console>")
289 filename = Unicode("<ipython console>")
290 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
290 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
291
291
292 # Input splitter, to transform input line by line and detect when a block
292 # Input splitter, to transform input line by line and detect when a block
293 # is ready to be executed.
293 # is ready to be executed.
294 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
294 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
295 (), {'line_input_checker': True})
295 (), {'line_input_checker': True})
296
296
297 # This InputSplitter instance is used to transform completed cells before
297 # This InputSplitter instance is used to transform completed cells before
298 # running them. It allows cell magics to contain blank lines.
298 # running them. It allows cell magics to contain blank lines.
299 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
299 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
300 (), {'line_input_checker': False})
300 (), {'line_input_checker': False})
301
301
302 logstart = CBool(False, config=True, help=
302 logstart = CBool(False, config=True, help=
303 """
303 """
304 Start logging to the default log file.
304 Start logging to the default log file.
305 """
305 """
306 )
306 )
307 logfile = Unicode('', config=True, help=
307 logfile = Unicode('', config=True, help=
308 """
308 """
309 The name of the logfile to use.
309 The name of the logfile to use.
310 """
310 """
311 )
311 )
312 logappend = Unicode('', config=True, help=
312 logappend = Unicode('', config=True, help=
313 """
313 """
314 Start logging to the given file in append mode.
314 Start logging to the given file in append mode.
315 """
315 """
316 )
316 )
317 object_info_string_level = Enum((0,1,2), default_value=0,
317 object_info_string_level = Enum((0,1,2), default_value=0,
318 config=True)
318 config=True)
319 pdb = CBool(False, config=True, help=
319 pdb = CBool(False, config=True, help=
320 """
320 """
321 Automatically call the pdb debugger after every exception.
321 Automatically call the pdb debugger after every exception.
322 """
322 """
323 )
323 )
324 multiline_history = CBool(sys.platform != 'win32', config=True,
324 multiline_history = CBool(sys.platform != 'win32', config=True,
325 help="Save multi-line entries as one entry in readline history"
325 help="Save multi-line entries as one entry in readline history"
326 )
326 )
327
327
328 # deprecated prompt traits:
328 # deprecated prompt traits:
329
329
330 prompt_in1 = Unicode('In [\\#]: ', config=True,
330 prompt_in1 = Unicode('In [\\#]: ', config=True,
331 help="Deprecated, use PromptManager.in_template")
331 help="Deprecated, use PromptManager.in_template")
332 prompt_in2 = Unicode(' .\\D.: ', config=True,
332 prompt_in2 = Unicode(' .\\D.: ', config=True,
333 help="Deprecated, use PromptManager.in2_template")
333 help="Deprecated, use PromptManager.in2_template")
334 prompt_out = Unicode('Out[\\#]: ', config=True,
334 prompt_out = Unicode('Out[\\#]: ', config=True,
335 help="Deprecated, use PromptManager.out_template")
335 help="Deprecated, use PromptManager.out_template")
336 prompts_pad_left = CBool(True, config=True,
336 prompts_pad_left = CBool(True, config=True,
337 help="Deprecated, use PromptManager.justify")
337 help="Deprecated, use PromptManager.justify")
338
338
339 def _prompt_trait_changed(self, name, old, new):
339 def _prompt_trait_changed(self, name, old, new):
340 table = {
340 table = {
341 'prompt_in1' : 'in_template',
341 'prompt_in1' : 'in_template',
342 'prompt_in2' : 'in2_template',
342 'prompt_in2' : 'in2_template',
343 'prompt_out' : 'out_template',
343 'prompt_out' : 'out_template',
344 'prompts_pad_left' : 'justify',
344 'prompts_pad_left' : 'justify',
345 }
345 }
346 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
346 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
347 name=name, newname=table[name])
347 name=name, newname=table[name])
348 )
348 )
349 # protect against weird cases where self.config may not exist:
349 # protect against weird cases where self.config may not exist:
350 if self.config is not None:
350 if self.config is not None:
351 # propagate to corresponding PromptManager trait
351 # propagate to corresponding PromptManager trait
352 setattr(self.config.PromptManager, table[name], new)
352 setattr(self.config.PromptManager, table[name], new)
353
353
354 _prompt_in1_changed = _prompt_trait_changed
354 _prompt_in1_changed = _prompt_trait_changed
355 _prompt_in2_changed = _prompt_trait_changed
355 _prompt_in2_changed = _prompt_trait_changed
356 _prompt_out_changed = _prompt_trait_changed
356 _prompt_out_changed = _prompt_trait_changed
357 _prompt_pad_left_changed = _prompt_trait_changed
357 _prompt_pad_left_changed = _prompt_trait_changed
358
358
359 show_rewritten_input = CBool(True, config=True,
359 show_rewritten_input = CBool(True, config=True,
360 help="Show rewritten input, e.g. for autocall."
360 help="Show rewritten input, e.g. for autocall."
361 )
361 )
362
362
363 quiet = CBool(False, config=True)
363 quiet = CBool(False, config=True)
364
364
365 history_length = Integer(10000, config=True)
365 history_length = Integer(10000, config=True)
366
366
367 # The readline stuff will eventually be moved to the terminal subclass
367 # The readline stuff will eventually be moved to the terminal subclass
368 # but for now, we can't do that as readline is welded in everywhere.
368 # but for now, we can't do that as readline is welded in everywhere.
369 readline_use = CBool(True, config=True)
369 readline_use = CBool(True, config=True)
370 readline_remove_delims = Unicode('-/~', config=True)
370 readline_remove_delims = Unicode('-/~', config=True)
371 readline_delims = Unicode() # set by init_readline()
371 readline_delims = Unicode() # set by init_readline()
372 # don't use \M- bindings by default, because they
372 # don't use \M- bindings by default, because they
373 # conflict with 8-bit encodings. See gh-58,gh-88
373 # conflict with 8-bit encodings. See gh-58,gh-88
374 readline_parse_and_bind = List([
374 readline_parse_and_bind = List([
375 'tab: complete',
375 'tab: complete',
376 '"\C-l": clear-screen',
376 '"\C-l": clear-screen',
377 'set show-all-if-ambiguous on',
377 'set show-all-if-ambiguous on',
378 '"\C-o": tab-insert',
378 '"\C-o": tab-insert',
379 '"\C-r": reverse-search-history',
379 '"\C-r": reverse-search-history',
380 '"\C-s": forward-search-history',
380 '"\C-s": forward-search-history',
381 '"\C-p": history-search-backward',
381 '"\C-p": history-search-backward',
382 '"\C-n": history-search-forward',
382 '"\C-n": history-search-forward',
383 '"\e[A": history-search-backward',
383 '"\e[A": history-search-backward',
384 '"\e[B": history-search-forward',
384 '"\e[B": history-search-forward',
385 '"\C-k": kill-line',
385 '"\C-k": kill-line',
386 '"\C-u": unix-line-discard',
386 '"\C-u": unix-line-discard',
387 ], allow_none=False, config=True)
387 ], allow_none=False, config=True)
388
388
389 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
389 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
390 default_value='last_expr', config=True,
390 default_value='last_expr', config=True,
391 help="""
391 help="""
392 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
392 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
393 run interactively (displaying output from expressions).""")
393 run interactively (displaying output from expressions).""")
394
394
395 # TODO: this part of prompt management should be moved to the frontends.
395 # TODO: this part of prompt management should be moved to the frontends.
396 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
396 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
397 separate_in = SeparateUnicode('\n', config=True)
397 separate_in = SeparateUnicode('\n', config=True)
398 separate_out = SeparateUnicode('', config=True)
398 separate_out = SeparateUnicode('', config=True)
399 separate_out2 = SeparateUnicode('', config=True)
399 separate_out2 = SeparateUnicode('', config=True)
400 wildcards_case_sensitive = CBool(True, config=True)
400 wildcards_case_sensitive = CBool(True, config=True)
401 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
401 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
402 default_value='Context', config=True)
402 default_value='Context', config=True)
403
403
404 # Subcomponents of InteractiveShell
404 # Subcomponents of InteractiveShell
405 alias_manager = Instance('IPython.core.alias.AliasManager')
405 alias_manager = Instance('IPython.core.alias.AliasManager')
406 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
406 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
407 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
407 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
408 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
408 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
409 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
409 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
410 payload_manager = Instance('IPython.core.payload.PayloadManager')
410 payload_manager = Instance('IPython.core.payload.PayloadManager')
411 history_manager = Instance('IPython.core.history.HistoryManager')
411 history_manager = Instance('IPython.core.history.HistoryManager')
412 magics_manager = Instance('IPython.core.magic.MagicsManager')
412 magics_manager = Instance('IPython.core.magic.MagicsManager')
413
413
414 profile_dir = Instance('IPython.core.application.ProfileDir')
414 profile_dir = Instance('IPython.core.application.ProfileDir')
415 @property
415 @property
416 def profile(self):
416 def profile(self):
417 if self.profile_dir is not None:
417 if self.profile_dir is not None:
418 name = os.path.basename(self.profile_dir.location)
418 name = os.path.basename(self.profile_dir.location)
419 return name.replace('profile_','')
419 return name.replace('profile_','')
420
420
421
421
422 # Private interface
422 # Private interface
423 _post_execute = Instance(dict)
423 _post_execute = Instance(dict)
424
424
425 # Tracks any GUI loop loaded for pylab
425 # Tracks any GUI loop loaded for pylab
426 pylab_gui_select = None
426 pylab_gui_select = None
427
427
428 def __init__(self, ipython_dir=None, profile_dir=None,
428 def __init__(self, ipython_dir=None, profile_dir=None,
429 user_module=None, user_ns=None,
429 user_module=None, user_ns=None,
430 custom_exceptions=((), None), **kwargs):
430 custom_exceptions=((), None), **kwargs):
431
431
432 # This is where traits with a config_key argument are updated
432 # This is where traits with a config_key argument are updated
433 # from the values on config.
433 # from the values on config.
434 super(InteractiveShell, self).__init__(**kwargs)
434 super(InteractiveShell, self).__init__(**kwargs)
435 self.configurables = [self]
435 self.configurables = [self]
436
436
437 # These are relatively independent and stateless
437 # These are relatively independent and stateless
438 self.init_ipython_dir(ipython_dir)
438 self.init_ipython_dir(ipython_dir)
439 self.init_profile_dir(profile_dir)
439 self.init_profile_dir(profile_dir)
440 self.init_instance_attrs()
440 self.init_instance_attrs()
441 self.init_environment()
441 self.init_environment()
442
442
443 # Check if we're in a virtualenv, and set up sys.path.
443 # Check if we're in a virtualenv, and set up sys.path.
444 self.init_virtualenv()
444 self.init_virtualenv()
445
445
446 # Create namespaces (user_ns, user_global_ns, etc.)
446 # Create namespaces (user_ns, user_global_ns, etc.)
447 self.init_create_namespaces(user_module, user_ns)
447 self.init_create_namespaces(user_module, user_ns)
448 # This has to be done after init_create_namespaces because it uses
448 # This has to be done after init_create_namespaces because it uses
449 # something in self.user_ns, but before init_sys_modules, which
449 # something in self.user_ns, but before init_sys_modules, which
450 # is the first thing to modify sys.
450 # is the first thing to modify sys.
451 # TODO: When we override sys.stdout and sys.stderr before this class
451 # TODO: When we override sys.stdout and sys.stderr before this class
452 # is created, we are saving the overridden ones here. Not sure if this
452 # is created, we are saving the overridden ones here. Not sure if this
453 # is what we want to do.
453 # is what we want to do.
454 self.save_sys_module_state()
454 self.save_sys_module_state()
455 self.init_sys_modules()
455 self.init_sys_modules()
456
456
457 # While we're trying to have each part of the code directly access what
457 # While we're trying to have each part of the code directly access what
458 # it needs without keeping redundant references to objects, we have too
458 # it needs without keeping redundant references to objects, we have too
459 # much legacy code that expects ip.db to exist.
459 # much legacy code that expects ip.db to exist.
460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
461
461
462 self.init_history()
462 self.init_history()
463 self.init_encoding()
463 self.init_encoding()
464 self.init_prefilter()
464 self.init_prefilter()
465
465
466 self.init_syntax_highlighting()
466 self.init_syntax_highlighting()
467 self.init_hooks()
467 self.init_hooks()
468 self.init_pushd_popd_magic()
468 self.init_pushd_popd_magic()
469 # self.init_traceback_handlers use to be here, but we moved it below
469 # self.init_traceback_handlers use to be here, but we moved it below
470 # because it and init_io have to come after init_readline.
470 # because it and init_io have to come after init_readline.
471 self.init_user_ns()
471 self.init_user_ns()
472 self.init_logger()
472 self.init_logger()
473 self.init_builtins()
473 self.init_builtins()
474
474
475 # The following was in post_config_initialization
475 # The following was in post_config_initialization
476 self.init_inspector()
476 self.init_inspector()
477 # init_readline() must come before init_io(), because init_io uses
477 # init_readline() must come before init_io(), because init_io uses
478 # readline related things.
478 # readline related things.
479 self.init_readline()
479 self.init_readline()
480 # We save this here in case user code replaces raw_input, but it needs
480 # We save this here in case user code replaces raw_input, but it needs
481 # to be after init_readline(), because PyPy's readline works by replacing
481 # to be after init_readline(), because PyPy's readline works by replacing
482 # raw_input.
482 # raw_input.
483 if py3compat.PY3:
483 if py3compat.PY3:
484 self.raw_input_original = input
484 self.raw_input_original = input
485 else:
485 else:
486 self.raw_input_original = raw_input
486 self.raw_input_original = raw_input
487 # init_completer must come after init_readline, because it needs to
487 # init_completer must come after init_readline, because it needs to
488 # know whether readline is present or not system-wide to configure the
488 # know whether readline is present or not system-wide to configure the
489 # completers, since the completion machinery can now operate
489 # completers, since the completion machinery can now operate
490 # independently of readline (e.g. over the network)
490 # independently of readline (e.g. over the network)
491 self.init_completer()
491 self.init_completer()
492 # TODO: init_io() needs to happen before init_traceback handlers
492 # TODO: init_io() needs to happen before init_traceback handlers
493 # because the traceback handlers hardcode the stdout/stderr streams.
493 # because the traceback handlers hardcode the stdout/stderr streams.
494 # This logic in in debugger.Pdb and should eventually be changed.
494 # This logic in in debugger.Pdb and should eventually be changed.
495 self.init_io()
495 self.init_io()
496 self.init_traceback_handlers(custom_exceptions)
496 self.init_traceback_handlers(custom_exceptions)
497 self.init_prompts()
497 self.init_prompts()
498 self.init_display_formatter()
498 self.init_display_formatter()
499 self.init_display_pub()
499 self.init_display_pub()
500 self.init_data_pub()
500 self.init_data_pub()
501 self.init_displayhook()
501 self.init_displayhook()
502 self.init_latextool()
502 self.init_latextool()
503 self.init_magics()
503 self.init_magics()
504 self.init_alias()
504 self.init_alias()
505 self.init_logstart()
505 self.init_logstart()
506 self.init_pdb()
506 self.init_pdb()
507 self.init_extension_manager()
507 self.init_extension_manager()
508 self.init_payload()
508 self.init_payload()
509 self.hooks.late_startup_hook()
509 self.hooks.late_startup_hook()
510 atexit.register(self.atexit_operations)
510 atexit.register(self.atexit_operations)
511
511
512 def get_ipython(self):
512 def get_ipython(self):
513 """Return the currently running IPython instance."""
513 """Return the currently running IPython instance."""
514 return self
514 return self
515
515
516 #-------------------------------------------------------------------------
516 #-------------------------------------------------------------------------
517 # Trait changed handlers
517 # Trait changed handlers
518 #-------------------------------------------------------------------------
518 #-------------------------------------------------------------------------
519
519
520 def _ipython_dir_changed(self, name, new):
520 def _ipython_dir_changed(self, name, new):
521 if not os.path.isdir(new):
521 if not os.path.isdir(new):
522 os.makedirs(new, mode = 0o777)
522 os.makedirs(new, mode = 0o777)
523
523
524 def set_autoindent(self,value=None):
524 def set_autoindent(self,value=None):
525 """Set the autoindent flag, checking for readline support.
525 """Set the autoindent flag, checking for readline support.
526
526
527 If called with no arguments, it acts as a toggle."""
527 If called with no arguments, it acts as a toggle."""
528
528
529 if value != 0 and not self.has_readline:
529 if value != 0 and not self.has_readline:
530 if os.name == 'posix':
530 if os.name == 'posix':
531 warn("The auto-indent feature requires the readline library")
531 warn("The auto-indent feature requires the readline library")
532 self.autoindent = 0
532 self.autoindent = 0
533 return
533 return
534 if value is None:
534 if value is None:
535 self.autoindent = not self.autoindent
535 self.autoindent = not self.autoindent
536 else:
536 else:
537 self.autoindent = value
537 self.autoindent = value
538
538
539 #-------------------------------------------------------------------------
539 #-------------------------------------------------------------------------
540 # init_* methods called by __init__
540 # init_* methods called by __init__
541 #-------------------------------------------------------------------------
541 #-------------------------------------------------------------------------
542
542
543 def init_ipython_dir(self, ipython_dir):
543 def init_ipython_dir(self, ipython_dir):
544 if ipython_dir is not None:
544 if ipython_dir is not None:
545 self.ipython_dir = ipython_dir
545 self.ipython_dir = ipython_dir
546 return
546 return
547
547
548 self.ipython_dir = get_ipython_dir()
548 self.ipython_dir = get_ipython_dir()
549
549
550 def init_profile_dir(self, profile_dir):
550 def init_profile_dir(self, profile_dir):
551 if profile_dir is not None:
551 if profile_dir is not None:
552 self.profile_dir = profile_dir
552 self.profile_dir = profile_dir
553 return
553 return
554 self.profile_dir =\
554 self.profile_dir =\
555 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
555 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
556
556
557 def init_instance_attrs(self):
557 def init_instance_attrs(self):
558 self.more = False
558 self.more = False
559
559
560 # command compiler
560 # command compiler
561 self.compile = CachingCompiler()
561 self.compile = CachingCompiler()
562
562
563 # Make an empty namespace, which extension writers can rely on both
563 # Make an empty namespace, which extension writers can rely on both
564 # existing and NEVER being used by ipython itself. This gives them a
564 # existing and NEVER being used by ipython itself. This gives them a
565 # convenient location for storing additional information and state
565 # convenient location for storing additional information and state
566 # their extensions may require, without fear of collisions with other
566 # their extensions may require, without fear of collisions with other
567 # ipython names that may develop later.
567 # ipython names that may develop later.
568 self.meta = Struct()
568 self.meta = Struct()
569
569
570 # Temporary files used for various purposes. Deleted at exit.
570 # Temporary files used for various purposes. Deleted at exit.
571 self.tempfiles = []
571 self.tempfiles = []
572
572
573 # Keep track of readline usage (later set by init_readline)
573 # Keep track of readline usage (later set by init_readline)
574 self.has_readline = False
574 self.has_readline = False
575
575
576 # keep track of where we started running (mainly for crash post-mortem)
576 # keep track of where we started running (mainly for crash post-mortem)
577 # This is not being used anywhere currently.
577 # This is not being used anywhere currently.
578 self.starting_dir = os.getcwdu()
578 self.starting_dir = os.getcwdu()
579
579
580 # Indentation management
580 # Indentation management
581 self.indent_current_nsp = 0
581 self.indent_current_nsp = 0
582
582
583 # Dict to track post-execution functions that have been registered
583 # Dict to track post-execution functions that have been registered
584 self._post_execute = {}
584 self._post_execute = {}
585
585
586 def init_environment(self):
586 def init_environment(self):
587 """Any changes we need to make to the user's environment."""
587 """Any changes we need to make to the user's environment."""
588 pass
588 pass
589
589
590 def init_encoding(self):
590 def init_encoding(self):
591 # Get system encoding at startup time. Certain terminals (like Emacs
591 # Get system encoding at startup time. Certain terminals (like Emacs
592 # under Win32 have it set to None, and we need to have a known valid
592 # under Win32 have it set to None, and we need to have a known valid
593 # encoding to use in the raw_input() method
593 # encoding to use in the raw_input() method
594 try:
594 try:
595 self.stdin_encoding = sys.stdin.encoding or 'ascii'
595 self.stdin_encoding = sys.stdin.encoding or 'ascii'
596 except AttributeError:
596 except AttributeError:
597 self.stdin_encoding = 'ascii'
597 self.stdin_encoding = 'ascii'
598
598
599 def init_syntax_highlighting(self):
599 def init_syntax_highlighting(self):
600 # Python source parser/formatter for syntax highlighting
600 # Python source parser/formatter for syntax highlighting
601 pyformat = PyColorize.Parser().format
601 pyformat = PyColorize.Parser().format
602 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
602 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
603
603
604 def init_pushd_popd_magic(self):
604 def init_pushd_popd_magic(self):
605 # for pushd/popd management
605 # for pushd/popd management
606 self.home_dir = get_home_dir()
606 self.home_dir = get_home_dir()
607
607
608 self.dir_stack = []
608 self.dir_stack = []
609
609
610 def init_logger(self):
610 def init_logger(self):
611 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
611 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
612 logmode='rotate')
612 logmode='rotate')
613
613
614 def init_logstart(self):
614 def init_logstart(self):
615 """Initialize logging in case it was requested at the command line.
615 """Initialize logging in case it was requested at the command line.
616 """
616 """
617 if self.logappend:
617 if self.logappend:
618 self.magic('logstart %s append' % self.logappend)
618 self.magic('logstart %s append' % self.logappend)
619 elif self.logfile:
619 elif self.logfile:
620 self.magic('logstart %s' % self.logfile)
620 self.magic('logstart %s' % self.logfile)
621 elif self.logstart:
621 elif self.logstart:
622 self.magic('logstart')
622 self.magic('logstart')
623
623
624 def init_builtins(self):
624 def init_builtins(self):
625 # A single, static flag that we set to True. Its presence indicates
625 # A single, static flag that we set to True. Its presence indicates
626 # that an IPython shell has been created, and we make no attempts at
626 # that an IPython shell has been created, and we make no attempts at
627 # removing on exit or representing the existence of more than one
627 # removing on exit or representing the existence of more than one
628 # IPython at a time.
628 # IPython at a time.
629 builtin_mod.__dict__['__IPYTHON__'] = True
629 builtin_mod.__dict__['__IPYTHON__'] = True
630
630
631 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
631 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
632 # manage on enter/exit, but with all our shells it's virtually
632 # manage on enter/exit, but with all our shells it's virtually
633 # impossible to get all the cases right. We're leaving the name in for
633 # impossible to get all the cases right. We're leaving the name in for
634 # those who adapted their codes to check for this flag, but will
634 # those who adapted their codes to check for this flag, but will
635 # eventually remove it after a few more releases.
635 # eventually remove it after a few more releases.
636 builtin_mod.__dict__['__IPYTHON__active'] = \
636 builtin_mod.__dict__['__IPYTHON__active'] = \
637 'Deprecated, check for __IPYTHON__'
637 'Deprecated, check for __IPYTHON__'
638
638
639 self.builtin_trap = BuiltinTrap(shell=self)
639 self.builtin_trap = BuiltinTrap(shell=self)
640
640
641 def init_inspector(self):
641 def init_inspector(self):
642 # Object inspector
642 # Object inspector
643 self.inspector = oinspect.Inspector(oinspect.InspectColors,
643 self.inspector = oinspect.Inspector(oinspect.InspectColors,
644 PyColorize.ANSICodeColors,
644 PyColorize.ANSICodeColors,
645 'NoColor',
645 'NoColor',
646 self.object_info_string_level)
646 self.object_info_string_level)
647
647
648 def init_io(self):
648 def init_io(self):
649 # This will just use sys.stdout and sys.stderr. If you want to
649 # This will just use sys.stdout and sys.stderr. If you want to
650 # override sys.stdout and sys.stderr themselves, you need to do that
650 # override sys.stdout and sys.stderr themselves, you need to do that
651 # *before* instantiating this class, because io holds onto
651 # *before* instantiating this class, because io holds onto
652 # references to the underlying streams.
652 # references to the underlying streams.
653 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
653 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
654 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
654 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
655 else:
655 else:
656 io.stdout = io.IOStream(sys.stdout)
656 io.stdout = io.IOStream(sys.stdout)
657 io.stderr = io.IOStream(sys.stderr)
657 io.stderr = io.IOStream(sys.stderr)
658
658
659 def init_prompts(self):
659 def init_prompts(self):
660 self.prompt_manager = PromptManager(shell=self, parent=self)
660 self.prompt_manager = PromptManager(shell=self, parent=self)
661 self.configurables.append(self.prompt_manager)
661 self.configurables.append(self.prompt_manager)
662 # Set system prompts, so that scripts can decide if they are running
662 # Set system prompts, so that scripts can decide if they are running
663 # interactively.
663 # interactively.
664 sys.ps1 = 'In : '
664 sys.ps1 = 'In : '
665 sys.ps2 = '...: '
665 sys.ps2 = '...: '
666 sys.ps3 = 'Out: '
666 sys.ps3 = 'Out: '
667
667
668 def init_display_formatter(self):
668 def init_display_formatter(self):
669 self.display_formatter = DisplayFormatter(parent=self)
669 self.display_formatter = DisplayFormatter(parent=self)
670 self.configurables.append(self.display_formatter)
670 self.configurables.append(self.display_formatter)
671
671
672 def init_display_pub(self):
672 def init_display_pub(self):
673 self.display_pub = self.display_pub_class(parent=self)
673 self.display_pub = self.display_pub_class(parent=self)
674 self.configurables.append(self.display_pub)
674 self.configurables.append(self.display_pub)
675
675
676 def init_data_pub(self):
676 def init_data_pub(self):
677 if not self.data_pub_class:
677 if not self.data_pub_class:
678 self.data_pub = None
678 self.data_pub = None
679 return
679 return
680 self.data_pub = self.data_pub_class(parent=self)
680 self.data_pub = self.data_pub_class(parent=self)
681 self.configurables.append(self.data_pub)
681 self.configurables.append(self.data_pub)
682
682
683 def init_displayhook(self):
683 def init_displayhook(self):
684 # Initialize displayhook, set in/out prompts and printing system
684 # Initialize displayhook, set in/out prompts and printing system
685 self.displayhook = self.displayhook_class(
685 self.displayhook = self.displayhook_class(
686 parent=self,
686 parent=self,
687 shell=self,
687 shell=self,
688 cache_size=self.cache_size,
688 cache_size=self.cache_size,
689 )
689 )
690 self.configurables.append(self.displayhook)
690 self.configurables.append(self.displayhook)
691 # This is a context manager that installs/revmoes the displayhook at
691 # This is a context manager that installs/revmoes the displayhook at
692 # the appropriate time.
692 # the appropriate time.
693 self.display_trap = DisplayTrap(hook=self.displayhook)
693 self.display_trap = DisplayTrap(hook=self.displayhook)
694
694
695 def init_latextool(self):
695 def init_latextool(self):
696 """Configure LaTeXTool."""
696 """Configure LaTeXTool."""
697 cfg = LaTeXTool.instance(parent=self)
697 cfg = LaTeXTool.instance(parent=self)
698 if cfg not in self.configurables:
698 if cfg not in self.configurables:
699 self.configurables.append(cfg)
699 self.configurables.append(cfg)
700
700
701 def init_virtualenv(self):
701 def init_virtualenv(self):
702 """Add a virtualenv to sys.path so the user can import modules from it.
702 """Add a virtualenv to sys.path so the user can import modules from it.
703 This isn't perfect: it doesn't use the Python interpreter with which the
703 This isn't perfect: it doesn't use the Python interpreter with which the
704 virtualenv was built, and it ignores the --no-site-packages option. A
704 virtualenv was built, and it ignores the --no-site-packages option. A
705 warning will appear suggesting the user installs IPython in the
705 warning will appear suggesting the user installs IPython in the
706 virtualenv, but for many cases, it probably works well enough.
706 virtualenv, but for many cases, it probably works well enough.
707
707
708 Adapted from code snippets online.
708 Adapted from code snippets online.
709
709
710 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
710 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
711 """
711 """
712 if 'VIRTUAL_ENV' not in os.environ:
712 if 'VIRTUAL_ENV' not in os.environ:
713 # Not in a virtualenv
713 # Not in a virtualenv
714 return
714 return
715
715
716 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
716 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
717 # Running properly in the virtualenv, don't need to do anything
717 # Running properly in the virtualenv, don't need to do anything
718 return
718 return
719
719
720 warn("Attempting to work in a virtualenv. If you encounter problems, please "
720 warn("Attempting to work in a virtualenv. If you encounter problems, please "
721 "install IPython inside the virtualenv.")
721 "install IPython inside the virtualenv.")
722 if sys.platform == "win32":
722 if sys.platform == "win32":
723 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
723 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
724 else:
724 else:
725 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
725 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
726 'python%d.%d' % sys.version_info[:2], 'site-packages')
726 'python%d.%d' % sys.version_info[:2], 'site-packages')
727
727
728 import site
728 import site
729 sys.path.insert(0, virtual_env)
729 sys.path.insert(0, virtual_env)
730 site.addsitedir(virtual_env)
730 site.addsitedir(virtual_env)
731
731
732 #-------------------------------------------------------------------------
732 #-------------------------------------------------------------------------
733 # Things related to injections into the sys module
733 # Things related to injections into the sys module
734 #-------------------------------------------------------------------------
734 #-------------------------------------------------------------------------
735
735
736 def save_sys_module_state(self):
736 def save_sys_module_state(self):
737 """Save the state of hooks in the sys module.
737 """Save the state of hooks in the sys module.
738
738
739 This has to be called after self.user_module is created.
739 This has to be called after self.user_module is created.
740 """
740 """
741 self._orig_sys_module_state = {}
741 self._orig_sys_module_state = {}
742 self._orig_sys_module_state['stdin'] = sys.stdin
742 self._orig_sys_module_state['stdin'] = sys.stdin
743 self._orig_sys_module_state['stdout'] = sys.stdout
743 self._orig_sys_module_state['stdout'] = sys.stdout
744 self._orig_sys_module_state['stderr'] = sys.stderr
744 self._orig_sys_module_state['stderr'] = sys.stderr
745 self._orig_sys_module_state['excepthook'] = sys.excepthook
745 self._orig_sys_module_state['excepthook'] = sys.excepthook
746 self._orig_sys_modules_main_name = self.user_module.__name__
746 self._orig_sys_modules_main_name = self.user_module.__name__
747 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
747 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
748
748
749 def restore_sys_module_state(self):
749 def restore_sys_module_state(self):
750 """Restore the state of the sys module."""
750 """Restore the state of the sys module."""
751 try:
751 try:
752 for k, v in self._orig_sys_module_state.iteritems():
752 for k, v in self._orig_sys_module_state.iteritems():
753 setattr(sys, k, v)
753 setattr(sys, k, v)
754 except AttributeError:
754 except AttributeError:
755 pass
755 pass
756 # Reset what what done in self.init_sys_modules
756 # Reset what what done in self.init_sys_modules
757 if self._orig_sys_modules_main_mod is not None:
757 if self._orig_sys_modules_main_mod is not None:
758 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
758 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
759
759
760 #-------------------------------------------------------------------------
760 #-------------------------------------------------------------------------
761 # Things related to hooks
761 # Things related to hooks
762 #-------------------------------------------------------------------------
762 #-------------------------------------------------------------------------
763
763
764 def init_hooks(self):
764 def init_hooks(self):
765 # hooks holds pointers used for user-side customizations
765 # hooks holds pointers used for user-side customizations
766 self.hooks = Struct()
766 self.hooks = Struct()
767
767
768 self.strdispatchers = {}
768 self.strdispatchers = {}
769
769
770 # Set all default hooks, defined in the IPython.hooks module.
770 # Set all default hooks, defined in the IPython.hooks module.
771 hooks = IPython.core.hooks
771 hooks = IPython.core.hooks
772 for hook_name in hooks.__all__:
772 for hook_name in hooks.__all__:
773 # default hooks have priority 100, i.e. low; user hooks should have
773 # default hooks have priority 100, i.e. low; user hooks should have
774 # 0-100 priority
774 # 0-100 priority
775 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
775 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
776
776
777 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
777 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
778 """set_hook(name,hook) -> sets an internal IPython hook.
778 """set_hook(name,hook) -> sets an internal IPython hook.
779
779
780 IPython exposes some of its internal API as user-modifiable hooks. By
780 IPython exposes some of its internal API as user-modifiable hooks. By
781 adding your function to one of these hooks, you can modify IPython's
781 adding your function to one of these hooks, you can modify IPython's
782 behavior to call at runtime your own routines."""
782 behavior to call at runtime your own routines."""
783
783
784 # At some point in the future, this should validate the hook before it
784 # At some point in the future, this should validate the hook before it
785 # accepts it. Probably at least check that the hook takes the number
785 # accepts it. Probably at least check that the hook takes the number
786 # of args it's supposed to.
786 # of args it's supposed to.
787
787
788 f = types.MethodType(hook,self)
788 f = types.MethodType(hook,self)
789
789
790 # check if the hook is for strdispatcher first
790 # check if the hook is for strdispatcher first
791 if str_key is not None:
791 if str_key is not None:
792 sdp = self.strdispatchers.get(name, StrDispatch())
792 sdp = self.strdispatchers.get(name, StrDispatch())
793 sdp.add_s(str_key, f, priority )
793 sdp.add_s(str_key, f, priority )
794 self.strdispatchers[name] = sdp
794 self.strdispatchers[name] = sdp
795 return
795 return
796 if re_key is not None:
796 if re_key is not None:
797 sdp = self.strdispatchers.get(name, StrDispatch())
797 sdp = self.strdispatchers.get(name, StrDispatch())
798 sdp.add_re(re.compile(re_key), f, priority )
798 sdp.add_re(re.compile(re_key), f, priority )
799 self.strdispatchers[name] = sdp
799 self.strdispatchers[name] = sdp
800 return
800 return
801
801
802 dp = getattr(self.hooks, name, None)
802 dp = getattr(self.hooks, name, None)
803 if name not in IPython.core.hooks.__all__:
803 if name not in IPython.core.hooks.__all__:
804 print("Warning! Hook '%s' is not one of %s" % \
804 print("Warning! Hook '%s' is not one of %s" % \
805 (name, IPython.core.hooks.__all__ ))
805 (name, IPython.core.hooks.__all__ ))
806 if not dp:
806 if not dp:
807 dp = IPython.core.hooks.CommandChainDispatcher()
807 dp = IPython.core.hooks.CommandChainDispatcher()
808
808
809 try:
809 try:
810 dp.add(f,priority)
810 dp.add(f,priority)
811 except AttributeError:
811 except AttributeError:
812 # it was not commandchain, plain old func - replace
812 # it was not commandchain, plain old func - replace
813 dp = f
813 dp = f
814
814
815 setattr(self.hooks,name, dp)
815 setattr(self.hooks,name, dp)
816
816
817 def register_post_execute(self, func):
817 def register_post_execute(self, func):
818 """Register a function for calling after code execution.
818 """Register a function for calling after code execution.
819 """
819 """
820 if not callable(func):
820 if not callable(func):
821 raise ValueError('argument %s must be callable' % func)
821 raise ValueError('argument %s must be callable' % func)
822 self._post_execute[func] = True
822 self._post_execute[func] = True
823
823
824 #-------------------------------------------------------------------------
824 #-------------------------------------------------------------------------
825 # Things related to the "main" module
825 # Things related to the "main" module
826 #-------------------------------------------------------------------------
826 #-------------------------------------------------------------------------
827
827
828 def new_main_mod(self, filename, modname):
828 def new_main_mod(self, filename, modname):
829 """Return a new 'main' module object for user code execution.
829 """Return a new 'main' module object for user code execution.
830
830
831 ``filename`` should be the path of the script which will be run in the
831 ``filename`` should be the path of the script which will be run in the
832 module. Requests with the same filename will get the same module, with
832 module. Requests with the same filename will get the same module, with
833 its namespace cleared.
833 its namespace cleared.
834
834
835 ``modname`` should be the module name - normally either '__main__' or
835 ``modname`` should be the module name - normally either '__main__' or
836 the basename of the file without the extension.
836 the basename of the file without the extension.
837
837
838 When scripts are executed via %run, we must keep a reference to their
838 When scripts are executed via %run, we must keep a reference to their
839 __main__ module around so that Python doesn't
839 __main__ module around so that Python doesn't
840 clear it, rendering references to module globals useless.
840 clear it, rendering references to module globals useless.
841
841
842 This method keeps said reference in a private dict, keyed by the
842 This method keeps said reference in a private dict, keyed by the
843 absolute path of the script. This way, for multiple executions of the
843 absolute path of the script. This way, for multiple executions of the
844 same script we only keep one copy of the namespace (the last one),
844 same script we only keep one copy of the namespace (the last one),
845 thus preventing memory leaks from old references while allowing the
845 thus preventing memory leaks from old references while allowing the
846 objects from the last execution to be accessible.
846 objects from the last execution to be accessible.
847 """
847 """
848 filename = os.path.abspath(filename)
848 filename = os.path.abspath(filename)
849 try:
849 try:
850 main_mod = self._main_mod_cache[filename]
850 main_mod = self._main_mod_cache[filename]
851 except KeyError:
851 except KeyError:
852 main_mod = self._main_mod_cache[filename] = types.ModuleType(modname,
852 main_mod = self._main_mod_cache[filename] = types.ModuleType(modname,
853 doc="Module created for script run in IPython")
853 doc="Module created for script run in IPython")
854 else:
854 else:
855 main_mod.__dict__.clear()
855 main_mod.__dict__.clear()
856 main_mod.__name__ = modname
856 main_mod.__name__ = modname
857
857
858 main_mod.__file__ = filename
858 main_mod.__file__ = filename
859 # It seems pydoc (and perhaps others) needs any module instance to
859 # It seems pydoc (and perhaps others) needs any module instance to
860 # implement a __nonzero__ method
860 # implement a __nonzero__ method
861 main_mod.__nonzero__ = lambda : True
861 main_mod.__nonzero__ = lambda : True
862
862
863 return main_mod
863 return main_mod
864
864
865 def clear_main_mod_cache(self):
865 def clear_main_mod_cache(self):
866 """Clear the cache of main modules.
866 """Clear the cache of main modules.
867
867
868 Mainly for use by utilities like %reset.
868 Mainly for use by utilities like %reset.
869
869
870 Examples
870 Examples
871 --------
871 --------
872
872
873 In [15]: import IPython
873 In [15]: import IPython
874
874
875 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
875 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
876
876
877 In [17]: len(_ip._main_mod_cache) > 0
877 In [17]: len(_ip._main_mod_cache) > 0
878 Out[17]: True
878 Out[17]: True
879
879
880 In [18]: _ip.clear_main_mod_cache()
880 In [18]: _ip.clear_main_mod_cache()
881
881
882 In [19]: len(_ip._main_mod_cache) == 0
882 In [19]: len(_ip._main_mod_cache) == 0
883 Out[19]: True
883 Out[19]: True
884 """
884 """
885 self._main_mod_cache.clear()
885 self._main_mod_cache.clear()
886
886
887 #-------------------------------------------------------------------------
887 #-------------------------------------------------------------------------
888 # Things related to debugging
888 # Things related to debugging
889 #-------------------------------------------------------------------------
889 #-------------------------------------------------------------------------
890
890
891 def init_pdb(self):
891 def init_pdb(self):
892 # Set calling of pdb on exceptions
892 # Set calling of pdb on exceptions
893 # self.call_pdb is a property
893 # self.call_pdb is a property
894 self.call_pdb = self.pdb
894 self.call_pdb = self.pdb
895
895
896 def _get_call_pdb(self):
896 def _get_call_pdb(self):
897 return self._call_pdb
897 return self._call_pdb
898
898
899 def _set_call_pdb(self,val):
899 def _set_call_pdb(self,val):
900
900
901 if val not in (0,1,False,True):
901 if val not in (0,1,False,True):
902 raise ValueError('new call_pdb value must be boolean')
902 raise ValueError('new call_pdb value must be boolean')
903
903
904 # store value in instance
904 # store value in instance
905 self._call_pdb = val
905 self._call_pdb = val
906
906
907 # notify the actual exception handlers
907 # notify the actual exception handlers
908 self.InteractiveTB.call_pdb = val
908 self.InteractiveTB.call_pdb = val
909
909
910 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
910 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
911 'Control auto-activation of pdb at exceptions')
911 'Control auto-activation of pdb at exceptions')
912
912
913 def debugger(self,force=False):
913 def debugger(self,force=False):
914 """Call the pydb/pdb debugger.
914 """Call the pydb/pdb debugger.
915
915
916 Keywords:
916 Keywords:
917
917
918 - force(False): by default, this routine checks the instance call_pdb
918 - force(False): by default, this routine checks the instance call_pdb
919 flag and does not actually invoke the debugger if the flag is false.
919 flag and does not actually invoke the debugger if the flag is false.
920 The 'force' option forces the debugger to activate even if the flag
920 The 'force' option forces the debugger to activate even if the flag
921 is false.
921 is false.
922 """
922 """
923
923
924 if not (force or self.call_pdb):
924 if not (force or self.call_pdb):
925 return
925 return
926
926
927 if not hasattr(sys,'last_traceback'):
927 if not hasattr(sys,'last_traceback'):
928 error('No traceback has been produced, nothing to debug.')
928 error('No traceback has been produced, nothing to debug.')
929 return
929 return
930
930
931 # use pydb if available
931 # use pydb if available
932 if debugger.has_pydb:
932 if debugger.has_pydb:
933 from pydb import pm
933 from pydb import pm
934 else:
934 else:
935 # fallback to our internal debugger
935 # fallback to our internal debugger
936 pm = lambda : self.InteractiveTB.debugger(force=True)
936 pm = lambda : self.InteractiveTB.debugger(force=True)
937
937
938 with self.readline_no_record:
938 with self.readline_no_record:
939 pm()
939 pm()
940
940
941 #-------------------------------------------------------------------------
941 #-------------------------------------------------------------------------
942 # Things related to IPython's various namespaces
942 # Things related to IPython's various namespaces
943 #-------------------------------------------------------------------------
943 #-------------------------------------------------------------------------
944 default_user_namespaces = True
944 default_user_namespaces = True
945
945
946 def init_create_namespaces(self, user_module=None, user_ns=None):
946 def init_create_namespaces(self, user_module=None, user_ns=None):
947 # Create the namespace where the user will operate. user_ns is
947 # Create the namespace where the user will operate. user_ns is
948 # normally the only one used, and it is passed to the exec calls as
948 # normally the only one used, and it is passed to the exec calls as
949 # the locals argument. But we do carry a user_global_ns namespace
949 # the locals argument. But we do carry a user_global_ns namespace
950 # given as the exec 'globals' argument, This is useful in embedding
950 # given as the exec 'globals' argument, This is useful in embedding
951 # situations where the ipython shell opens in a context where the
951 # situations where the ipython shell opens in a context where the
952 # distinction between locals and globals is meaningful. For
952 # distinction between locals and globals is meaningful. For
953 # non-embedded contexts, it is just the same object as the user_ns dict.
953 # non-embedded contexts, it is just the same object as the user_ns dict.
954
954
955 # FIXME. For some strange reason, __builtins__ is showing up at user
955 # FIXME. For some strange reason, __builtins__ is showing up at user
956 # level as a dict instead of a module. This is a manual fix, but I
956 # level as a dict instead of a module. This is a manual fix, but I
957 # should really track down where the problem is coming from. Alex
957 # should really track down where the problem is coming from. Alex
958 # Schmolck reported this problem first.
958 # Schmolck reported this problem first.
959
959
960 # A useful post by Alex Martelli on this topic:
960 # A useful post by Alex Martelli on this topic:
961 # Re: inconsistent value from __builtins__
961 # Re: inconsistent value from __builtins__
962 # Von: Alex Martelli <aleaxit@yahoo.com>
962 # Von: Alex Martelli <aleaxit@yahoo.com>
963 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
963 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
964 # Gruppen: comp.lang.python
964 # Gruppen: comp.lang.python
965
965
966 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
966 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
967 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
967 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
968 # > <type 'dict'>
968 # > <type 'dict'>
969 # > >>> print type(__builtins__)
969 # > >>> print type(__builtins__)
970 # > <type 'module'>
970 # > <type 'module'>
971 # > Is this difference in return value intentional?
971 # > Is this difference in return value intentional?
972
972
973 # Well, it's documented that '__builtins__' can be either a dictionary
973 # Well, it's documented that '__builtins__' can be either a dictionary
974 # or a module, and it's been that way for a long time. Whether it's
974 # or a module, and it's been that way for a long time. Whether it's
975 # intentional (or sensible), I don't know. In any case, the idea is
975 # intentional (or sensible), I don't know. In any case, the idea is
976 # that if you need to access the built-in namespace directly, you
976 # that if you need to access the built-in namespace directly, you
977 # should start with "import __builtin__" (note, no 's') which will
977 # should start with "import __builtin__" (note, no 's') which will
978 # definitely give you a module. Yeah, it's somewhat confusing:-(.
978 # definitely give you a module. Yeah, it's somewhat confusing:-(.
979
979
980 # These routines return a properly built module and dict as needed by
980 # These routines return a properly built module and dict as needed by
981 # the rest of the code, and can also be used by extension writers to
981 # the rest of the code, and can also be used by extension writers to
982 # generate properly initialized namespaces.
982 # generate properly initialized namespaces.
983 if (user_ns is not None) or (user_module is not None):
983 if (user_ns is not None) or (user_module is not None):
984 self.default_user_namespaces = False
984 self.default_user_namespaces = False
985 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
985 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
986
986
987 # A record of hidden variables we have added to the user namespace, so
987 # A record of hidden variables we have added to the user namespace, so
988 # we can list later only variables defined in actual interactive use.
988 # we can list later only variables defined in actual interactive use.
989 self.user_ns_hidden = {}
989 self.user_ns_hidden = {}
990
990
991 # Now that FakeModule produces a real module, we've run into a nasty
991 # Now that FakeModule produces a real module, we've run into a nasty
992 # problem: after script execution (via %run), the module where the user
992 # problem: after script execution (via %run), the module where the user
993 # code ran is deleted. Now that this object is a true module (needed
993 # code ran is deleted. Now that this object is a true module (needed
994 # so docetst and other tools work correctly), the Python module
994 # so docetst and other tools work correctly), the Python module
995 # teardown mechanism runs over it, and sets to None every variable
995 # teardown mechanism runs over it, and sets to None every variable
996 # present in that module. Top-level references to objects from the
996 # present in that module. Top-level references to objects from the
997 # script survive, because the user_ns is updated with them. However,
997 # script survive, because the user_ns is updated with them. However,
998 # calling functions defined in the script that use other things from
998 # calling functions defined in the script that use other things from
999 # the script will fail, because the function's closure had references
999 # the script will fail, because the function's closure had references
1000 # to the original objects, which are now all None. So we must protect
1000 # to the original objects, which are now all None. So we must protect
1001 # these modules from deletion by keeping a cache.
1001 # these modules from deletion by keeping a cache.
1002 #
1002 #
1003 # To avoid keeping stale modules around (we only need the one from the
1003 # To avoid keeping stale modules around (we only need the one from the
1004 # last run), we use a dict keyed with the full path to the script, so
1004 # last run), we use a dict keyed with the full path to the script, so
1005 # only the last version of the module is held in the cache. Note,
1005 # only the last version of the module is held in the cache. Note,
1006 # however, that we must cache the module *namespace contents* (their
1006 # however, that we must cache the module *namespace contents* (their
1007 # __dict__). Because if we try to cache the actual modules, old ones
1007 # __dict__). Because if we try to cache the actual modules, old ones
1008 # (uncached) could be destroyed while still holding references (such as
1008 # (uncached) could be destroyed while still holding references (such as
1009 # those held by GUI objects that tend to be long-lived)>
1009 # those held by GUI objects that tend to be long-lived)>
1010 #
1010 #
1011 # The %reset command will flush this cache. See the cache_main_mod()
1011 # The %reset command will flush this cache. See the cache_main_mod()
1012 # and clear_main_mod_cache() methods for details on use.
1012 # and clear_main_mod_cache() methods for details on use.
1013
1013
1014 # This is the cache used for 'main' namespaces
1014 # This is the cache used for 'main' namespaces
1015 self._main_mod_cache = {}
1015 self._main_mod_cache = {}
1016
1016
1017 # A table holding all the namespaces IPython deals with, so that
1017 # A table holding all the namespaces IPython deals with, so that
1018 # introspection facilities can search easily.
1018 # introspection facilities can search easily.
1019 self.ns_table = {'user_global':self.user_module.__dict__,
1019 self.ns_table = {'user_global':self.user_module.__dict__,
1020 'user_local':self.user_ns,
1020 'user_local':self.user_ns,
1021 'builtin':builtin_mod.__dict__
1021 'builtin':builtin_mod.__dict__
1022 }
1022 }
1023
1023
1024 @property
1024 @property
1025 def user_global_ns(self):
1025 def user_global_ns(self):
1026 return self.user_module.__dict__
1026 return self.user_module.__dict__
1027
1027
1028 def prepare_user_module(self, user_module=None, user_ns=None):
1028 def prepare_user_module(self, user_module=None, user_ns=None):
1029 """Prepare the module and namespace in which user code will be run.
1029 """Prepare the module and namespace in which user code will be run.
1030
1030
1031 When IPython is started normally, both parameters are None: a new module
1031 When IPython is started normally, both parameters are None: a new module
1032 is created automatically, and its __dict__ used as the namespace.
1032 is created automatically, and its __dict__ used as the namespace.
1033
1033
1034 If only user_module is provided, its __dict__ is used as the namespace.
1034 If only user_module is provided, its __dict__ is used as the namespace.
1035 If only user_ns is provided, a dummy module is created, and user_ns
1035 If only user_ns is provided, a dummy module is created, and user_ns
1036 becomes the global namespace. If both are provided (as they may be
1036 becomes the global namespace. If both are provided (as they may be
1037 when embedding), user_ns is the local namespace, and user_module
1037 when embedding), user_ns is the local namespace, and user_module
1038 provides the global namespace.
1038 provides the global namespace.
1039
1039
1040 Parameters
1040 Parameters
1041 ----------
1041 ----------
1042 user_module : module, optional
1042 user_module : module, optional
1043 The current user module in which IPython is being run. If None,
1043 The current user module in which IPython is being run. If None,
1044 a clean module will be created.
1044 a clean module will be created.
1045 user_ns : dict, optional
1045 user_ns : dict, optional
1046 A namespace in which to run interactive commands.
1046 A namespace in which to run interactive commands.
1047
1047
1048 Returns
1048 Returns
1049 -------
1049 -------
1050 A tuple of user_module and user_ns, each properly initialised.
1050 A tuple of user_module and user_ns, each properly initialised.
1051 """
1051 """
1052 if user_module is None and user_ns is not None:
1052 if user_module is None and user_ns is not None:
1053 user_ns.setdefault("__name__", "__main__")
1053 user_ns.setdefault("__name__", "__main__")
1054 user_module = DummyMod()
1054 user_module = DummyMod()
1055 user_module.__dict__ = user_ns
1055 user_module.__dict__ = user_ns
1056
1056
1057 if user_module is None:
1057 if user_module is None:
1058 user_module = types.ModuleType("__main__",
1058 user_module = types.ModuleType("__main__",
1059 doc="Automatically created module for IPython interactive environment")
1059 doc="Automatically created module for IPython interactive environment")
1060
1060
1061 # We must ensure that __builtin__ (without the final 's') is always
1061 # We must ensure that __builtin__ (without the final 's') is always
1062 # available and pointing to the __builtin__ *module*. For more details:
1062 # available and pointing to the __builtin__ *module*. For more details:
1063 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1063 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1064 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1064 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1065 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1065 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1066
1066
1067 if user_ns is None:
1067 if user_ns is None:
1068 user_ns = user_module.__dict__
1068 user_ns = user_module.__dict__
1069
1069
1070 return user_module, user_ns
1070 return user_module, user_ns
1071
1071
1072 def init_sys_modules(self):
1072 def init_sys_modules(self):
1073 # We need to insert into sys.modules something that looks like a
1073 # We need to insert into sys.modules something that looks like a
1074 # module but which accesses the IPython namespace, for shelve and
1074 # module but which accesses the IPython namespace, for shelve and
1075 # pickle to work interactively. Normally they rely on getting
1075 # pickle to work interactively. Normally they rely on getting
1076 # everything out of __main__, but for embedding purposes each IPython
1076 # everything out of __main__, but for embedding purposes each IPython
1077 # instance has its own private namespace, so we can't go shoving
1077 # instance has its own private namespace, so we can't go shoving
1078 # everything into __main__.
1078 # everything into __main__.
1079
1079
1080 # note, however, that we should only do this for non-embedded
1080 # note, however, that we should only do this for non-embedded
1081 # ipythons, which really mimic the __main__.__dict__ with their own
1081 # ipythons, which really mimic the __main__.__dict__ with their own
1082 # namespace. Embedded instances, on the other hand, should not do
1082 # namespace. Embedded instances, on the other hand, should not do
1083 # this because they need to manage the user local/global namespaces
1083 # this because they need to manage the user local/global namespaces
1084 # only, but they live within a 'normal' __main__ (meaning, they
1084 # only, but they live within a 'normal' __main__ (meaning, they
1085 # shouldn't overtake the execution environment of the script they're
1085 # shouldn't overtake the execution environment of the script they're
1086 # embedded in).
1086 # embedded in).
1087
1087
1088 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1088 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1089 main_name = self.user_module.__name__
1089 main_name = self.user_module.__name__
1090 sys.modules[main_name] = self.user_module
1090 sys.modules[main_name] = self.user_module
1091
1091
1092 def init_user_ns(self):
1092 def init_user_ns(self):
1093 """Initialize all user-visible namespaces to their minimum defaults.
1093 """Initialize all user-visible namespaces to their minimum defaults.
1094
1094
1095 Certain history lists are also initialized here, as they effectively
1095 Certain history lists are also initialized here, as they effectively
1096 act as user namespaces.
1096 act as user namespaces.
1097
1097
1098 Notes
1098 Notes
1099 -----
1099 -----
1100 All data structures here are only filled in, they are NOT reset by this
1100 All data structures here are only filled in, they are NOT reset by this
1101 method. If they were not empty before, data will simply be added to
1101 method. If they were not empty before, data will simply be added to
1102 therm.
1102 therm.
1103 """
1103 """
1104 # This function works in two parts: first we put a few things in
1104 # This function works in two parts: first we put a few things in
1105 # user_ns, and we sync that contents into user_ns_hidden so that these
1105 # user_ns, and we sync that contents into user_ns_hidden so that these
1106 # initial variables aren't shown by %who. After the sync, we add the
1106 # initial variables aren't shown by %who. After the sync, we add the
1107 # rest of what we *do* want the user to see with %who even on a new
1107 # rest of what we *do* want the user to see with %who even on a new
1108 # session (probably nothing, so theye really only see their own stuff)
1108 # session (probably nothing, so theye really only see their own stuff)
1109
1109
1110 # The user dict must *always* have a __builtin__ reference to the
1110 # The user dict must *always* have a __builtin__ reference to the
1111 # Python standard __builtin__ namespace, which must be imported.
1111 # Python standard __builtin__ namespace, which must be imported.
1112 # This is so that certain operations in prompt evaluation can be
1112 # This is so that certain operations in prompt evaluation can be
1113 # reliably executed with builtins. Note that we can NOT use
1113 # reliably executed with builtins. Note that we can NOT use
1114 # __builtins__ (note the 's'), because that can either be a dict or a
1114 # __builtins__ (note the 's'), because that can either be a dict or a
1115 # module, and can even mutate at runtime, depending on the context
1115 # module, and can even mutate at runtime, depending on the context
1116 # (Python makes no guarantees on it). In contrast, __builtin__ is
1116 # (Python makes no guarantees on it). In contrast, __builtin__ is
1117 # always a module object, though it must be explicitly imported.
1117 # always a module object, though it must be explicitly imported.
1118
1118
1119 # For more details:
1119 # For more details:
1120 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1120 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1121 ns = dict()
1121 ns = dict()
1122
1122
1123 # Put 'help' in the user namespace
1123 # Put 'help' in the user namespace
1124 try:
1124 try:
1125 from site import _Helper
1125 from site import _Helper
1126 ns['help'] = _Helper()
1126 ns['help'] = _Helper()
1127 except ImportError:
1127 except ImportError:
1128 warn('help() not available - check site.py')
1128 warn('help() not available - check site.py')
1129
1129
1130 # make global variables for user access to the histories
1130 # make global variables for user access to the histories
1131 ns['_ih'] = self.history_manager.input_hist_parsed
1131 ns['_ih'] = self.history_manager.input_hist_parsed
1132 ns['_oh'] = self.history_manager.output_hist
1132 ns['_oh'] = self.history_manager.output_hist
1133 ns['_dh'] = self.history_manager.dir_hist
1133 ns['_dh'] = self.history_manager.dir_hist
1134
1134
1135 ns['_sh'] = shadowns
1135 ns['_sh'] = shadowns
1136
1136
1137 # user aliases to input and output histories. These shouldn't show up
1137 # user aliases to input and output histories. These shouldn't show up
1138 # in %who, as they can have very large reprs.
1138 # in %who, as they can have very large reprs.
1139 ns['In'] = self.history_manager.input_hist_parsed
1139 ns['In'] = self.history_manager.input_hist_parsed
1140 ns['Out'] = self.history_manager.output_hist
1140 ns['Out'] = self.history_manager.output_hist
1141
1141
1142 # Store myself as the public api!!!
1142 # Store myself as the public api!!!
1143 ns['get_ipython'] = self.get_ipython
1143 ns['get_ipython'] = self.get_ipython
1144
1144
1145 ns['exit'] = self.exiter
1145 ns['exit'] = self.exiter
1146 ns['quit'] = self.exiter
1146 ns['quit'] = self.exiter
1147
1147
1148 # Sync what we've added so far to user_ns_hidden so these aren't seen
1148 # Sync what we've added so far to user_ns_hidden so these aren't seen
1149 # by %who
1149 # by %who
1150 self.user_ns_hidden.update(ns)
1150 self.user_ns_hidden.update(ns)
1151
1151
1152 # Anything put into ns now would show up in %who. Think twice before
1152 # Anything put into ns now would show up in %who. Think twice before
1153 # putting anything here, as we really want %who to show the user their
1153 # putting anything here, as we really want %who to show the user their
1154 # stuff, not our variables.
1154 # stuff, not our variables.
1155
1155
1156 # Finally, update the real user's namespace
1156 # Finally, update the real user's namespace
1157 self.user_ns.update(ns)
1157 self.user_ns.update(ns)
1158
1158
1159 @property
1159 @property
1160 def all_ns_refs(self):
1160 def all_ns_refs(self):
1161 """Get a list of references to all the namespace dictionaries in which
1161 """Get a list of references to all the namespace dictionaries in which
1162 IPython might store a user-created object.
1162 IPython might store a user-created object.
1163
1163
1164 Note that this does not include the displayhook, which also caches
1164 Note that this does not include the displayhook, which also caches
1165 objects from the output."""
1165 objects from the output."""
1166 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1166 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1167 [m.__dict__ for m in self._main_mod_cache.values()]
1167 [m.__dict__ for m in self._main_mod_cache.values()]
1168
1168
1169 def reset(self, new_session=True):
1169 def reset(self, new_session=True):
1170 """Clear all internal namespaces, and attempt to release references to
1170 """Clear all internal namespaces, and attempt to release references to
1171 user objects.
1171 user objects.
1172
1172
1173 If new_session is True, a new history session will be opened.
1173 If new_session is True, a new history session will be opened.
1174 """
1174 """
1175 # Clear histories
1175 # Clear histories
1176 self.history_manager.reset(new_session)
1176 self.history_manager.reset(new_session)
1177 # Reset counter used to index all histories
1177 # Reset counter used to index all histories
1178 if new_session:
1178 if new_session:
1179 self.execution_count = 1
1179 self.execution_count = 1
1180
1180
1181 # Flush cached output items
1181 # Flush cached output items
1182 if self.displayhook.do_full_cache:
1182 if self.displayhook.do_full_cache:
1183 self.displayhook.flush()
1183 self.displayhook.flush()
1184
1184
1185 # The main execution namespaces must be cleared very carefully,
1185 # The main execution namespaces must be cleared very carefully,
1186 # skipping the deletion of the builtin-related keys, because doing so
1186 # skipping the deletion of the builtin-related keys, because doing so
1187 # would cause errors in many object's __del__ methods.
1187 # would cause errors in many object's __del__ methods.
1188 if self.user_ns is not self.user_global_ns:
1188 if self.user_ns is not self.user_global_ns:
1189 self.user_ns.clear()
1189 self.user_ns.clear()
1190 ns = self.user_global_ns
1190 ns = self.user_global_ns
1191 drop_keys = set(ns.keys())
1191 drop_keys = set(ns.keys())
1192 drop_keys.discard('__builtin__')
1192 drop_keys.discard('__builtin__')
1193 drop_keys.discard('__builtins__')
1193 drop_keys.discard('__builtins__')
1194 drop_keys.discard('__name__')
1194 drop_keys.discard('__name__')
1195 for k in drop_keys:
1195 for k in drop_keys:
1196 del ns[k]
1196 del ns[k]
1197
1197
1198 self.user_ns_hidden.clear()
1198 self.user_ns_hidden.clear()
1199
1199
1200 # Restore the user namespaces to minimal usability
1200 # Restore the user namespaces to minimal usability
1201 self.init_user_ns()
1201 self.init_user_ns()
1202
1202
1203 # Restore the default and user aliases
1203 # Restore the default and user aliases
1204 self.alias_manager.clear_aliases()
1204 self.alias_manager.clear_aliases()
1205 self.alias_manager.init_aliases()
1205 self.alias_manager.init_aliases()
1206
1206
1207 # Flush the private list of module references kept for script
1207 # Flush the private list of module references kept for script
1208 # execution protection
1208 # execution protection
1209 self.clear_main_mod_cache()
1209 self.clear_main_mod_cache()
1210
1210
1211 def del_var(self, varname, by_name=False):
1211 def del_var(self, varname, by_name=False):
1212 """Delete a variable from the various namespaces, so that, as
1212 """Delete a variable from the various namespaces, so that, as
1213 far as possible, we're not keeping any hidden references to it.
1213 far as possible, we're not keeping any hidden references to it.
1214
1214
1215 Parameters
1215 Parameters
1216 ----------
1216 ----------
1217 varname : str
1217 varname : str
1218 The name of the variable to delete.
1218 The name of the variable to delete.
1219 by_name : bool
1219 by_name : bool
1220 If True, delete variables with the given name in each
1220 If True, delete variables with the given name in each
1221 namespace. If False (default), find the variable in the user
1221 namespace. If False (default), find the variable in the user
1222 namespace, and delete references to it.
1222 namespace, and delete references to it.
1223 """
1223 """
1224 if varname in ('__builtin__', '__builtins__'):
1224 if varname in ('__builtin__', '__builtins__'):
1225 raise ValueError("Refusing to delete %s" % varname)
1225 raise ValueError("Refusing to delete %s" % varname)
1226
1226
1227 ns_refs = self.all_ns_refs
1227 ns_refs = self.all_ns_refs
1228
1228
1229 if by_name: # Delete by name
1229 if by_name: # Delete by name
1230 for ns in ns_refs:
1230 for ns in ns_refs:
1231 try:
1231 try:
1232 del ns[varname]
1232 del ns[varname]
1233 except KeyError:
1233 except KeyError:
1234 pass
1234 pass
1235 else: # Delete by object
1235 else: # Delete by object
1236 try:
1236 try:
1237 obj = self.user_ns[varname]
1237 obj = self.user_ns[varname]
1238 except KeyError:
1238 except KeyError:
1239 raise NameError("name '%s' is not defined" % varname)
1239 raise NameError("name '%s' is not defined" % varname)
1240 # Also check in output history
1240 # Also check in output history
1241 ns_refs.append(self.history_manager.output_hist)
1241 ns_refs.append(self.history_manager.output_hist)
1242 for ns in ns_refs:
1242 for ns in ns_refs:
1243 to_delete = [n for n, o in ns.iteritems() if o is obj]
1243 to_delete = [n for n, o in ns.iteritems() if o is obj]
1244 for name in to_delete:
1244 for name in to_delete:
1245 del ns[name]
1245 del ns[name]
1246
1246
1247 # displayhook keeps extra references, but not in a dictionary
1247 # displayhook keeps extra references, but not in a dictionary
1248 for name in ('_', '__', '___'):
1248 for name in ('_', '__', '___'):
1249 if getattr(self.displayhook, name) is obj:
1249 if getattr(self.displayhook, name) is obj:
1250 setattr(self.displayhook, name, None)
1250 setattr(self.displayhook, name, None)
1251
1251
1252 def reset_selective(self, regex=None):
1252 def reset_selective(self, regex=None):
1253 """Clear selective variables from internal namespaces based on a
1253 """Clear selective variables from internal namespaces based on a
1254 specified regular expression.
1254 specified regular expression.
1255
1255
1256 Parameters
1256 Parameters
1257 ----------
1257 ----------
1258 regex : string or compiled pattern, optional
1258 regex : string or compiled pattern, optional
1259 A regular expression pattern that will be used in searching
1259 A regular expression pattern that will be used in searching
1260 variable names in the users namespaces.
1260 variable names in the users namespaces.
1261 """
1261 """
1262 if regex is not None:
1262 if regex is not None:
1263 try:
1263 try:
1264 m = re.compile(regex)
1264 m = re.compile(regex)
1265 except TypeError:
1265 except TypeError:
1266 raise TypeError('regex must be a string or compiled pattern')
1266 raise TypeError('regex must be a string or compiled pattern')
1267 # Search for keys in each namespace that match the given regex
1267 # Search for keys in each namespace that match the given regex
1268 # If a match is found, delete the key/value pair.
1268 # If a match is found, delete the key/value pair.
1269 for ns in self.all_ns_refs:
1269 for ns in self.all_ns_refs:
1270 for var in ns:
1270 for var in ns:
1271 if m.search(var):
1271 if m.search(var):
1272 del ns[var]
1272 del ns[var]
1273
1273
1274 def push(self, variables, interactive=True):
1274 def push(self, variables, interactive=True):
1275 """Inject a group of variables into the IPython user namespace.
1275 """Inject a group of variables into the IPython user namespace.
1276
1276
1277 Parameters
1277 Parameters
1278 ----------
1278 ----------
1279 variables : dict, str or list/tuple of str
1279 variables : dict, str or list/tuple of str
1280 The variables to inject into the user's namespace. If a dict, a
1280 The variables to inject into the user's namespace. If a dict, a
1281 simple update is done. If a str, the string is assumed to have
1281 simple update is done. If a str, the string is assumed to have
1282 variable names separated by spaces. A list/tuple of str can also
1282 variable names separated by spaces. A list/tuple of str can also
1283 be used to give the variable names. If just the variable names are
1283 be used to give the variable names. If just the variable names are
1284 give (list/tuple/str) then the variable values looked up in the
1284 give (list/tuple/str) then the variable values looked up in the
1285 callers frame.
1285 callers frame.
1286 interactive : bool
1286 interactive : bool
1287 If True (default), the variables will be listed with the ``who``
1287 If True (default), the variables will be listed with the ``who``
1288 magic.
1288 magic.
1289 """
1289 """
1290 vdict = None
1290 vdict = None
1291
1291
1292 # We need a dict of name/value pairs to do namespace updates.
1292 # We need a dict of name/value pairs to do namespace updates.
1293 if isinstance(variables, dict):
1293 if isinstance(variables, dict):
1294 vdict = variables
1294 vdict = variables
1295 elif isinstance(variables, (basestring, list, tuple)):
1295 elif isinstance(variables, (basestring, list, tuple)):
1296 if isinstance(variables, basestring):
1296 if isinstance(variables, basestring):
1297 vlist = variables.split()
1297 vlist = variables.split()
1298 else:
1298 else:
1299 vlist = variables
1299 vlist = variables
1300 vdict = {}
1300 vdict = {}
1301 cf = sys._getframe(1)
1301 cf = sys._getframe(1)
1302 for name in vlist:
1302 for name in vlist:
1303 try:
1303 try:
1304 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1304 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1305 except:
1305 except:
1306 print('Could not get variable %s from %s' %
1306 print('Could not get variable %s from %s' %
1307 (name,cf.f_code.co_name))
1307 (name,cf.f_code.co_name))
1308 else:
1308 else:
1309 raise ValueError('variables must be a dict/str/list/tuple')
1309 raise ValueError('variables must be a dict/str/list/tuple')
1310
1310
1311 # Propagate variables to user namespace
1311 # Propagate variables to user namespace
1312 self.user_ns.update(vdict)
1312 self.user_ns.update(vdict)
1313
1313
1314 # And configure interactive visibility
1314 # And configure interactive visibility
1315 user_ns_hidden = self.user_ns_hidden
1315 user_ns_hidden = self.user_ns_hidden
1316 if interactive:
1316 if interactive:
1317 for name in vdict:
1317 for name in vdict:
1318 user_ns_hidden.pop(name, None)
1318 user_ns_hidden.pop(name, None)
1319 else:
1319 else:
1320 user_ns_hidden.update(vdict)
1320 user_ns_hidden.update(vdict)
1321
1321
1322 def drop_by_id(self, variables):
1322 def drop_by_id(self, variables):
1323 """Remove a dict of variables from the user namespace, if they are the
1323 """Remove a dict of variables from the user namespace, if they are the
1324 same as the values in the dictionary.
1324 same as the values in the dictionary.
1325
1325
1326 This is intended for use by extensions: variables that they've added can
1326 This is intended for use by extensions: variables that they've added can
1327 be taken back out if they are unloaded, without removing any that the
1327 be taken back out if they are unloaded, without removing any that the
1328 user has overwritten.
1328 user has overwritten.
1329
1329
1330 Parameters
1330 Parameters
1331 ----------
1331 ----------
1332 variables : dict
1332 variables : dict
1333 A dictionary mapping object names (as strings) to the objects.
1333 A dictionary mapping object names (as strings) to the objects.
1334 """
1334 """
1335 for name, obj in variables.iteritems():
1335 for name, obj in variables.iteritems():
1336 if name in self.user_ns and self.user_ns[name] is obj:
1336 if name in self.user_ns and self.user_ns[name] is obj:
1337 del self.user_ns[name]
1337 del self.user_ns[name]
1338 self.user_ns_hidden.pop(name, None)
1338 self.user_ns_hidden.pop(name, None)
1339
1339
1340 #-------------------------------------------------------------------------
1340 #-------------------------------------------------------------------------
1341 # Things related to object introspection
1341 # Things related to object introspection
1342 #-------------------------------------------------------------------------
1342 #-------------------------------------------------------------------------
1343
1343
1344 def _ofind(self, oname, namespaces=None):
1344 def _ofind(self, oname, namespaces=None):
1345 """Find an object in the available namespaces.
1345 """Find an object in the available namespaces.
1346
1346
1347 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1347 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1348
1348
1349 Has special code to detect magic functions.
1349 Has special code to detect magic functions.
1350 """
1350 """
1351 oname = oname.strip()
1351 oname = oname.strip()
1352 #print '1- oname: <%r>' % oname # dbg
1352 #print '1- oname: <%r>' % oname # dbg
1353 if not oname.startswith(ESC_MAGIC) and \
1353 if not oname.startswith(ESC_MAGIC) and \
1354 not oname.startswith(ESC_MAGIC2) and \
1354 not oname.startswith(ESC_MAGIC2) and \
1355 not py3compat.isidentifier(oname, dotted=True):
1355 not py3compat.isidentifier(oname, dotted=True):
1356 return dict(found=False)
1356 return dict(found=False)
1357
1357
1358 alias_ns = None
1358 alias_ns = None
1359 if namespaces is None:
1359 if namespaces is None:
1360 # Namespaces to search in:
1360 # Namespaces to search in:
1361 # Put them in a list. The order is important so that we
1361 # Put them in a list. The order is important so that we
1362 # find things in the same order that Python finds them.
1362 # find things in the same order that Python finds them.
1363 namespaces = [ ('Interactive', self.user_ns),
1363 namespaces = [ ('Interactive', self.user_ns),
1364 ('Interactive (global)', self.user_global_ns),
1364 ('Interactive (global)', self.user_global_ns),
1365 ('Python builtin', builtin_mod.__dict__),
1365 ('Python builtin', builtin_mod.__dict__),
1366 ]
1366 ]
1367
1367
1368 # initialize results to 'null'
1368 # initialize results to 'null'
1369 found = False; obj = None; ospace = None; ds = None;
1369 found = False; obj = None; ospace = None; ds = None;
1370 ismagic = False; isalias = False; parent = None
1370 ismagic = False; isalias = False; parent = None
1371
1371
1372 # We need to special-case 'print', which as of python2.6 registers as a
1372 # We need to special-case 'print', which as of python2.6 registers as a
1373 # function but should only be treated as one if print_function was
1373 # function but should only be treated as one if print_function was
1374 # loaded with a future import. In this case, just bail.
1374 # loaded with a future import. In this case, just bail.
1375 if (oname == 'print' and not py3compat.PY3 and not \
1375 if (oname == 'print' and not py3compat.PY3 and not \
1376 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1376 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1377 return {'found':found, 'obj':obj, 'namespace':ospace,
1377 return {'found':found, 'obj':obj, 'namespace':ospace,
1378 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1378 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1379
1379
1380 # Look for the given name by splitting it in parts. If the head is
1380 # Look for the given name by splitting it in parts. If the head is
1381 # found, then we look for all the remaining parts as members, and only
1381 # found, then we look for all the remaining parts as members, and only
1382 # declare success if we can find them all.
1382 # declare success if we can find them all.
1383 oname_parts = oname.split('.')
1383 oname_parts = oname.split('.')
1384 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1384 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1385 for nsname,ns in namespaces:
1385 for nsname,ns in namespaces:
1386 try:
1386 try:
1387 obj = ns[oname_head]
1387 obj = ns[oname_head]
1388 except KeyError:
1388 except KeyError:
1389 continue
1389 continue
1390 else:
1390 else:
1391 #print 'oname_rest:', oname_rest # dbg
1391 #print 'oname_rest:', oname_rest # dbg
1392 for part in oname_rest:
1392 for part in oname_rest:
1393 try:
1393 try:
1394 parent = obj
1394 parent = obj
1395 obj = getattr(obj,part)
1395 obj = getattr(obj,part)
1396 except:
1396 except:
1397 # Blanket except b/c some badly implemented objects
1397 # Blanket except b/c some badly implemented objects
1398 # allow __getattr__ to raise exceptions other than
1398 # allow __getattr__ to raise exceptions other than
1399 # AttributeError, which then crashes IPython.
1399 # AttributeError, which then crashes IPython.
1400 break
1400 break
1401 else:
1401 else:
1402 # If we finish the for loop (no break), we got all members
1402 # If we finish the for loop (no break), we got all members
1403 found = True
1403 found = True
1404 ospace = nsname
1404 ospace = nsname
1405 break # namespace loop
1405 break # namespace loop
1406
1406
1407 # Try to see if it's magic
1407 # Try to see if it's magic
1408 if not found:
1408 if not found:
1409 obj = None
1409 obj = None
1410 if oname.startswith(ESC_MAGIC2):
1410 if oname.startswith(ESC_MAGIC2):
1411 oname = oname.lstrip(ESC_MAGIC2)
1411 oname = oname.lstrip(ESC_MAGIC2)
1412 obj = self.find_cell_magic(oname)
1412 obj = self.find_cell_magic(oname)
1413 elif oname.startswith(ESC_MAGIC):
1413 elif oname.startswith(ESC_MAGIC):
1414 oname = oname.lstrip(ESC_MAGIC)
1414 oname = oname.lstrip(ESC_MAGIC)
1415 obj = self.find_line_magic(oname)
1415 obj = self.find_line_magic(oname)
1416 else:
1416 else:
1417 # search without prefix, so run? will find %run?
1417 # search without prefix, so run? will find %run?
1418 obj = self.find_line_magic(oname)
1418 obj = self.find_line_magic(oname)
1419 if obj is None:
1419 if obj is None:
1420 obj = self.find_cell_magic(oname)
1420 obj = self.find_cell_magic(oname)
1421 if obj is not None:
1421 if obj is not None:
1422 found = True
1422 found = True
1423 ospace = 'IPython internal'
1423 ospace = 'IPython internal'
1424 ismagic = True
1424 ismagic = True
1425
1425
1426 # Last try: special-case some literals like '', [], {}, etc:
1426 # Last try: special-case some literals like '', [], {}, etc:
1427 if not found and oname_head in ["''",'""','[]','{}','()']:
1427 if not found and oname_head in ["''",'""','[]','{}','()']:
1428 obj = eval(oname_head)
1428 obj = eval(oname_head)
1429 found = True
1429 found = True
1430 ospace = 'Interactive'
1430 ospace = 'Interactive'
1431
1431
1432 return {'found':found, 'obj':obj, 'namespace':ospace,
1432 return {'found':found, 'obj':obj, 'namespace':ospace,
1433 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1433 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1434
1434
1435 def _ofind_property(self, oname, info):
1435 def _ofind_property(self, oname, info):
1436 """Second part of object finding, to look for property details."""
1436 """Second part of object finding, to look for property details."""
1437 if info.found:
1437 if info.found:
1438 # Get the docstring of the class property if it exists.
1438 # Get the docstring of the class property if it exists.
1439 path = oname.split('.')
1439 path = oname.split('.')
1440 root = '.'.join(path[:-1])
1440 root = '.'.join(path[:-1])
1441 if info.parent is not None:
1441 if info.parent is not None:
1442 try:
1442 try:
1443 target = getattr(info.parent, '__class__')
1443 target = getattr(info.parent, '__class__')
1444 # The object belongs to a class instance.
1444 # The object belongs to a class instance.
1445 try:
1445 try:
1446 target = getattr(target, path[-1])
1446 target = getattr(target, path[-1])
1447 # The class defines the object.
1447 # The class defines the object.
1448 if isinstance(target, property):
1448 if isinstance(target, property):
1449 oname = root + '.__class__.' + path[-1]
1449 oname = root + '.__class__.' + path[-1]
1450 info = Struct(self._ofind(oname))
1450 info = Struct(self._ofind(oname))
1451 except AttributeError: pass
1451 except AttributeError: pass
1452 except AttributeError: pass
1452 except AttributeError: pass
1453
1453
1454 # We return either the new info or the unmodified input if the object
1454 # We return either the new info or the unmodified input if the object
1455 # hadn't been found
1455 # hadn't been found
1456 return info
1456 return info
1457
1457
1458 def _object_find(self, oname, namespaces=None):
1458 def _object_find(self, oname, namespaces=None):
1459 """Find an object and return a struct with info about it."""
1459 """Find an object and return a struct with info about it."""
1460 inf = Struct(self._ofind(oname, namespaces))
1460 inf = Struct(self._ofind(oname, namespaces))
1461 return Struct(self._ofind_property(oname, inf))
1461 return Struct(self._ofind_property(oname, inf))
1462
1462
1463 def _inspect(self, meth, oname, namespaces=None, **kw):
1463 def _inspect(self, meth, oname, namespaces=None, **kw):
1464 """Generic interface to the inspector system.
1464 """Generic interface to the inspector system.
1465
1465
1466 This function is meant to be called by pdef, pdoc & friends."""
1466 This function is meant to be called by pdef, pdoc & friends."""
1467 info = self._object_find(oname, namespaces)
1467 info = self._object_find(oname, namespaces)
1468 if info.found:
1468 if info.found:
1469 pmethod = getattr(self.inspector, meth)
1469 pmethod = getattr(self.inspector, meth)
1470 formatter = format_screen if info.ismagic else None
1470 formatter = format_screen if info.ismagic else None
1471 if meth == 'pdoc':
1471 if meth == 'pdoc':
1472 pmethod(info.obj, oname, formatter)
1472 pmethod(info.obj, oname, formatter)
1473 elif meth == 'pinfo':
1473 elif meth == 'pinfo':
1474 pmethod(info.obj, oname, formatter, info, **kw)
1474 pmethod(info.obj, oname, formatter, info, **kw)
1475 else:
1475 else:
1476 pmethod(info.obj, oname)
1476 pmethod(info.obj, oname)
1477 else:
1477 else:
1478 print('Object `%s` not found.' % oname)
1478 print('Object `%s` not found.' % oname)
1479 return 'not found' # so callers can take other action
1479 return 'not found' # so callers can take other action
1480
1480
1481 def object_inspect(self, oname, detail_level=0):
1481 def object_inspect(self, oname, detail_level=0):
1482 with self.builtin_trap:
1482 with self.builtin_trap:
1483 info = self._object_find(oname)
1483 info = self._object_find(oname)
1484 if info.found:
1484 if info.found:
1485 return self.inspector.info(info.obj, oname, info=info,
1485 return self.inspector.info(info.obj, oname, info=info,
1486 detail_level=detail_level
1486 detail_level=detail_level
1487 )
1487 )
1488 else:
1488 else:
1489 return oinspect.object_info(name=oname, found=False)
1489 return oinspect.object_info(name=oname, found=False)
1490
1490
1491 #-------------------------------------------------------------------------
1491 #-------------------------------------------------------------------------
1492 # Things related to history management
1492 # Things related to history management
1493 #-------------------------------------------------------------------------
1493 #-------------------------------------------------------------------------
1494
1494
1495 def init_history(self):
1495 def init_history(self):
1496 """Sets up the command history, and starts regular autosaves."""
1496 """Sets up the command history, and starts regular autosaves."""
1497 self.history_manager = HistoryManager(shell=self, parent=self)
1497 self.history_manager = HistoryManager(shell=self, parent=self)
1498 self.configurables.append(self.history_manager)
1498 self.configurables.append(self.history_manager)
1499
1499
1500 #-------------------------------------------------------------------------
1500 #-------------------------------------------------------------------------
1501 # Things related to exception handling and tracebacks (not debugging)
1501 # Things related to exception handling and tracebacks (not debugging)
1502 #-------------------------------------------------------------------------
1502 #-------------------------------------------------------------------------
1503
1503
1504 def init_traceback_handlers(self, custom_exceptions):
1504 def init_traceback_handlers(self, custom_exceptions):
1505 # Syntax error handler.
1505 # Syntax error handler.
1506 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1506 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1507
1507
1508 # The interactive one is initialized with an offset, meaning we always
1508 # The interactive one is initialized with an offset, meaning we always
1509 # want to remove the topmost item in the traceback, which is our own
1509 # want to remove the topmost item in the traceback, which is our own
1510 # internal code. Valid modes: ['Plain','Context','Verbose']
1510 # internal code. Valid modes: ['Plain','Context','Verbose']
1511 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1511 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1512 color_scheme='NoColor',
1512 color_scheme='NoColor',
1513 tb_offset = 1,
1513 tb_offset = 1,
1514 check_cache=check_linecache_ipython)
1514 check_cache=check_linecache_ipython)
1515
1515
1516 # The instance will store a pointer to the system-wide exception hook,
1516 # The instance will store a pointer to the system-wide exception hook,
1517 # so that runtime code (such as magics) can access it. This is because
1517 # so that runtime code (such as magics) can access it. This is because
1518 # during the read-eval loop, it may get temporarily overwritten.
1518 # during the read-eval loop, it may get temporarily overwritten.
1519 self.sys_excepthook = sys.excepthook
1519 self.sys_excepthook = sys.excepthook
1520
1520
1521 # and add any custom exception handlers the user may have specified
1521 # and add any custom exception handlers the user may have specified
1522 self.set_custom_exc(*custom_exceptions)
1522 self.set_custom_exc(*custom_exceptions)
1523
1523
1524 # Set the exception mode
1524 # Set the exception mode
1525 self.InteractiveTB.set_mode(mode=self.xmode)
1525 self.InteractiveTB.set_mode(mode=self.xmode)
1526
1526
1527 def set_custom_exc(self, exc_tuple, handler):
1527 def set_custom_exc(self, exc_tuple, handler):
1528 """set_custom_exc(exc_tuple,handler)
1528 """set_custom_exc(exc_tuple,handler)
1529
1529
1530 Set a custom exception handler, which will be called if any of the
1530 Set a custom exception handler, which will be called if any of the
1531 exceptions in exc_tuple occur in the mainloop (specifically, in the
1531 exceptions in exc_tuple occur in the mainloop (specifically, in the
1532 run_code() method).
1532 run_code() method).
1533
1533
1534 Parameters
1534 Parameters
1535 ----------
1535 ----------
1536
1536
1537 exc_tuple : tuple of exception classes
1537 exc_tuple : tuple of exception classes
1538 A *tuple* of exception classes, for which to call the defined
1538 A *tuple* of exception classes, for which to call the defined
1539 handler. It is very important that you use a tuple, and NOT A
1539 handler. It is very important that you use a tuple, and NOT A
1540 LIST here, because of the way Python's except statement works. If
1540 LIST here, because of the way Python's except statement works. If
1541 you only want to trap a single exception, use a singleton tuple::
1541 you only want to trap a single exception, use a singleton tuple::
1542
1542
1543 exc_tuple == (MyCustomException,)
1543 exc_tuple == (MyCustomException,)
1544
1544
1545 handler : callable
1545 handler : callable
1546 handler must have the following signature::
1546 handler must have the following signature::
1547
1547
1548 def my_handler(self, etype, value, tb, tb_offset=None):
1548 def my_handler(self, etype, value, tb, tb_offset=None):
1549 ...
1549 ...
1550 return structured_traceback
1550 return structured_traceback
1551
1551
1552 Your handler must return a structured traceback (a list of strings),
1552 Your handler must return a structured traceback (a list of strings),
1553 or None.
1553 or None.
1554
1554
1555 This will be made into an instance method (via types.MethodType)
1555 This will be made into an instance method (via types.MethodType)
1556 of IPython itself, and it will be called if any of the exceptions
1556 of IPython itself, and it will be called if any of the exceptions
1557 listed in the exc_tuple are caught. If the handler is None, an
1557 listed in the exc_tuple are caught. If the handler is None, an
1558 internal basic one is used, which just prints basic info.
1558 internal basic one is used, which just prints basic info.
1559
1559
1560 To protect IPython from crashes, if your handler ever raises an
1560 To protect IPython from crashes, if your handler ever raises an
1561 exception or returns an invalid result, it will be immediately
1561 exception or returns an invalid result, it will be immediately
1562 disabled.
1562 disabled.
1563
1563
1564 WARNING: by putting in your own exception handler into IPython's main
1564 WARNING: by putting in your own exception handler into IPython's main
1565 execution loop, you run a very good chance of nasty crashes. This
1565 execution loop, you run a very good chance of nasty crashes. This
1566 facility should only be used if you really know what you are doing."""
1566 facility should only be used if you really know what you are doing."""
1567
1567
1568 assert type(exc_tuple)==type(()) , \
1568 assert type(exc_tuple)==type(()) , \
1569 "The custom exceptions must be given AS A TUPLE."
1569 "The custom exceptions must be given AS A TUPLE."
1570
1570
1571 def dummy_handler(self,etype,value,tb,tb_offset=None):
1571 def dummy_handler(self,etype,value,tb,tb_offset=None):
1572 print('*** Simple custom exception handler ***')
1572 print('*** Simple custom exception handler ***')
1573 print('Exception type :',etype)
1573 print('Exception type :',etype)
1574 print('Exception value:',value)
1574 print('Exception value:',value)
1575 print('Traceback :',tb)
1575 print('Traceback :',tb)
1576 #print 'Source code :','\n'.join(self.buffer)
1576 #print 'Source code :','\n'.join(self.buffer)
1577
1577
1578 def validate_stb(stb):
1578 def validate_stb(stb):
1579 """validate structured traceback return type
1579 """validate structured traceback return type
1580
1580
1581 return type of CustomTB *should* be a list of strings, but allow
1581 return type of CustomTB *should* be a list of strings, but allow
1582 single strings or None, which are harmless.
1582 single strings or None, which are harmless.
1583
1583
1584 This function will *always* return a list of strings,
1584 This function will *always* return a list of strings,
1585 and will raise a TypeError if stb is inappropriate.
1585 and will raise a TypeError if stb is inappropriate.
1586 """
1586 """
1587 msg = "CustomTB must return list of strings, not %r" % stb
1587 msg = "CustomTB must return list of strings, not %r" % stb
1588 if stb is None:
1588 if stb is None:
1589 return []
1589 return []
1590 elif isinstance(stb, basestring):
1590 elif isinstance(stb, basestring):
1591 return [stb]
1591 return [stb]
1592 elif not isinstance(stb, list):
1592 elif not isinstance(stb, list):
1593 raise TypeError(msg)
1593 raise TypeError(msg)
1594 # it's a list
1594 # it's a list
1595 for line in stb:
1595 for line in stb:
1596 # check every element
1596 # check every element
1597 if not isinstance(line, basestring):
1597 if not isinstance(line, basestring):
1598 raise TypeError(msg)
1598 raise TypeError(msg)
1599 return stb
1599 return stb
1600
1600
1601 if handler is None:
1601 if handler is None:
1602 wrapped = dummy_handler
1602 wrapped = dummy_handler
1603 else:
1603 else:
1604 def wrapped(self,etype,value,tb,tb_offset=None):
1604 def wrapped(self,etype,value,tb,tb_offset=None):
1605 """wrap CustomTB handler, to protect IPython from user code
1605 """wrap CustomTB handler, to protect IPython from user code
1606
1606
1607 This makes it harder (but not impossible) for custom exception
1607 This makes it harder (but not impossible) for custom exception
1608 handlers to crash IPython.
1608 handlers to crash IPython.
1609 """
1609 """
1610 try:
1610 try:
1611 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1611 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1612 return validate_stb(stb)
1612 return validate_stb(stb)
1613 except:
1613 except:
1614 # clear custom handler immediately
1614 # clear custom handler immediately
1615 self.set_custom_exc((), None)
1615 self.set_custom_exc((), None)
1616 print("Custom TB Handler failed, unregistering", file=io.stderr)
1616 print("Custom TB Handler failed, unregistering", file=io.stderr)
1617 # show the exception in handler first
1617 # show the exception in handler first
1618 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1618 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1619 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1619 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1620 print("The original exception:", file=io.stdout)
1620 print("The original exception:", file=io.stdout)
1621 stb = self.InteractiveTB.structured_traceback(
1621 stb = self.InteractiveTB.structured_traceback(
1622 (etype,value,tb), tb_offset=tb_offset
1622 (etype,value,tb), tb_offset=tb_offset
1623 )
1623 )
1624 return stb
1624 return stb
1625
1625
1626 self.CustomTB = types.MethodType(wrapped,self)
1626 self.CustomTB = types.MethodType(wrapped,self)
1627 self.custom_exceptions = exc_tuple
1627 self.custom_exceptions = exc_tuple
1628
1628
1629 def excepthook(self, etype, value, tb):
1629 def excepthook(self, etype, value, tb):
1630 """One more defense for GUI apps that call sys.excepthook.
1630 """One more defense for GUI apps that call sys.excepthook.
1631
1631
1632 GUI frameworks like wxPython trap exceptions and call
1632 GUI frameworks like wxPython trap exceptions and call
1633 sys.excepthook themselves. I guess this is a feature that
1633 sys.excepthook themselves. I guess this is a feature that
1634 enables them to keep running after exceptions that would
1634 enables them to keep running after exceptions that would
1635 otherwise kill their mainloop. This is a bother for IPython
1635 otherwise kill their mainloop. This is a bother for IPython
1636 which excepts to catch all of the program exceptions with a try:
1636 which excepts to catch all of the program exceptions with a try:
1637 except: statement.
1637 except: statement.
1638
1638
1639 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1639 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1640 any app directly invokes sys.excepthook, it will look to the user like
1640 any app directly invokes sys.excepthook, it will look to the user like
1641 IPython crashed. In order to work around this, we can disable the
1641 IPython crashed. In order to work around this, we can disable the
1642 CrashHandler and replace it with this excepthook instead, which prints a
1642 CrashHandler and replace it with this excepthook instead, which prints a
1643 regular traceback using our InteractiveTB. In this fashion, apps which
1643 regular traceback using our InteractiveTB. In this fashion, apps which
1644 call sys.excepthook will generate a regular-looking exception from
1644 call sys.excepthook will generate a regular-looking exception from
1645 IPython, and the CrashHandler will only be triggered by real IPython
1645 IPython, and the CrashHandler will only be triggered by real IPython
1646 crashes.
1646 crashes.
1647
1647
1648 This hook should be used sparingly, only in places which are not likely
1648 This hook should be used sparingly, only in places which are not likely
1649 to be true IPython errors.
1649 to be true IPython errors.
1650 """
1650 """
1651 self.showtraceback((etype,value,tb),tb_offset=0)
1651 self.showtraceback((etype,value,tb),tb_offset=0)
1652
1652
1653 def _get_exc_info(self, exc_tuple=None):
1653 def _get_exc_info(self, exc_tuple=None):
1654 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1654 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1655
1655
1656 Ensures sys.last_type,value,traceback hold the exc_info we found,
1656 Ensures sys.last_type,value,traceback hold the exc_info we found,
1657 from whichever source.
1657 from whichever source.
1658
1658
1659 raises ValueError if none of these contain any information
1659 raises ValueError if none of these contain any information
1660 """
1660 """
1661 if exc_tuple is None:
1661 if exc_tuple is None:
1662 etype, value, tb = sys.exc_info()
1662 etype, value, tb = sys.exc_info()
1663 else:
1663 else:
1664 etype, value, tb = exc_tuple
1664 etype, value, tb = exc_tuple
1665
1665
1666 if etype is None:
1666 if etype is None:
1667 if hasattr(sys, 'last_type'):
1667 if hasattr(sys, 'last_type'):
1668 etype, value, tb = sys.last_type, sys.last_value, \
1668 etype, value, tb = sys.last_type, sys.last_value, \
1669 sys.last_traceback
1669 sys.last_traceback
1670
1670
1671 if etype is None:
1671 if etype is None:
1672 raise ValueError("No exception to find")
1672 raise ValueError("No exception to find")
1673
1673
1674 # Now store the exception info in sys.last_type etc.
1674 # Now store the exception info in sys.last_type etc.
1675 # WARNING: these variables are somewhat deprecated and not
1675 # WARNING: these variables are somewhat deprecated and not
1676 # necessarily safe to use in a threaded environment, but tools
1676 # necessarily safe to use in a threaded environment, but tools
1677 # like pdb depend on their existence, so let's set them. If we
1677 # like pdb depend on their existence, so let's set them. If we
1678 # find problems in the field, we'll need to revisit their use.
1678 # find problems in the field, we'll need to revisit their use.
1679 sys.last_type = etype
1679 sys.last_type = etype
1680 sys.last_value = value
1680 sys.last_value = value
1681 sys.last_traceback = tb
1681 sys.last_traceback = tb
1682
1682
1683 return etype, value, tb
1683 return etype, value, tb
1684
1684
1685 def show_usage_error(self, exc):
1685 def show_usage_error(self, exc):
1686 """Show a short message for UsageErrors
1686 """Show a short message for UsageErrors
1687
1687
1688 These are special exceptions that shouldn't show a traceback.
1688 These are special exceptions that shouldn't show a traceback.
1689 """
1689 """
1690 self.write_err("UsageError: %s" % exc)
1690 self.write_err("UsageError: %s" % exc)
1691
1691
1692 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1692 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1693 exception_only=False):
1693 exception_only=False):
1694 """Display the exception that just occurred.
1694 """Display the exception that just occurred.
1695
1695
1696 If nothing is known about the exception, this is the method which
1696 If nothing is known about the exception, this is the method which
1697 should be used throughout the code for presenting user tracebacks,
1697 should be used throughout the code for presenting user tracebacks,
1698 rather than directly invoking the InteractiveTB object.
1698 rather than directly invoking the InteractiveTB object.
1699
1699
1700 A specific showsyntaxerror() also exists, but this method can take
1700 A specific showsyntaxerror() also exists, but this method can take
1701 care of calling it if needed, so unless you are explicitly catching a
1701 care of calling it if needed, so unless you are explicitly catching a
1702 SyntaxError exception, don't try to analyze the stack manually and
1702 SyntaxError exception, don't try to analyze the stack manually and
1703 simply call this method."""
1703 simply call this method."""
1704
1704
1705 try:
1705 try:
1706 try:
1706 try:
1707 etype, value, tb = self._get_exc_info(exc_tuple)
1707 etype, value, tb = self._get_exc_info(exc_tuple)
1708 except ValueError:
1708 except ValueError:
1709 self.write_err('No traceback available to show.\n')
1709 self.write_err('No traceback available to show.\n')
1710 return
1710 return
1711
1711
1712 if issubclass(etype, SyntaxError):
1712 if issubclass(etype, SyntaxError):
1713 # Though this won't be called by syntax errors in the input
1713 # Though this won't be called by syntax errors in the input
1714 # line, there may be SyntaxError cases with imported code.
1714 # line, there may be SyntaxError cases with imported code.
1715 self.showsyntaxerror(filename)
1715 self.showsyntaxerror(filename)
1716 elif etype is UsageError:
1716 elif etype is UsageError:
1717 self.show_usage_error(value)
1717 self.show_usage_error(value)
1718 else:
1718 else:
1719 if exception_only:
1719 if exception_only:
1720 stb = ['An exception has occurred, use %tb to see '
1720 stb = ['An exception has occurred, use %tb to see '
1721 'the full traceback.\n']
1721 'the full traceback.\n']
1722 stb.extend(self.InteractiveTB.get_exception_only(etype,
1722 stb.extend(self.InteractiveTB.get_exception_only(etype,
1723 value))
1723 value))
1724 else:
1724 else:
1725 try:
1725 try:
1726 # Exception classes can customise their traceback - we
1726 # Exception classes can customise their traceback - we
1727 # use this in IPython.parallel for exceptions occurring
1727 # use this in IPython.parallel for exceptions occurring
1728 # in the engines. This should return a list of strings.
1728 # in the engines. This should return a list of strings.
1729 stb = value._render_traceback_()
1729 stb = value._render_traceback_()
1730 except Exception:
1730 except Exception:
1731 stb = self.InteractiveTB.structured_traceback(etype,
1731 stb = self.InteractiveTB.structured_traceback(etype,
1732 value, tb, tb_offset=tb_offset)
1732 value, tb, tb_offset=tb_offset)
1733
1733
1734 self._showtraceback(etype, value, stb)
1734 self._showtraceback(etype, value, stb)
1735 if self.call_pdb:
1735 if self.call_pdb:
1736 # drop into debugger
1736 # drop into debugger
1737 self.debugger(force=True)
1737 self.debugger(force=True)
1738 return
1738 return
1739
1739
1740 # Actually show the traceback
1740 # Actually show the traceback
1741 self._showtraceback(etype, value, stb)
1741 self._showtraceback(etype, value, stb)
1742
1742
1743 except KeyboardInterrupt:
1743 except KeyboardInterrupt:
1744 self.write_err("\nKeyboardInterrupt\n")
1744 self.write_err("\nKeyboardInterrupt\n")
1745
1745
1746 def _showtraceback(self, etype, evalue, stb):
1746 def _showtraceback(self, etype, evalue, stb):
1747 """Actually show a traceback.
1747 """Actually show a traceback.
1748
1748
1749 Subclasses may override this method to put the traceback on a different
1749 Subclasses may override this method to put the traceback on a different
1750 place, like a side channel.
1750 place, like a side channel.
1751 """
1751 """
1752 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1752 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1753
1753
1754 def showsyntaxerror(self, filename=None):
1754 def showsyntaxerror(self, filename=None):
1755 """Display the syntax error that just occurred.
1755 """Display the syntax error that just occurred.
1756
1756
1757 This doesn't display a stack trace because there isn't one.
1757 This doesn't display a stack trace because there isn't one.
1758
1758
1759 If a filename is given, it is stuffed in the exception instead
1759 If a filename is given, it is stuffed in the exception instead
1760 of what was there before (because Python's parser always uses
1760 of what was there before (because Python's parser always uses
1761 "<string>" when reading from a string).
1761 "<string>" when reading from a string).
1762 """
1762 """
1763 etype, value, last_traceback = self._get_exc_info()
1763 etype, value, last_traceback = self._get_exc_info()
1764
1764
1765 if filename and issubclass(etype, SyntaxError):
1765 if filename and issubclass(etype, SyntaxError):
1766 try:
1766 try:
1767 value.filename = filename
1767 value.filename = filename
1768 except:
1768 except:
1769 # Not the format we expect; leave it alone
1769 # Not the format we expect; leave it alone
1770 pass
1770 pass
1771
1771
1772 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1772 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1773 self._showtraceback(etype, value, stb)
1773 self._showtraceback(etype, value, stb)
1774
1774
1775 # This is overridden in TerminalInteractiveShell to show a message about
1775 # This is overridden in TerminalInteractiveShell to show a message about
1776 # the %paste magic.
1776 # the %paste magic.
1777 def showindentationerror(self):
1777 def showindentationerror(self):
1778 """Called by run_cell when there's an IndentationError in code entered
1778 """Called by run_cell when there's an IndentationError in code entered
1779 at the prompt.
1779 at the prompt.
1780
1780
1781 This is overridden in TerminalInteractiveShell to show a message about
1781 This is overridden in TerminalInteractiveShell to show a message about
1782 the %paste magic."""
1782 the %paste magic."""
1783 self.showsyntaxerror()
1783 self.showsyntaxerror()
1784
1784
1785 #-------------------------------------------------------------------------
1785 #-------------------------------------------------------------------------
1786 # Things related to readline
1786 # Things related to readline
1787 #-------------------------------------------------------------------------
1787 #-------------------------------------------------------------------------
1788
1788
1789 def init_readline(self):
1789 def init_readline(self):
1790 """Command history completion/saving/reloading."""
1790 """Command history completion/saving/reloading."""
1791
1791
1792 if self.readline_use:
1792 if self.readline_use:
1793 import IPython.utils.rlineimpl as readline
1793 import IPython.utils.rlineimpl as readline
1794
1794
1795 self.rl_next_input = None
1795 self.rl_next_input = None
1796 self.rl_do_indent = False
1796 self.rl_do_indent = False
1797
1797
1798 if not self.readline_use or not readline.have_readline:
1798 if not self.readline_use or not readline.have_readline:
1799 self.has_readline = False
1799 self.has_readline = False
1800 self.readline = None
1800 self.readline = None
1801 # Set a number of methods that depend on readline to be no-op
1801 # Set a number of methods that depend on readline to be no-op
1802 self.readline_no_record = no_op_context
1802 self.readline_no_record = no_op_context
1803 self.set_readline_completer = no_op
1803 self.set_readline_completer = no_op
1804 self.set_custom_completer = no_op
1804 self.set_custom_completer = no_op
1805 if self.readline_use:
1805 if self.readline_use:
1806 warn('Readline services not available or not loaded.')
1806 warn('Readline services not available or not loaded.')
1807 else:
1807 else:
1808 self.has_readline = True
1808 self.has_readline = True
1809 self.readline = readline
1809 self.readline = readline
1810 sys.modules['readline'] = readline
1810 sys.modules['readline'] = readline
1811
1811
1812 # Platform-specific configuration
1812 # Platform-specific configuration
1813 if os.name == 'nt':
1813 if os.name == 'nt':
1814 # FIXME - check with Frederick to see if we can harmonize
1814 # FIXME - check with Frederick to see if we can harmonize
1815 # naming conventions with pyreadline to avoid this
1815 # naming conventions with pyreadline to avoid this
1816 # platform-dependent check
1816 # platform-dependent check
1817 self.readline_startup_hook = readline.set_pre_input_hook
1817 self.readline_startup_hook = readline.set_pre_input_hook
1818 else:
1818 else:
1819 self.readline_startup_hook = readline.set_startup_hook
1819 self.readline_startup_hook = readline.set_startup_hook
1820
1820
1821 # Load user's initrc file (readline config)
1821 # Load user's initrc file (readline config)
1822 # Or if libedit is used, load editrc.
1822 # Or if libedit is used, load editrc.
1823 inputrc_name = os.environ.get('INPUTRC')
1823 inputrc_name = os.environ.get('INPUTRC')
1824 if inputrc_name is None:
1824 if inputrc_name is None:
1825 inputrc_name = '.inputrc'
1825 inputrc_name = '.inputrc'
1826 if readline.uses_libedit:
1826 if readline.uses_libedit:
1827 inputrc_name = '.editrc'
1827 inputrc_name = '.editrc'
1828 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1828 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1829 if os.path.isfile(inputrc_name):
1829 if os.path.isfile(inputrc_name):
1830 try:
1830 try:
1831 readline.read_init_file(inputrc_name)
1831 readline.read_init_file(inputrc_name)
1832 except:
1832 except:
1833 warn('Problems reading readline initialization file <%s>'
1833 warn('Problems reading readline initialization file <%s>'
1834 % inputrc_name)
1834 % inputrc_name)
1835
1835
1836 # Configure readline according to user's prefs
1836 # Configure readline according to user's prefs
1837 # This is only done if GNU readline is being used. If libedit
1837 # This is only done if GNU readline is being used. If libedit
1838 # is being used (as on Leopard) the readline config is
1838 # is being used (as on Leopard) the readline config is
1839 # not run as the syntax for libedit is different.
1839 # not run as the syntax for libedit is different.
1840 if not readline.uses_libedit:
1840 if not readline.uses_libedit:
1841 for rlcommand in self.readline_parse_and_bind:
1841 for rlcommand in self.readline_parse_and_bind:
1842 #print "loading rl:",rlcommand # dbg
1842 #print "loading rl:",rlcommand # dbg
1843 readline.parse_and_bind(rlcommand)
1843 readline.parse_and_bind(rlcommand)
1844
1844
1845 # Remove some chars from the delimiters list. If we encounter
1845 # Remove some chars from the delimiters list. If we encounter
1846 # unicode chars, discard them.
1846 # unicode chars, discard them.
1847 delims = readline.get_completer_delims()
1847 delims = readline.get_completer_delims()
1848 if not py3compat.PY3:
1848 if not py3compat.PY3:
1849 delims = delims.encode("ascii", "ignore")
1849 delims = delims.encode("ascii", "ignore")
1850 for d in self.readline_remove_delims:
1850 for d in self.readline_remove_delims:
1851 delims = delims.replace(d, "")
1851 delims = delims.replace(d, "")
1852 delims = delims.replace(ESC_MAGIC, '')
1852 delims = delims.replace(ESC_MAGIC, '')
1853 readline.set_completer_delims(delims)
1853 readline.set_completer_delims(delims)
1854 # Store these so we can restore them if something like rpy2 modifies
1854 # Store these so we can restore them if something like rpy2 modifies
1855 # them.
1855 # them.
1856 self.readline_delims = delims
1856 self.readline_delims = delims
1857 # otherwise we end up with a monster history after a while:
1857 # otherwise we end up with a monster history after a while:
1858 readline.set_history_length(self.history_length)
1858 readline.set_history_length(self.history_length)
1859
1859
1860 self.refill_readline_hist()
1860 self.refill_readline_hist()
1861 self.readline_no_record = ReadlineNoRecord(self)
1861 self.readline_no_record = ReadlineNoRecord(self)
1862
1862
1863 # Configure auto-indent for all platforms
1863 # Configure auto-indent for all platforms
1864 self.set_autoindent(self.autoindent)
1864 self.set_autoindent(self.autoindent)
1865
1865
1866 def refill_readline_hist(self):
1866 def refill_readline_hist(self):
1867 # Load the last 1000 lines from history
1867 # Load the last 1000 lines from history
1868 self.readline.clear_history()
1868 self.readline.clear_history()
1869 stdin_encoding = sys.stdin.encoding or "utf-8"
1869 stdin_encoding = sys.stdin.encoding or "utf-8"
1870 last_cell = u""
1870 last_cell = u""
1871 for _, _, cell in self.history_manager.get_tail(1000,
1871 for _, _, cell in self.history_manager.get_tail(1000,
1872 include_latest=True):
1872 include_latest=True):
1873 # Ignore blank lines and consecutive duplicates
1873 # Ignore blank lines and consecutive duplicates
1874 cell = cell.rstrip()
1874 cell = cell.rstrip()
1875 if cell and (cell != last_cell):
1875 if cell and (cell != last_cell):
1876 try:
1876 try:
1877 if self.multiline_history:
1877 if self.multiline_history:
1878 self.readline.add_history(py3compat.unicode_to_str(cell,
1878 self.readline.add_history(py3compat.unicode_to_str(cell,
1879 stdin_encoding))
1879 stdin_encoding))
1880 else:
1880 else:
1881 for line in cell.splitlines():
1881 for line in cell.splitlines():
1882 self.readline.add_history(py3compat.unicode_to_str(line,
1882 self.readline.add_history(py3compat.unicode_to_str(line,
1883 stdin_encoding))
1883 stdin_encoding))
1884 last_cell = cell
1884 last_cell = cell
1885
1885
1886 except TypeError:
1886 except TypeError:
1887 # The history DB can get corrupted so it returns strings
1887 # The history DB can get corrupted so it returns strings
1888 # containing null bytes, which readline objects to.
1888 # containing null bytes, which readline objects to.
1889 continue
1889 continue
1890
1890
1891 @skip_doctest
1891 @skip_doctest
1892 def set_next_input(self, s):
1892 def set_next_input(self, s):
1893 """ Sets the 'default' input string for the next command line.
1893 """ Sets the 'default' input string for the next command line.
1894
1894
1895 Requires readline.
1895 Requires readline.
1896
1896
1897 Example::
1897 Example::
1898
1898
1899 In [1]: _ip.set_next_input("Hello Word")
1899 In [1]: _ip.set_next_input("Hello Word")
1900 In [2]: Hello Word_ # cursor is here
1900 In [2]: Hello Word_ # cursor is here
1901 """
1901 """
1902 self.rl_next_input = py3compat.cast_bytes_py2(s)
1902 self.rl_next_input = py3compat.cast_bytes_py2(s)
1903
1903
1904 # Maybe move this to the terminal subclass?
1904 # Maybe move this to the terminal subclass?
1905 def pre_readline(self):
1905 def pre_readline(self):
1906 """readline hook to be used at the start of each line.
1906 """readline hook to be used at the start of each line.
1907
1907
1908 Currently it handles auto-indent only."""
1908 Currently it handles auto-indent only."""
1909
1909
1910 if self.rl_do_indent:
1910 if self.rl_do_indent:
1911 self.readline.insert_text(self._indent_current_str())
1911 self.readline.insert_text(self._indent_current_str())
1912 if self.rl_next_input is not None:
1912 if self.rl_next_input is not None:
1913 self.readline.insert_text(self.rl_next_input)
1913 self.readline.insert_text(self.rl_next_input)
1914 self.rl_next_input = None
1914 self.rl_next_input = None
1915
1915
1916 def _indent_current_str(self):
1916 def _indent_current_str(self):
1917 """return the current level of indentation as a string"""
1917 """return the current level of indentation as a string"""
1918 return self.input_splitter.indent_spaces * ' '
1918 return self.input_splitter.indent_spaces * ' '
1919
1919
1920 #-------------------------------------------------------------------------
1920 #-------------------------------------------------------------------------
1921 # Things related to text completion
1921 # Things related to text completion
1922 #-------------------------------------------------------------------------
1922 #-------------------------------------------------------------------------
1923
1923
1924 def init_completer(self):
1924 def init_completer(self):
1925 """Initialize the completion machinery.
1925 """Initialize the completion machinery.
1926
1926
1927 This creates completion machinery that can be used by client code,
1927 This creates completion machinery that can be used by client code,
1928 either interactively in-process (typically triggered by the readline
1928 either interactively in-process (typically triggered by the readline
1929 library), programatically (such as in test suites) or out-of-prcess
1929 library), programatically (such as in test suites) or out-of-prcess
1930 (typically over the network by remote frontends).
1930 (typically over the network by remote frontends).
1931 """
1931 """
1932 from IPython.core.completer import IPCompleter
1932 from IPython.core.completer import IPCompleter
1933 from IPython.core.completerlib import (module_completer,
1933 from IPython.core.completerlib import (module_completer,
1934 magic_run_completer, cd_completer, reset_completer)
1934 magic_run_completer, cd_completer, reset_completer)
1935
1935
1936 self.Completer = IPCompleter(shell=self,
1936 self.Completer = IPCompleter(shell=self,
1937 namespace=self.user_ns,
1937 namespace=self.user_ns,
1938 global_namespace=self.user_global_ns,
1938 global_namespace=self.user_global_ns,
1939 #alias_table=self.alias_manager.alias_table,
1940 use_readline=self.has_readline,
1939 use_readline=self.has_readline,
1941 parent=self,
1940 parent=self,
1942 )
1941 )
1943 self.configurables.append(self.Completer)
1942 self.configurables.append(self.Completer)
1944
1943
1945 # Add custom completers to the basic ones built into IPCompleter
1944 # Add custom completers to the basic ones built into IPCompleter
1946 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1945 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1947 self.strdispatchers['complete_command'] = sdisp
1946 self.strdispatchers['complete_command'] = sdisp
1948 self.Completer.custom_completers = sdisp
1947 self.Completer.custom_completers = sdisp
1949
1948
1950 self.set_hook('complete_command', module_completer, str_key = 'import')
1949 self.set_hook('complete_command', module_completer, str_key = 'import')
1951 self.set_hook('complete_command', module_completer, str_key = 'from')
1950 self.set_hook('complete_command', module_completer, str_key = 'from')
1952 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1951 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1953 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1952 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1954 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1953 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1955
1954
1956 # Only configure readline if we truly are using readline. IPython can
1955 # Only configure readline if we truly are using readline. IPython can
1957 # do tab-completion over the network, in GUIs, etc, where readline
1956 # do tab-completion over the network, in GUIs, etc, where readline
1958 # itself may be absent
1957 # itself may be absent
1959 if self.has_readline:
1958 if self.has_readline:
1960 self.set_readline_completer()
1959 self.set_readline_completer()
1961
1960
1962 def complete(self, text, line=None, cursor_pos=None):
1961 def complete(self, text, line=None, cursor_pos=None):
1963 """Return the completed text and a list of completions.
1962 """Return the completed text and a list of completions.
1964
1963
1965 Parameters
1964 Parameters
1966 ----------
1965 ----------
1967
1966
1968 text : string
1967 text : string
1969 A string of text to be completed on. It can be given as empty and
1968 A string of text to be completed on. It can be given as empty and
1970 instead a line/position pair are given. In this case, the
1969 instead a line/position pair are given. In this case, the
1971 completer itself will split the line like readline does.
1970 completer itself will split the line like readline does.
1972
1971
1973 line : string, optional
1972 line : string, optional
1974 The complete line that text is part of.
1973 The complete line that text is part of.
1975
1974
1976 cursor_pos : int, optional
1975 cursor_pos : int, optional
1977 The position of the cursor on the input line.
1976 The position of the cursor on the input line.
1978
1977
1979 Returns
1978 Returns
1980 -------
1979 -------
1981 text : string
1980 text : string
1982 The actual text that was completed.
1981 The actual text that was completed.
1983
1982
1984 matches : list
1983 matches : list
1985 A sorted list with all possible completions.
1984 A sorted list with all possible completions.
1986
1985
1987 The optional arguments allow the completion to take more context into
1986 The optional arguments allow the completion to take more context into
1988 account, and are part of the low-level completion API.
1987 account, and are part of the low-level completion API.
1989
1988
1990 This is a wrapper around the completion mechanism, similar to what
1989 This is a wrapper around the completion mechanism, similar to what
1991 readline does at the command line when the TAB key is hit. By
1990 readline does at the command line when the TAB key is hit. By
1992 exposing it as a method, it can be used by other non-readline
1991 exposing it as a method, it can be used by other non-readline
1993 environments (such as GUIs) for text completion.
1992 environments (such as GUIs) for text completion.
1994
1993
1995 Simple usage example:
1994 Simple usage example:
1996
1995
1997 In [1]: x = 'hello'
1996 In [1]: x = 'hello'
1998
1997
1999 In [2]: _ip.complete('x.l')
1998 In [2]: _ip.complete('x.l')
2000 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1999 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2001 """
2000 """
2002
2001
2003 # Inject names into __builtin__ so we can complete on the added names.
2002 # Inject names into __builtin__ so we can complete on the added names.
2004 with self.builtin_trap:
2003 with self.builtin_trap:
2005 return self.Completer.complete(text, line, cursor_pos)
2004 return self.Completer.complete(text, line, cursor_pos)
2006
2005
2007 def set_custom_completer(self, completer, pos=0):
2006 def set_custom_completer(self, completer, pos=0):
2008 """Adds a new custom completer function.
2007 """Adds a new custom completer function.
2009
2008
2010 The position argument (defaults to 0) is the index in the completers
2009 The position argument (defaults to 0) is the index in the completers
2011 list where you want the completer to be inserted."""
2010 list where you want the completer to be inserted."""
2012
2011
2013 newcomp = types.MethodType(completer,self.Completer)
2012 newcomp = types.MethodType(completer,self.Completer)
2014 self.Completer.matchers.insert(pos,newcomp)
2013 self.Completer.matchers.insert(pos,newcomp)
2015
2014
2016 def set_readline_completer(self):
2015 def set_readline_completer(self):
2017 """Reset readline's completer to be our own."""
2016 """Reset readline's completer to be our own."""
2018 self.readline.set_completer(self.Completer.rlcomplete)
2017 self.readline.set_completer(self.Completer.rlcomplete)
2019
2018
2020 def set_completer_frame(self, frame=None):
2019 def set_completer_frame(self, frame=None):
2021 """Set the frame of the completer."""
2020 """Set the frame of the completer."""
2022 if frame:
2021 if frame:
2023 self.Completer.namespace = frame.f_locals
2022 self.Completer.namespace = frame.f_locals
2024 self.Completer.global_namespace = frame.f_globals
2023 self.Completer.global_namespace = frame.f_globals
2025 else:
2024 else:
2026 self.Completer.namespace = self.user_ns
2025 self.Completer.namespace = self.user_ns
2027 self.Completer.global_namespace = self.user_global_ns
2026 self.Completer.global_namespace = self.user_global_ns
2028
2027
2029 #-------------------------------------------------------------------------
2028 #-------------------------------------------------------------------------
2030 # Things related to magics
2029 # Things related to magics
2031 #-------------------------------------------------------------------------
2030 #-------------------------------------------------------------------------
2032
2031
2033 def init_magics(self):
2032 def init_magics(self):
2034 from IPython.core import magics as m
2033 from IPython.core import magics as m
2035 self.magics_manager = magic.MagicsManager(shell=self,
2034 self.magics_manager = magic.MagicsManager(shell=self,
2036 parent=self,
2035 parent=self,
2037 user_magics=m.UserMagics(self))
2036 user_magics=m.UserMagics(self))
2038 self.configurables.append(self.magics_manager)
2037 self.configurables.append(self.magics_manager)
2039
2038
2040 # Expose as public API from the magics manager
2039 # Expose as public API from the magics manager
2041 self.register_magics = self.magics_manager.register
2040 self.register_magics = self.magics_manager.register
2042 self.define_magic = self.magics_manager.define_magic
2041 self.define_magic = self.magics_manager.define_magic
2043
2042
2044 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2043 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2045 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2044 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2046 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2045 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2047 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2046 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2048 )
2047 )
2049
2048
2050 # Register Magic Aliases
2049 # Register Magic Aliases
2051 mman = self.magics_manager
2050 mman = self.magics_manager
2052 # FIXME: magic aliases should be defined by the Magics classes
2051 # FIXME: magic aliases should be defined by the Magics classes
2053 # or in MagicsManager, not here
2052 # or in MagicsManager, not here
2054 mman.register_alias('ed', 'edit')
2053 mman.register_alias('ed', 'edit')
2055 mman.register_alias('hist', 'history')
2054 mman.register_alias('hist', 'history')
2056 mman.register_alias('rep', 'recall')
2055 mman.register_alias('rep', 'recall')
2057 mman.register_alias('SVG', 'svg', 'cell')
2056 mman.register_alias('SVG', 'svg', 'cell')
2058 mman.register_alias('HTML', 'html', 'cell')
2057 mman.register_alias('HTML', 'html', 'cell')
2059 mman.register_alias('file', 'writefile', 'cell')
2058 mman.register_alias('file', 'writefile', 'cell')
2060
2059
2061 # FIXME: Move the color initialization to the DisplayHook, which
2060 # FIXME: Move the color initialization to the DisplayHook, which
2062 # should be split into a prompt manager and displayhook. We probably
2061 # should be split into a prompt manager and displayhook. We probably
2063 # even need a centralize colors management object.
2062 # even need a centralize colors management object.
2064 self.magic('colors %s' % self.colors)
2063 self.magic('colors %s' % self.colors)
2065
2064
2066 # Defined here so that it's included in the documentation
2065 # Defined here so that it's included in the documentation
2067 @functools.wraps(magic.MagicsManager.register_function)
2066 @functools.wraps(magic.MagicsManager.register_function)
2068 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2067 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2069 self.magics_manager.register_function(func,
2068 self.magics_manager.register_function(func,
2070 magic_kind=magic_kind, magic_name=magic_name)
2069 magic_kind=magic_kind, magic_name=magic_name)
2071
2070
2072 def run_line_magic(self, magic_name, line):
2071 def run_line_magic(self, magic_name, line):
2073 """Execute the given line magic.
2072 """Execute the given line magic.
2074
2073
2075 Parameters
2074 Parameters
2076 ----------
2075 ----------
2077 magic_name : str
2076 magic_name : str
2078 Name of the desired magic function, without '%' prefix.
2077 Name of the desired magic function, without '%' prefix.
2079
2078
2080 line : str
2079 line : str
2081 The rest of the input line as a single string.
2080 The rest of the input line as a single string.
2082 """
2081 """
2083 fn = self.find_line_magic(magic_name)
2082 fn = self.find_line_magic(magic_name)
2084 if fn is None:
2083 if fn is None:
2085 cm = self.find_cell_magic(magic_name)
2084 cm = self.find_cell_magic(magic_name)
2086 etpl = "Line magic function `%%%s` not found%s."
2085 etpl = "Line magic function `%%%s` not found%s."
2087 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2086 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2088 'did you mean that instead?)' % magic_name )
2087 'did you mean that instead?)' % magic_name )
2089 error(etpl % (magic_name, extra))
2088 error(etpl % (magic_name, extra))
2090 else:
2089 else:
2091 # Note: this is the distance in the stack to the user's frame.
2090 # Note: this is the distance in the stack to the user's frame.
2092 # This will need to be updated if the internal calling logic gets
2091 # This will need to be updated if the internal calling logic gets
2093 # refactored, or else we'll be expanding the wrong variables.
2092 # refactored, or else we'll be expanding the wrong variables.
2094 stack_depth = 2
2093 stack_depth = 2
2095 magic_arg_s = self.var_expand(line, stack_depth)
2094 magic_arg_s = self.var_expand(line, stack_depth)
2096 # Put magic args in a list so we can call with f(*a) syntax
2095 # Put magic args in a list so we can call with f(*a) syntax
2097 args = [magic_arg_s]
2096 args = [magic_arg_s]
2098 kwargs = {}
2097 kwargs = {}
2099 # Grab local namespace if we need it:
2098 # Grab local namespace if we need it:
2100 if getattr(fn, "needs_local_scope", False):
2099 if getattr(fn, "needs_local_scope", False):
2101 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2100 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2102 with self.builtin_trap:
2101 with self.builtin_trap:
2103 result = fn(*args,**kwargs)
2102 result = fn(*args,**kwargs)
2104 return result
2103 return result
2105
2104
2106 def run_cell_magic(self, magic_name, line, cell):
2105 def run_cell_magic(self, magic_name, line, cell):
2107 """Execute the given cell magic.
2106 """Execute the given cell magic.
2108
2107
2109 Parameters
2108 Parameters
2110 ----------
2109 ----------
2111 magic_name : str
2110 magic_name : str
2112 Name of the desired magic function, without '%' prefix.
2111 Name of the desired magic function, without '%' prefix.
2113
2112
2114 line : str
2113 line : str
2115 The rest of the first input line as a single string.
2114 The rest of the first input line as a single string.
2116
2115
2117 cell : str
2116 cell : str
2118 The body of the cell as a (possibly multiline) string.
2117 The body of the cell as a (possibly multiline) string.
2119 """
2118 """
2120 fn = self.find_cell_magic(magic_name)
2119 fn = self.find_cell_magic(magic_name)
2121 if fn is None:
2120 if fn is None:
2122 lm = self.find_line_magic(magic_name)
2121 lm = self.find_line_magic(magic_name)
2123 etpl = "Cell magic `%%{0}` not found{1}."
2122 etpl = "Cell magic `%%{0}` not found{1}."
2124 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2123 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2125 'did you mean that instead?)'.format(magic_name))
2124 'did you mean that instead?)'.format(magic_name))
2126 error(etpl.format(magic_name, extra))
2125 error(etpl.format(magic_name, extra))
2127 elif cell == '':
2126 elif cell == '':
2128 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2127 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2129 if self.find_line_magic(magic_name) is not None:
2128 if self.find_line_magic(magic_name) is not None:
2130 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2129 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2131 raise UsageError(message)
2130 raise UsageError(message)
2132 else:
2131 else:
2133 # Note: this is the distance in the stack to the user's frame.
2132 # Note: this is the distance in the stack to the user's frame.
2134 # This will need to be updated if the internal calling logic gets
2133 # This will need to be updated if the internal calling logic gets
2135 # refactored, or else we'll be expanding the wrong variables.
2134 # refactored, or else we'll be expanding the wrong variables.
2136 stack_depth = 2
2135 stack_depth = 2
2137 magic_arg_s = self.var_expand(line, stack_depth)
2136 magic_arg_s = self.var_expand(line, stack_depth)
2138 with self.builtin_trap:
2137 with self.builtin_trap:
2139 result = fn(magic_arg_s, cell)
2138 result = fn(magic_arg_s, cell)
2140 return result
2139 return result
2141
2140
2142 def find_line_magic(self, magic_name):
2141 def find_line_magic(self, magic_name):
2143 """Find and return a line magic by name.
2142 """Find and return a line magic by name.
2144
2143
2145 Returns None if the magic isn't found."""
2144 Returns None if the magic isn't found."""
2146 return self.magics_manager.magics['line'].get(magic_name)
2145 return self.magics_manager.magics['line'].get(magic_name)
2147
2146
2148 def find_cell_magic(self, magic_name):
2147 def find_cell_magic(self, magic_name):
2149 """Find and return a cell magic by name.
2148 """Find and return a cell magic by name.
2150
2149
2151 Returns None if the magic isn't found."""
2150 Returns None if the magic isn't found."""
2152 return self.magics_manager.magics['cell'].get(magic_name)
2151 return self.magics_manager.magics['cell'].get(magic_name)
2153
2152
2154 def find_magic(self, magic_name, magic_kind='line'):
2153 def find_magic(self, magic_name, magic_kind='line'):
2155 """Find and return a magic of the given type by name.
2154 """Find and return a magic of the given type by name.
2156
2155
2157 Returns None if the magic isn't found."""
2156 Returns None if the magic isn't found."""
2158 return self.magics_manager.magics[magic_kind].get(magic_name)
2157 return self.magics_manager.magics[magic_kind].get(magic_name)
2159
2158
2160 def magic(self, arg_s):
2159 def magic(self, arg_s):
2161 """DEPRECATED. Use run_line_magic() instead.
2160 """DEPRECATED. Use run_line_magic() instead.
2162
2161
2163 Call a magic function by name.
2162 Call a magic function by name.
2164
2163
2165 Input: a string containing the name of the magic function to call and
2164 Input: a string containing the name of the magic function to call and
2166 any additional arguments to be passed to the magic.
2165 any additional arguments to be passed to the magic.
2167
2166
2168 magic('name -opt foo bar') is equivalent to typing at the ipython
2167 magic('name -opt foo bar') is equivalent to typing at the ipython
2169 prompt:
2168 prompt:
2170
2169
2171 In[1]: %name -opt foo bar
2170 In[1]: %name -opt foo bar
2172
2171
2173 To call a magic without arguments, simply use magic('name').
2172 To call a magic without arguments, simply use magic('name').
2174
2173
2175 This provides a proper Python function to call IPython's magics in any
2174 This provides a proper Python function to call IPython's magics in any
2176 valid Python code you can type at the interpreter, including loops and
2175 valid Python code you can type at the interpreter, including loops and
2177 compound statements.
2176 compound statements.
2178 """
2177 """
2179 # TODO: should we issue a loud deprecation warning here?
2178 # TODO: should we issue a loud deprecation warning here?
2180 magic_name, _, magic_arg_s = arg_s.partition(' ')
2179 magic_name, _, magic_arg_s = arg_s.partition(' ')
2181 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2180 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2182 return self.run_line_magic(magic_name, magic_arg_s)
2181 return self.run_line_magic(magic_name, magic_arg_s)
2183
2182
2184 #-------------------------------------------------------------------------
2183 #-------------------------------------------------------------------------
2185 # Things related to macros
2184 # Things related to macros
2186 #-------------------------------------------------------------------------
2185 #-------------------------------------------------------------------------
2187
2186
2188 def define_macro(self, name, themacro):
2187 def define_macro(self, name, themacro):
2189 """Define a new macro
2188 """Define a new macro
2190
2189
2191 Parameters
2190 Parameters
2192 ----------
2191 ----------
2193 name : str
2192 name : str
2194 The name of the macro.
2193 The name of the macro.
2195 themacro : str or Macro
2194 themacro : str or Macro
2196 The action to do upon invoking the macro. If a string, a new
2195 The action to do upon invoking the macro. If a string, a new
2197 Macro object is created by passing the string to it.
2196 Macro object is created by passing the string to it.
2198 """
2197 """
2199
2198
2200 from IPython.core import macro
2199 from IPython.core import macro
2201
2200
2202 if isinstance(themacro, basestring):
2201 if isinstance(themacro, basestring):
2203 themacro = macro.Macro(themacro)
2202 themacro = macro.Macro(themacro)
2204 if not isinstance(themacro, macro.Macro):
2203 if not isinstance(themacro, macro.Macro):
2205 raise ValueError('A macro must be a string or a Macro instance.')
2204 raise ValueError('A macro must be a string or a Macro instance.')
2206 self.user_ns[name] = themacro
2205 self.user_ns[name] = themacro
2207
2206
2208 #-------------------------------------------------------------------------
2207 #-------------------------------------------------------------------------
2209 # Things related to the running of system commands
2208 # Things related to the running of system commands
2210 #-------------------------------------------------------------------------
2209 #-------------------------------------------------------------------------
2211
2210
2212 def system_piped(self, cmd):
2211 def system_piped(self, cmd):
2213 """Call the given cmd in a subprocess, piping stdout/err
2212 """Call the given cmd in a subprocess, piping stdout/err
2214
2213
2215 Parameters
2214 Parameters
2216 ----------
2215 ----------
2217 cmd : str
2216 cmd : str
2218 Command to execute (can not end in '&', as background processes are
2217 Command to execute (can not end in '&', as background processes are
2219 not supported. Should not be a command that expects input
2218 not supported. Should not be a command that expects input
2220 other than simple text.
2219 other than simple text.
2221 """
2220 """
2222 if cmd.rstrip().endswith('&'):
2221 if cmd.rstrip().endswith('&'):
2223 # this is *far* from a rigorous test
2222 # this is *far* from a rigorous test
2224 # We do not support backgrounding processes because we either use
2223 # We do not support backgrounding processes because we either use
2225 # pexpect or pipes to read from. Users can always just call
2224 # pexpect or pipes to read from. Users can always just call
2226 # os.system() or use ip.system=ip.system_raw
2225 # os.system() or use ip.system=ip.system_raw
2227 # if they really want a background process.
2226 # if they really want a background process.
2228 raise OSError("Background processes not supported.")
2227 raise OSError("Background processes not supported.")
2229
2228
2230 # we explicitly do NOT return the subprocess status code, because
2229 # we explicitly do NOT return the subprocess status code, because
2231 # a non-None value would trigger :func:`sys.displayhook` calls.
2230 # a non-None value would trigger :func:`sys.displayhook` calls.
2232 # Instead, we store the exit_code in user_ns.
2231 # Instead, we store the exit_code in user_ns.
2233 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2232 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2234
2233
2235 def system_raw(self, cmd):
2234 def system_raw(self, cmd):
2236 """Call the given cmd in a subprocess using os.system
2235 """Call the given cmd in a subprocess using os.system
2237
2236
2238 Parameters
2237 Parameters
2239 ----------
2238 ----------
2240 cmd : str
2239 cmd : str
2241 Command to execute.
2240 Command to execute.
2242 """
2241 """
2243 cmd = self.var_expand(cmd, depth=1)
2242 cmd = self.var_expand(cmd, depth=1)
2244 # protect os.system from UNC paths on Windows, which it can't handle:
2243 # protect os.system from UNC paths on Windows, which it can't handle:
2245 if sys.platform == 'win32':
2244 if sys.platform == 'win32':
2246 from IPython.utils._process_win32 import AvoidUNCPath
2245 from IPython.utils._process_win32 import AvoidUNCPath
2247 with AvoidUNCPath() as path:
2246 with AvoidUNCPath() as path:
2248 if path is not None:
2247 if path is not None:
2249 cmd = '"pushd %s &&"%s' % (path, cmd)
2248 cmd = '"pushd %s &&"%s' % (path, cmd)
2250 cmd = py3compat.unicode_to_str(cmd)
2249 cmd = py3compat.unicode_to_str(cmd)
2251 ec = os.system(cmd)
2250 ec = os.system(cmd)
2252 else:
2251 else:
2253 cmd = py3compat.unicode_to_str(cmd)
2252 cmd = py3compat.unicode_to_str(cmd)
2254 ec = os.system(cmd)
2253 ec = os.system(cmd)
2255 # The high byte is the exit code, the low byte is a signal number
2254 # The high byte is the exit code, the low byte is a signal number
2256 # that we discard for now. See the docs for os.wait()
2255 # that we discard for now. See the docs for os.wait()
2257 if ec > 255:
2256 if ec > 255:
2258 ec >>= 8
2257 ec >>= 8
2259
2258
2260 # We explicitly do NOT return the subprocess status code, because
2259 # We explicitly do NOT return the subprocess status code, because
2261 # a non-None value would trigger :func:`sys.displayhook` calls.
2260 # a non-None value would trigger :func:`sys.displayhook` calls.
2262 # Instead, we store the exit_code in user_ns.
2261 # Instead, we store the exit_code in user_ns.
2263 self.user_ns['_exit_code'] = ec
2262 self.user_ns['_exit_code'] = ec
2264
2263
2265 # use piped system by default, because it is better behaved
2264 # use piped system by default, because it is better behaved
2266 system = system_piped
2265 system = system_piped
2267
2266
2268 def getoutput(self, cmd, split=True, depth=0):
2267 def getoutput(self, cmd, split=True, depth=0):
2269 """Get output (possibly including stderr) from a subprocess.
2268 """Get output (possibly including stderr) from a subprocess.
2270
2269
2271 Parameters
2270 Parameters
2272 ----------
2271 ----------
2273 cmd : str
2272 cmd : str
2274 Command to execute (can not end in '&', as background processes are
2273 Command to execute (can not end in '&', as background processes are
2275 not supported.
2274 not supported.
2276 split : bool, optional
2275 split : bool, optional
2277 If True, split the output into an IPython SList. Otherwise, an
2276 If True, split the output into an IPython SList. Otherwise, an
2278 IPython LSString is returned. These are objects similar to normal
2277 IPython LSString is returned. These are objects similar to normal
2279 lists and strings, with a few convenience attributes for easier
2278 lists and strings, with a few convenience attributes for easier
2280 manipulation of line-based output. You can use '?' on them for
2279 manipulation of line-based output. You can use '?' on them for
2281 details.
2280 details.
2282 depth : int, optional
2281 depth : int, optional
2283 How many frames above the caller are the local variables which should
2282 How many frames above the caller are the local variables which should
2284 be expanded in the command string? The default (0) assumes that the
2283 be expanded in the command string? The default (0) assumes that the
2285 expansion variables are in the stack frame calling this function.
2284 expansion variables are in the stack frame calling this function.
2286 """
2285 """
2287 if cmd.rstrip().endswith('&'):
2286 if cmd.rstrip().endswith('&'):
2288 # this is *far* from a rigorous test
2287 # this is *far* from a rigorous test
2289 raise OSError("Background processes not supported.")
2288 raise OSError("Background processes not supported.")
2290 out = getoutput(self.var_expand(cmd, depth=depth+1))
2289 out = getoutput(self.var_expand(cmd, depth=depth+1))
2291 if split:
2290 if split:
2292 out = SList(out.splitlines())
2291 out = SList(out.splitlines())
2293 else:
2292 else:
2294 out = LSString(out)
2293 out = LSString(out)
2295 return out
2294 return out
2296
2295
2297 #-------------------------------------------------------------------------
2296 #-------------------------------------------------------------------------
2298 # Things related to aliases
2297 # Things related to aliases
2299 #-------------------------------------------------------------------------
2298 #-------------------------------------------------------------------------
2300
2299
2301 def init_alias(self):
2300 def init_alias(self):
2302 self.alias_manager = AliasManager(shell=self, parent=self)
2301 self.alias_manager = AliasManager(shell=self, parent=self)
2303 self.configurables.append(self.alias_manager)
2302 self.configurables.append(self.alias_manager)
2304
2303
2305 #-------------------------------------------------------------------------
2304 #-------------------------------------------------------------------------
2306 # Things related to extensions
2305 # Things related to extensions
2307 #-------------------------------------------------------------------------
2306 #-------------------------------------------------------------------------
2308
2307
2309 def init_extension_manager(self):
2308 def init_extension_manager(self):
2310 self.extension_manager = ExtensionManager(shell=self, parent=self)
2309 self.extension_manager = ExtensionManager(shell=self, parent=self)
2311 self.configurables.append(self.extension_manager)
2310 self.configurables.append(self.extension_manager)
2312
2311
2313 #-------------------------------------------------------------------------
2312 #-------------------------------------------------------------------------
2314 # Things related to payloads
2313 # Things related to payloads
2315 #-------------------------------------------------------------------------
2314 #-------------------------------------------------------------------------
2316
2315
2317 def init_payload(self):
2316 def init_payload(self):
2318 self.payload_manager = PayloadManager(parent=self)
2317 self.payload_manager = PayloadManager(parent=self)
2319 self.configurables.append(self.payload_manager)
2318 self.configurables.append(self.payload_manager)
2320
2319
2321 #-------------------------------------------------------------------------
2320 #-------------------------------------------------------------------------
2322 # Things related to the prefilter
2321 # Things related to the prefilter
2323 #-------------------------------------------------------------------------
2322 #-------------------------------------------------------------------------
2324
2323
2325 def init_prefilter(self):
2324 def init_prefilter(self):
2326 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2325 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2327 self.configurables.append(self.prefilter_manager)
2326 self.configurables.append(self.prefilter_manager)
2328 # Ultimately this will be refactored in the new interpreter code, but
2327 # Ultimately this will be refactored in the new interpreter code, but
2329 # for now, we should expose the main prefilter method (there's legacy
2328 # for now, we should expose the main prefilter method (there's legacy
2330 # code out there that may rely on this).
2329 # code out there that may rely on this).
2331 self.prefilter = self.prefilter_manager.prefilter_lines
2330 self.prefilter = self.prefilter_manager.prefilter_lines
2332
2331
2333 def auto_rewrite_input(self, cmd):
2332 def auto_rewrite_input(self, cmd):
2334 """Print to the screen the rewritten form of the user's command.
2333 """Print to the screen the rewritten form of the user's command.
2335
2334
2336 This shows visual feedback by rewriting input lines that cause
2335 This shows visual feedback by rewriting input lines that cause
2337 automatic calling to kick in, like::
2336 automatic calling to kick in, like::
2338
2337
2339 /f x
2338 /f x
2340
2339
2341 into::
2340 into::
2342
2341
2343 ------> f(x)
2342 ------> f(x)
2344
2343
2345 after the user's input prompt. This helps the user understand that the
2344 after the user's input prompt. This helps the user understand that the
2346 input line was transformed automatically by IPython.
2345 input line was transformed automatically by IPython.
2347 """
2346 """
2348 if not self.show_rewritten_input:
2347 if not self.show_rewritten_input:
2349 return
2348 return
2350
2349
2351 rw = self.prompt_manager.render('rewrite') + cmd
2350 rw = self.prompt_manager.render('rewrite') + cmd
2352
2351
2353 try:
2352 try:
2354 # plain ascii works better w/ pyreadline, on some machines, so
2353 # plain ascii works better w/ pyreadline, on some machines, so
2355 # we use it and only print uncolored rewrite if we have unicode
2354 # we use it and only print uncolored rewrite if we have unicode
2356 rw = str(rw)
2355 rw = str(rw)
2357 print(rw, file=io.stdout)
2356 print(rw, file=io.stdout)
2358 except UnicodeEncodeError:
2357 except UnicodeEncodeError:
2359 print("------> " + cmd)
2358 print("------> " + cmd)
2360
2359
2361 #-------------------------------------------------------------------------
2360 #-------------------------------------------------------------------------
2362 # Things related to extracting values/expressions from kernel and user_ns
2361 # Things related to extracting values/expressions from kernel and user_ns
2363 #-------------------------------------------------------------------------
2362 #-------------------------------------------------------------------------
2364
2363
2365 def _user_obj_error(self):
2364 def _user_obj_error(self):
2366 """return simple exception dict
2365 """return simple exception dict
2367
2366
2368 for use in user_variables / expressions
2367 for use in user_variables / expressions
2369 """
2368 """
2370
2369
2371 etype, evalue, tb = self._get_exc_info()
2370 etype, evalue, tb = self._get_exc_info()
2372 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2371 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2373
2372
2374 exc_info = {
2373 exc_info = {
2375 u'status' : 'error',
2374 u'status' : 'error',
2376 u'traceback' : stb,
2375 u'traceback' : stb,
2377 u'ename' : unicode(etype.__name__),
2376 u'ename' : unicode(etype.__name__),
2378 u'evalue' : py3compat.safe_unicode(evalue),
2377 u'evalue' : py3compat.safe_unicode(evalue),
2379 }
2378 }
2380
2379
2381 return exc_info
2380 return exc_info
2382
2381
2383 def _format_user_obj(self, obj):
2382 def _format_user_obj(self, obj):
2384 """format a user object to display dict
2383 """format a user object to display dict
2385
2384
2386 for use in user_expressions / variables
2385 for use in user_expressions / variables
2387 """
2386 """
2388
2387
2389 data, md = self.display_formatter.format(obj)
2388 data, md = self.display_formatter.format(obj)
2390 value = {
2389 value = {
2391 'status' : 'ok',
2390 'status' : 'ok',
2392 'data' : data,
2391 'data' : data,
2393 'metadata' : md,
2392 'metadata' : md,
2394 }
2393 }
2395 return value
2394 return value
2396
2395
2397 def user_variables(self, names):
2396 def user_variables(self, names):
2398 """Get a list of variable names from the user's namespace.
2397 """Get a list of variable names from the user's namespace.
2399
2398
2400 Parameters
2399 Parameters
2401 ----------
2400 ----------
2402 names : list of strings
2401 names : list of strings
2403 A list of names of variables to be read from the user namespace.
2402 A list of names of variables to be read from the user namespace.
2404
2403
2405 Returns
2404 Returns
2406 -------
2405 -------
2407 A dict, keyed by the input names and with the rich mime-type repr(s) of each value.
2406 A dict, keyed by the input names and with the rich mime-type repr(s) of each value.
2408 Each element will be a sub-dict of the same form as a display_data message.
2407 Each element will be a sub-dict of the same form as a display_data message.
2409 """
2408 """
2410 out = {}
2409 out = {}
2411 user_ns = self.user_ns
2410 user_ns = self.user_ns
2412
2411
2413 for varname in names:
2412 for varname in names:
2414 try:
2413 try:
2415 value = self._format_user_obj(user_ns[varname])
2414 value = self._format_user_obj(user_ns[varname])
2416 except:
2415 except:
2417 value = self._user_obj_error()
2416 value = self._user_obj_error()
2418 out[varname] = value
2417 out[varname] = value
2419 return out
2418 return out
2420
2419
2421 def user_expressions(self, expressions):
2420 def user_expressions(self, expressions):
2422 """Evaluate a dict of expressions in the user's namespace.
2421 """Evaluate a dict of expressions in the user's namespace.
2423
2422
2424 Parameters
2423 Parameters
2425 ----------
2424 ----------
2426 expressions : dict
2425 expressions : dict
2427 A dict with string keys and string values. The expression values
2426 A dict with string keys and string values. The expression values
2428 should be valid Python expressions, each of which will be evaluated
2427 should be valid Python expressions, each of which will be evaluated
2429 in the user namespace.
2428 in the user namespace.
2430
2429
2431 Returns
2430 Returns
2432 -------
2431 -------
2433 A dict, keyed like the input expressions dict, with the rich mime-typed
2432 A dict, keyed like the input expressions dict, with the rich mime-typed
2434 display_data of each value.
2433 display_data of each value.
2435 """
2434 """
2436 out = {}
2435 out = {}
2437 user_ns = self.user_ns
2436 user_ns = self.user_ns
2438 global_ns = self.user_global_ns
2437 global_ns = self.user_global_ns
2439
2438
2440 for key, expr in expressions.iteritems():
2439 for key, expr in expressions.iteritems():
2441 try:
2440 try:
2442 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2441 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2443 except:
2442 except:
2444 value = self._user_obj_error()
2443 value = self._user_obj_error()
2445 out[key] = value
2444 out[key] = value
2446 return out
2445 return out
2447
2446
2448 #-------------------------------------------------------------------------
2447 #-------------------------------------------------------------------------
2449 # Things related to the running of code
2448 # Things related to the running of code
2450 #-------------------------------------------------------------------------
2449 #-------------------------------------------------------------------------
2451
2450
2452 def ex(self, cmd):
2451 def ex(self, cmd):
2453 """Execute a normal python statement in user namespace."""
2452 """Execute a normal python statement in user namespace."""
2454 with self.builtin_trap:
2453 with self.builtin_trap:
2455 exec cmd in self.user_global_ns, self.user_ns
2454 exec cmd in self.user_global_ns, self.user_ns
2456
2455
2457 def ev(self, expr):
2456 def ev(self, expr):
2458 """Evaluate python expression expr in user namespace.
2457 """Evaluate python expression expr in user namespace.
2459
2458
2460 Returns the result of evaluation
2459 Returns the result of evaluation
2461 """
2460 """
2462 with self.builtin_trap:
2461 with self.builtin_trap:
2463 return eval(expr, self.user_global_ns, self.user_ns)
2462 return eval(expr, self.user_global_ns, self.user_ns)
2464
2463
2465 def safe_execfile(self, fname, *where, **kw):
2464 def safe_execfile(self, fname, *where, **kw):
2466 """A safe version of the builtin execfile().
2465 """A safe version of the builtin execfile().
2467
2466
2468 This version will never throw an exception, but instead print
2467 This version will never throw an exception, but instead print
2469 helpful error messages to the screen. This only works on pure
2468 helpful error messages to the screen. This only works on pure
2470 Python files with the .py extension.
2469 Python files with the .py extension.
2471
2470
2472 Parameters
2471 Parameters
2473 ----------
2472 ----------
2474 fname : string
2473 fname : string
2475 The name of the file to be executed.
2474 The name of the file to be executed.
2476 where : tuple
2475 where : tuple
2477 One or two namespaces, passed to execfile() as (globals,locals).
2476 One or two namespaces, passed to execfile() as (globals,locals).
2478 If only one is given, it is passed as both.
2477 If only one is given, it is passed as both.
2479 exit_ignore : bool (False)
2478 exit_ignore : bool (False)
2480 If True, then silence SystemExit for non-zero status (it is always
2479 If True, then silence SystemExit for non-zero status (it is always
2481 silenced for zero status, as it is so common).
2480 silenced for zero status, as it is so common).
2482 raise_exceptions : bool (False)
2481 raise_exceptions : bool (False)
2483 If True raise exceptions everywhere. Meant for testing.
2482 If True raise exceptions everywhere. Meant for testing.
2484
2483
2485 """
2484 """
2486 kw.setdefault('exit_ignore', False)
2485 kw.setdefault('exit_ignore', False)
2487 kw.setdefault('raise_exceptions', False)
2486 kw.setdefault('raise_exceptions', False)
2488
2487
2489 fname = os.path.abspath(os.path.expanduser(fname))
2488 fname = os.path.abspath(os.path.expanduser(fname))
2490
2489
2491 # Make sure we can open the file
2490 # Make sure we can open the file
2492 try:
2491 try:
2493 with open(fname) as thefile:
2492 with open(fname) as thefile:
2494 pass
2493 pass
2495 except:
2494 except:
2496 warn('Could not open file <%s> for safe execution.' % fname)
2495 warn('Could not open file <%s> for safe execution.' % fname)
2497 return
2496 return
2498
2497
2499 # Find things also in current directory. This is needed to mimic the
2498 # Find things also in current directory. This is needed to mimic the
2500 # behavior of running a script from the system command line, where
2499 # behavior of running a script from the system command line, where
2501 # Python inserts the script's directory into sys.path
2500 # Python inserts the script's directory into sys.path
2502 dname = os.path.dirname(fname)
2501 dname = os.path.dirname(fname)
2503
2502
2504 with prepended_to_syspath(dname):
2503 with prepended_to_syspath(dname):
2505 try:
2504 try:
2506 py3compat.execfile(fname,*where)
2505 py3compat.execfile(fname,*where)
2507 except SystemExit as status:
2506 except SystemExit as status:
2508 # If the call was made with 0 or None exit status (sys.exit(0)
2507 # If the call was made with 0 or None exit status (sys.exit(0)
2509 # or sys.exit() ), don't bother showing a traceback, as both of
2508 # or sys.exit() ), don't bother showing a traceback, as both of
2510 # these are considered normal by the OS:
2509 # these are considered normal by the OS:
2511 # > python -c'import sys;sys.exit(0)'; echo $?
2510 # > python -c'import sys;sys.exit(0)'; echo $?
2512 # 0
2511 # 0
2513 # > python -c'import sys;sys.exit()'; echo $?
2512 # > python -c'import sys;sys.exit()'; echo $?
2514 # 0
2513 # 0
2515 # For other exit status, we show the exception unless
2514 # For other exit status, we show the exception unless
2516 # explicitly silenced, but only in short form.
2515 # explicitly silenced, but only in short form.
2517 if kw['raise_exceptions']:
2516 if kw['raise_exceptions']:
2518 raise
2517 raise
2519 if status.code and not kw['exit_ignore']:
2518 if status.code and not kw['exit_ignore']:
2520 self.showtraceback(exception_only=True)
2519 self.showtraceback(exception_only=True)
2521 except:
2520 except:
2522 if kw['raise_exceptions']:
2521 if kw['raise_exceptions']:
2523 raise
2522 raise
2524 self.showtraceback()
2523 self.showtraceback()
2525
2524
2526 def safe_execfile_ipy(self, fname):
2525 def safe_execfile_ipy(self, fname):
2527 """Like safe_execfile, but for .ipy files with IPython syntax.
2526 """Like safe_execfile, but for .ipy files with IPython syntax.
2528
2527
2529 Parameters
2528 Parameters
2530 ----------
2529 ----------
2531 fname : str
2530 fname : str
2532 The name of the file to execute. The filename must have a
2531 The name of the file to execute. The filename must have a
2533 .ipy extension.
2532 .ipy extension.
2534 """
2533 """
2535 fname = os.path.abspath(os.path.expanduser(fname))
2534 fname = os.path.abspath(os.path.expanduser(fname))
2536
2535
2537 # Make sure we can open the file
2536 # Make sure we can open the file
2538 try:
2537 try:
2539 with open(fname) as thefile:
2538 with open(fname) as thefile:
2540 pass
2539 pass
2541 except:
2540 except:
2542 warn('Could not open file <%s> for safe execution.' % fname)
2541 warn('Could not open file <%s> for safe execution.' % fname)
2543 return
2542 return
2544
2543
2545 # Find things also in current directory. This is needed to mimic the
2544 # Find things also in current directory. This is needed to mimic the
2546 # behavior of running a script from the system command line, where
2545 # behavior of running a script from the system command line, where
2547 # Python inserts the script's directory into sys.path
2546 # Python inserts the script's directory into sys.path
2548 dname = os.path.dirname(fname)
2547 dname = os.path.dirname(fname)
2549
2548
2550 with prepended_to_syspath(dname):
2549 with prepended_to_syspath(dname):
2551 try:
2550 try:
2552 with open(fname) as thefile:
2551 with open(fname) as thefile:
2553 # self.run_cell currently captures all exceptions
2552 # self.run_cell currently captures all exceptions
2554 # raised in user code. It would be nice if there were
2553 # raised in user code. It would be nice if there were
2555 # versions of runlines, execfile that did raise, so
2554 # versions of runlines, execfile that did raise, so
2556 # we could catch the errors.
2555 # we could catch the errors.
2557 self.run_cell(thefile.read(), store_history=False, shell_futures=False)
2556 self.run_cell(thefile.read(), store_history=False, shell_futures=False)
2558 except:
2557 except:
2559 self.showtraceback()
2558 self.showtraceback()
2560 warn('Unknown failure executing file: <%s>' % fname)
2559 warn('Unknown failure executing file: <%s>' % fname)
2561
2560
2562 def safe_run_module(self, mod_name, where):
2561 def safe_run_module(self, mod_name, where):
2563 """A safe version of runpy.run_module().
2562 """A safe version of runpy.run_module().
2564
2563
2565 This version will never throw an exception, but instead print
2564 This version will never throw an exception, but instead print
2566 helpful error messages to the screen.
2565 helpful error messages to the screen.
2567
2566
2568 `SystemExit` exceptions with status code 0 or None are ignored.
2567 `SystemExit` exceptions with status code 0 or None are ignored.
2569
2568
2570 Parameters
2569 Parameters
2571 ----------
2570 ----------
2572 mod_name : string
2571 mod_name : string
2573 The name of the module to be executed.
2572 The name of the module to be executed.
2574 where : dict
2573 where : dict
2575 The globals namespace.
2574 The globals namespace.
2576 """
2575 """
2577 try:
2576 try:
2578 try:
2577 try:
2579 where.update(
2578 where.update(
2580 runpy.run_module(str(mod_name), run_name="__main__",
2579 runpy.run_module(str(mod_name), run_name="__main__",
2581 alter_sys=True)
2580 alter_sys=True)
2582 )
2581 )
2583 except SystemExit as status:
2582 except SystemExit as status:
2584 if status.code:
2583 if status.code:
2585 raise
2584 raise
2586 except:
2585 except:
2587 self.showtraceback()
2586 self.showtraceback()
2588 warn('Unknown failure executing module: <%s>' % mod_name)
2587 warn('Unknown failure executing module: <%s>' % mod_name)
2589
2588
2590 def _run_cached_cell_magic(self, magic_name, line):
2589 def _run_cached_cell_magic(self, magic_name, line):
2591 """Special method to call a cell magic with the data stored in self.
2590 """Special method to call a cell magic with the data stored in self.
2592 """
2591 """
2593 cell = self._current_cell_magic_body
2592 cell = self._current_cell_magic_body
2594 self._current_cell_magic_body = None
2593 self._current_cell_magic_body = None
2595 return self.run_cell_magic(magic_name, line, cell)
2594 return self.run_cell_magic(magic_name, line, cell)
2596
2595
2597 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2596 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2598 """Run a complete IPython cell.
2597 """Run a complete IPython cell.
2599
2598
2600 Parameters
2599 Parameters
2601 ----------
2600 ----------
2602 raw_cell : str
2601 raw_cell : str
2603 The code (including IPython code such as %magic functions) to run.
2602 The code (including IPython code such as %magic functions) to run.
2604 store_history : bool
2603 store_history : bool
2605 If True, the raw and translated cell will be stored in IPython's
2604 If True, the raw and translated cell will be stored in IPython's
2606 history. For user code calling back into IPython's machinery, this
2605 history. For user code calling back into IPython's machinery, this
2607 should be set to False.
2606 should be set to False.
2608 silent : bool
2607 silent : bool
2609 If True, avoid side-effects, such as implicit displayhooks and
2608 If True, avoid side-effects, such as implicit displayhooks and
2610 and logging. silent=True forces store_history=False.
2609 and logging. silent=True forces store_history=False.
2611 shell_futures : bool
2610 shell_futures : bool
2612 If True, the code will share future statements with the interactive
2611 If True, the code will share future statements with the interactive
2613 shell. It will both be affected by previous __future__ imports, and
2612 shell. It will both be affected by previous __future__ imports, and
2614 any __future__ imports in the code will affect the shell. If False,
2613 any __future__ imports in the code will affect the shell. If False,
2615 __future__ imports are not shared in either direction.
2614 __future__ imports are not shared in either direction.
2616 """
2615 """
2617 if (not raw_cell) or raw_cell.isspace():
2616 if (not raw_cell) or raw_cell.isspace():
2618 return
2617 return
2619
2618
2620 if silent:
2619 if silent:
2621 store_history = False
2620 store_history = False
2622
2621
2623 self.input_transformer_manager.push(raw_cell)
2622 self.input_transformer_manager.push(raw_cell)
2624 cell = self.input_transformer_manager.source_reset()
2623 cell = self.input_transformer_manager.source_reset()
2625
2624
2626 # Our own compiler remembers the __future__ environment. If we want to
2625 # Our own compiler remembers the __future__ environment. If we want to
2627 # run code with a separate __future__ environment, use the default
2626 # run code with a separate __future__ environment, use the default
2628 # compiler
2627 # compiler
2629 compiler = self.compile if shell_futures else CachingCompiler()
2628 compiler = self.compile if shell_futures else CachingCompiler()
2630
2629
2631 with self.builtin_trap:
2630 with self.builtin_trap:
2632 prefilter_failed = False
2631 prefilter_failed = False
2633 if len(cell.splitlines()) == 1:
2632 if len(cell.splitlines()) == 1:
2634 try:
2633 try:
2635 # use prefilter_lines to handle trailing newlines
2634 # use prefilter_lines to handle trailing newlines
2636 # restore trailing newline for ast.parse
2635 # restore trailing newline for ast.parse
2637 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2636 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2638 except AliasError as e:
2637 except AliasError as e:
2639 error(e)
2638 error(e)
2640 prefilter_failed = True
2639 prefilter_failed = True
2641 except Exception:
2640 except Exception:
2642 # don't allow prefilter errors to crash IPython
2641 # don't allow prefilter errors to crash IPython
2643 self.showtraceback()
2642 self.showtraceback()
2644 prefilter_failed = True
2643 prefilter_failed = True
2645
2644
2646 # Store raw and processed history
2645 # Store raw and processed history
2647 if store_history:
2646 if store_history:
2648 self.history_manager.store_inputs(self.execution_count,
2647 self.history_manager.store_inputs(self.execution_count,
2649 cell, raw_cell)
2648 cell, raw_cell)
2650 if not silent:
2649 if not silent:
2651 self.logger.log(cell, raw_cell)
2650 self.logger.log(cell, raw_cell)
2652
2651
2653 if not prefilter_failed:
2652 if not prefilter_failed:
2654 # don't run if prefilter failed
2653 # don't run if prefilter failed
2655 cell_name = self.compile.cache(cell, self.execution_count)
2654 cell_name = self.compile.cache(cell, self.execution_count)
2656
2655
2657 with self.display_trap:
2656 with self.display_trap:
2658 try:
2657 try:
2659 code_ast = compiler.ast_parse(cell, filename=cell_name)
2658 code_ast = compiler.ast_parse(cell, filename=cell_name)
2660 except IndentationError:
2659 except IndentationError:
2661 self.showindentationerror()
2660 self.showindentationerror()
2662 if store_history:
2661 if store_history:
2663 self.execution_count += 1
2662 self.execution_count += 1
2664 return None
2663 return None
2665 except (OverflowError, SyntaxError, ValueError, TypeError,
2664 except (OverflowError, SyntaxError, ValueError, TypeError,
2666 MemoryError):
2665 MemoryError):
2667 self.showsyntaxerror()
2666 self.showsyntaxerror()
2668 if store_history:
2667 if store_history:
2669 self.execution_count += 1
2668 self.execution_count += 1
2670 return None
2669 return None
2671
2670
2672 code_ast = self.transform_ast(code_ast)
2671 code_ast = self.transform_ast(code_ast)
2673
2672
2674 interactivity = "none" if silent else self.ast_node_interactivity
2673 interactivity = "none" if silent else self.ast_node_interactivity
2675 self.run_ast_nodes(code_ast.body, cell_name,
2674 self.run_ast_nodes(code_ast.body, cell_name,
2676 interactivity=interactivity, compiler=compiler)
2675 interactivity=interactivity, compiler=compiler)
2677
2676
2678 # Execute any registered post-execution functions.
2677 # Execute any registered post-execution functions.
2679 # unless we are silent
2678 # unless we are silent
2680 post_exec = [] if silent else self._post_execute.iteritems()
2679 post_exec = [] if silent else self._post_execute.iteritems()
2681
2680
2682 for func, status in post_exec:
2681 for func, status in post_exec:
2683 if self.disable_failing_post_execute and not status:
2682 if self.disable_failing_post_execute and not status:
2684 continue
2683 continue
2685 try:
2684 try:
2686 func()
2685 func()
2687 except KeyboardInterrupt:
2686 except KeyboardInterrupt:
2688 print("\nKeyboardInterrupt", file=io.stderr)
2687 print("\nKeyboardInterrupt", file=io.stderr)
2689 except Exception:
2688 except Exception:
2690 # register as failing:
2689 # register as failing:
2691 self._post_execute[func] = False
2690 self._post_execute[func] = False
2692 self.showtraceback()
2691 self.showtraceback()
2693 print('\n'.join([
2692 print('\n'.join([
2694 "post-execution function %r produced an error." % func,
2693 "post-execution function %r produced an error." % func,
2695 "If this problem persists, you can disable failing post-exec functions with:",
2694 "If this problem persists, you can disable failing post-exec functions with:",
2696 "",
2695 "",
2697 " get_ipython().disable_failing_post_execute = True"
2696 " get_ipython().disable_failing_post_execute = True"
2698 ]), file=io.stderr)
2697 ]), file=io.stderr)
2699
2698
2700 if store_history:
2699 if store_history:
2701 # Write output to the database. Does nothing unless
2700 # Write output to the database. Does nothing unless
2702 # history output logging is enabled.
2701 # history output logging is enabled.
2703 self.history_manager.store_output(self.execution_count)
2702 self.history_manager.store_output(self.execution_count)
2704 # Each cell is a *single* input, regardless of how many lines it has
2703 # Each cell is a *single* input, regardless of how many lines it has
2705 self.execution_count += 1
2704 self.execution_count += 1
2706
2705
2707 def transform_ast(self, node):
2706 def transform_ast(self, node):
2708 """Apply the AST transformations from self.ast_transformers
2707 """Apply the AST transformations from self.ast_transformers
2709
2708
2710 Parameters
2709 Parameters
2711 ----------
2710 ----------
2712 node : ast.Node
2711 node : ast.Node
2713 The root node to be transformed. Typically called with the ast.Module
2712 The root node to be transformed. Typically called with the ast.Module
2714 produced by parsing user input.
2713 produced by parsing user input.
2715
2714
2716 Returns
2715 Returns
2717 -------
2716 -------
2718 An ast.Node corresponding to the node it was called with. Note that it
2717 An ast.Node corresponding to the node it was called with. Note that it
2719 may also modify the passed object, so don't rely on references to the
2718 may also modify the passed object, so don't rely on references to the
2720 original AST.
2719 original AST.
2721 """
2720 """
2722 for transformer in self.ast_transformers:
2721 for transformer in self.ast_transformers:
2723 try:
2722 try:
2724 node = transformer.visit(node)
2723 node = transformer.visit(node)
2725 except Exception:
2724 except Exception:
2726 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2725 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2727 self.ast_transformers.remove(transformer)
2726 self.ast_transformers.remove(transformer)
2728
2727
2729 if self.ast_transformers:
2728 if self.ast_transformers:
2730 ast.fix_missing_locations(node)
2729 ast.fix_missing_locations(node)
2731 return node
2730 return node
2732
2731
2733
2732
2734 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2733 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2735 compiler=compile):
2734 compiler=compile):
2736 """Run a sequence of AST nodes. The execution mode depends on the
2735 """Run a sequence of AST nodes. The execution mode depends on the
2737 interactivity parameter.
2736 interactivity parameter.
2738
2737
2739 Parameters
2738 Parameters
2740 ----------
2739 ----------
2741 nodelist : list
2740 nodelist : list
2742 A sequence of AST nodes to run.
2741 A sequence of AST nodes to run.
2743 cell_name : str
2742 cell_name : str
2744 Will be passed to the compiler as the filename of the cell. Typically
2743 Will be passed to the compiler as the filename of the cell. Typically
2745 the value returned by ip.compile.cache(cell).
2744 the value returned by ip.compile.cache(cell).
2746 interactivity : str
2745 interactivity : str
2747 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2746 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2748 run interactively (displaying output from expressions). 'last_expr'
2747 run interactively (displaying output from expressions). 'last_expr'
2749 will run the last node interactively only if it is an expression (i.e.
2748 will run the last node interactively only if it is an expression (i.e.
2750 expressions in loops or other blocks are not displayed. Other values
2749 expressions in loops or other blocks are not displayed. Other values
2751 for this parameter will raise a ValueError.
2750 for this parameter will raise a ValueError.
2752 compiler : callable
2751 compiler : callable
2753 A function with the same interface as the built-in compile(), to turn
2752 A function with the same interface as the built-in compile(), to turn
2754 the AST nodes into code objects. Default is the built-in compile().
2753 the AST nodes into code objects. Default is the built-in compile().
2755 """
2754 """
2756 if not nodelist:
2755 if not nodelist:
2757 return
2756 return
2758
2757
2759 if interactivity == 'last_expr':
2758 if interactivity == 'last_expr':
2760 if isinstance(nodelist[-1], ast.Expr):
2759 if isinstance(nodelist[-1], ast.Expr):
2761 interactivity = "last"
2760 interactivity = "last"
2762 else:
2761 else:
2763 interactivity = "none"
2762 interactivity = "none"
2764
2763
2765 if interactivity == 'none':
2764 if interactivity == 'none':
2766 to_run_exec, to_run_interactive = nodelist, []
2765 to_run_exec, to_run_interactive = nodelist, []
2767 elif interactivity == 'last':
2766 elif interactivity == 'last':
2768 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2767 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2769 elif interactivity == 'all':
2768 elif interactivity == 'all':
2770 to_run_exec, to_run_interactive = [], nodelist
2769 to_run_exec, to_run_interactive = [], nodelist
2771 else:
2770 else:
2772 raise ValueError("Interactivity was %r" % interactivity)
2771 raise ValueError("Interactivity was %r" % interactivity)
2773
2772
2774 exec_count = self.execution_count
2773 exec_count = self.execution_count
2775
2774
2776 try:
2775 try:
2777 for i, node in enumerate(to_run_exec):
2776 for i, node in enumerate(to_run_exec):
2778 mod = ast.Module([node])
2777 mod = ast.Module([node])
2779 code = compiler(mod, cell_name, "exec")
2778 code = compiler(mod, cell_name, "exec")
2780 if self.run_code(code):
2779 if self.run_code(code):
2781 return True
2780 return True
2782
2781
2783 for i, node in enumerate(to_run_interactive):
2782 for i, node in enumerate(to_run_interactive):
2784 mod = ast.Interactive([node])
2783 mod = ast.Interactive([node])
2785 code = compiler(mod, cell_name, "single")
2784 code = compiler(mod, cell_name, "single")
2786 if self.run_code(code):
2785 if self.run_code(code):
2787 return True
2786 return True
2788
2787
2789 # Flush softspace
2788 # Flush softspace
2790 if softspace(sys.stdout, 0):
2789 if softspace(sys.stdout, 0):
2791 print()
2790 print()
2792
2791
2793 except:
2792 except:
2794 # It's possible to have exceptions raised here, typically by
2793 # It's possible to have exceptions raised here, typically by
2795 # compilation of odd code (such as a naked 'return' outside a
2794 # compilation of odd code (such as a naked 'return' outside a
2796 # function) that did parse but isn't valid. Typically the exception
2795 # function) that did parse but isn't valid. Typically the exception
2797 # is a SyntaxError, but it's safest just to catch anything and show
2796 # is a SyntaxError, but it's safest just to catch anything and show
2798 # the user a traceback.
2797 # the user a traceback.
2799
2798
2800 # We do only one try/except outside the loop to minimize the impact
2799 # We do only one try/except outside the loop to minimize the impact
2801 # on runtime, and also because if any node in the node list is
2800 # on runtime, and also because if any node in the node list is
2802 # broken, we should stop execution completely.
2801 # broken, we should stop execution completely.
2803 self.showtraceback()
2802 self.showtraceback()
2804
2803
2805 return False
2804 return False
2806
2805
2807 def run_code(self, code_obj):
2806 def run_code(self, code_obj):
2808 """Execute a code object.
2807 """Execute a code object.
2809
2808
2810 When an exception occurs, self.showtraceback() is called to display a
2809 When an exception occurs, self.showtraceback() is called to display a
2811 traceback.
2810 traceback.
2812
2811
2813 Parameters
2812 Parameters
2814 ----------
2813 ----------
2815 code_obj : code object
2814 code_obj : code object
2816 A compiled code object, to be executed
2815 A compiled code object, to be executed
2817
2816
2818 Returns
2817 Returns
2819 -------
2818 -------
2820 False : successful execution.
2819 False : successful execution.
2821 True : an error occurred.
2820 True : an error occurred.
2822 """
2821 """
2823
2822
2824 # Set our own excepthook in case the user code tries to call it
2823 # Set our own excepthook in case the user code tries to call it
2825 # directly, so that the IPython crash handler doesn't get triggered
2824 # directly, so that the IPython crash handler doesn't get triggered
2826 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2825 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2827
2826
2828 # we save the original sys.excepthook in the instance, in case config
2827 # we save the original sys.excepthook in the instance, in case config
2829 # code (such as magics) needs access to it.
2828 # code (such as magics) needs access to it.
2830 self.sys_excepthook = old_excepthook
2829 self.sys_excepthook = old_excepthook
2831 outflag = 1 # happens in more places, so it's easier as default
2830 outflag = 1 # happens in more places, so it's easier as default
2832 try:
2831 try:
2833 try:
2832 try:
2834 self.hooks.pre_run_code_hook()
2833 self.hooks.pre_run_code_hook()
2835 #rprint('Running code', repr(code_obj)) # dbg
2834 #rprint('Running code', repr(code_obj)) # dbg
2836 exec code_obj in self.user_global_ns, self.user_ns
2835 exec code_obj in self.user_global_ns, self.user_ns
2837 finally:
2836 finally:
2838 # Reset our crash handler in place
2837 # Reset our crash handler in place
2839 sys.excepthook = old_excepthook
2838 sys.excepthook = old_excepthook
2840 except SystemExit:
2839 except SystemExit:
2841 self.showtraceback(exception_only=True)
2840 self.showtraceback(exception_only=True)
2842 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2841 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2843 except self.custom_exceptions:
2842 except self.custom_exceptions:
2844 etype,value,tb = sys.exc_info()
2843 etype,value,tb = sys.exc_info()
2845 self.CustomTB(etype,value,tb)
2844 self.CustomTB(etype,value,tb)
2846 except:
2845 except:
2847 self.showtraceback()
2846 self.showtraceback()
2848 else:
2847 else:
2849 outflag = 0
2848 outflag = 0
2850 return outflag
2849 return outflag
2851
2850
2852 # For backwards compatibility
2851 # For backwards compatibility
2853 runcode = run_code
2852 runcode = run_code
2854
2853
2855 #-------------------------------------------------------------------------
2854 #-------------------------------------------------------------------------
2856 # Things related to GUI support and pylab
2855 # Things related to GUI support and pylab
2857 #-------------------------------------------------------------------------
2856 #-------------------------------------------------------------------------
2858
2857
2859 def enable_gui(self, gui=None):
2858 def enable_gui(self, gui=None):
2860 raise NotImplementedError('Implement enable_gui in a subclass')
2859 raise NotImplementedError('Implement enable_gui in a subclass')
2861
2860
2862 def enable_matplotlib(self, gui=None):
2861 def enable_matplotlib(self, gui=None):
2863 """Enable interactive matplotlib and inline figure support.
2862 """Enable interactive matplotlib and inline figure support.
2864
2863
2865 This takes the following steps:
2864 This takes the following steps:
2866
2865
2867 1. select the appropriate eventloop and matplotlib backend
2866 1. select the appropriate eventloop and matplotlib backend
2868 2. set up matplotlib for interactive use with that backend
2867 2. set up matplotlib for interactive use with that backend
2869 3. configure formatters for inline figure display
2868 3. configure formatters for inline figure display
2870 4. enable the selected gui eventloop
2869 4. enable the selected gui eventloop
2871
2870
2872 Parameters
2871 Parameters
2873 ----------
2872 ----------
2874 gui : optional, string
2873 gui : optional, string
2875 If given, dictates the choice of matplotlib GUI backend to use
2874 If given, dictates the choice of matplotlib GUI backend to use
2876 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2875 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2877 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2876 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2878 matplotlib (as dictated by the matplotlib build-time options plus the
2877 matplotlib (as dictated by the matplotlib build-time options plus the
2879 user's matplotlibrc configuration file). Note that not all backends
2878 user's matplotlibrc configuration file). Note that not all backends
2880 make sense in all contexts, for example a terminal ipython can't
2879 make sense in all contexts, for example a terminal ipython can't
2881 display figures inline.
2880 display figures inline.
2882 """
2881 """
2883 from IPython.core import pylabtools as pt
2882 from IPython.core import pylabtools as pt
2884 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2883 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2885
2884
2886 if gui != 'inline':
2885 if gui != 'inline':
2887 # If we have our first gui selection, store it
2886 # If we have our first gui selection, store it
2888 if self.pylab_gui_select is None:
2887 if self.pylab_gui_select is None:
2889 self.pylab_gui_select = gui
2888 self.pylab_gui_select = gui
2890 # Otherwise if they are different
2889 # Otherwise if they are different
2891 elif gui != self.pylab_gui_select:
2890 elif gui != self.pylab_gui_select:
2892 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2891 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2893 ' Using %s instead.' % (gui, self.pylab_gui_select))
2892 ' Using %s instead.' % (gui, self.pylab_gui_select))
2894 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2893 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2895
2894
2896 pt.activate_matplotlib(backend)
2895 pt.activate_matplotlib(backend)
2897 pt.configure_inline_support(self, backend)
2896 pt.configure_inline_support(self, backend)
2898
2897
2899 # Now we must activate the gui pylab wants to use, and fix %run to take
2898 # Now we must activate the gui pylab wants to use, and fix %run to take
2900 # plot updates into account
2899 # plot updates into account
2901 self.enable_gui(gui)
2900 self.enable_gui(gui)
2902 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2901 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2903 pt.mpl_runner(self.safe_execfile)
2902 pt.mpl_runner(self.safe_execfile)
2904
2903
2905 return gui, backend
2904 return gui, backend
2906
2905
2907 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2906 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2908 """Activate pylab support at runtime.
2907 """Activate pylab support at runtime.
2909
2908
2910 This turns on support for matplotlib, preloads into the interactive
2909 This turns on support for matplotlib, preloads into the interactive
2911 namespace all of numpy and pylab, and configures IPython to correctly
2910 namespace all of numpy and pylab, and configures IPython to correctly
2912 interact with the GUI event loop. The GUI backend to be used can be
2911 interact with the GUI event loop. The GUI backend to be used can be
2913 optionally selected with the optional ``gui`` argument.
2912 optionally selected with the optional ``gui`` argument.
2914
2913
2915 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2914 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2916
2915
2917 Parameters
2916 Parameters
2918 ----------
2917 ----------
2919 gui : optional, string
2918 gui : optional, string
2920 If given, dictates the choice of matplotlib GUI backend to use
2919 If given, dictates the choice of matplotlib GUI backend to use
2921 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2920 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2922 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2921 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2923 matplotlib (as dictated by the matplotlib build-time options plus the
2922 matplotlib (as dictated by the matplotlib build-time options plus the
2924 user's matplotlibrc configuration file). Note that not all backends
2923 user's matplotlibrc configuration file). Note that not all backends
2925 make sense in all contexts, for example a terminal ipython can't
2924 make sense in all contexts, for example a terminal ipython can't
2926 display figures inline.
2925 display figures inline.
2927 import_all : optional, bool, default: True
2926 import_all : optional, bool, default: True
2928 Whether to do `from numpy import *` and `from pylab import *`
2927 Whether to do `from numpy import *` and `from pylab import *`
2929 in addition to module imports.
2928 in addition to module imports.
2930 welcome_message : deprecated
2929 welcome_message : deprecated
2931 This argument is ignored, no welcome message will be displayed.
2930 This argument is ignored, no welcome message will be displayed.
2932 """
2931 """
2933 from IPython.core.pylabtools import import_pylab
2932 from IPython.core.pylabtools import import_pylab
2934
2933
2935 gui, backend = self.enable_matplotlib(gui)
2934 gui, backend = self.enable_matplotlib(gui)
2936
2935
2937 # We want to prevent the loading of pylab to pollute the user's
2936 # We want to prevent the loading of pylab to pollute the user's
2938 # namespace as shown by the %who* magics, so we execute the activation
2937 # namespace as shown by the %who* magics, so we execute the activation
2939 # code in an empty namespace, and we update *both* user_ns and
2938 # code in an empty namespace, and we update *both* user_ns and
2940 # user_ns_hidden with this information.
2939 # user_ns_hidden with this information.
2941 ns = {}
2940 ns = {}
2942 import_pylab(ns, import_all)
2941 import_pylab(ns, import_all)
2943 # warn about clobbered names
2942 # warn about clobbered names
2944 ignored = set(["__builtins__"])
2943 ignored = set(["__builtins__"])
2945 both = set(ns).intersection(self.user_ns).difference(ignored)
2944 both = set(ns).intersection(self.user_ns).difference(ignored)
2946 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2945 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2947 self.user_ns.update(ns)
2946 self.user_ns.update(ns)
2948 self.user_ns_hidden.update(ns)
2947 self.user_ns_hidden.update(ns)
2949 return gui, backend, clobbered
2948 return gui, backend, clobbered
2950
2949
2951 #-------------------------------------------------------------------------
2950 #-------------------------------------------------------------------------
2952 # Utilities
2951 # Utilities
2953 #-------------------------------------------------------------------------
2952 #-------------------------------------------------------------------------
2954
2953
2955 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2954 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2956 """Expand python variables in a string.
2955 """Expand python variables in a string.
2957
2956
2958 The depth argument indicates how many frames above the caller should
2957 The depth argument indicates how many frames above the caller should
2959 be walked to look for the local namespace where to expand variables.
2958 be walked to look for the local namespace where to expand variables.
2960
2959
2961 The global namespace for expansion is always the user's interactive
2960 The global namespace for expansion is always the user's interactive
2962 namespace.
2961 namespace.
2963 """
2962 """
2964 ns = self.user_ns.copy()
2963 ns = self.user_ns.copy()
2965 ns.update(sys._getframe(depth+1).f_locals)
2964 ns.update(sys._getframe(depth+1).f_locals)
2966 try:
2965 try:
2967 # We have to use .vformat() here, because 'self' is a valid and common
2966 # We have to use .vformat() here, because 'self' is a valid and common
2968 # name, and expanding **ns for .format() would make it collide with
2967 # name, and expanding **ns for .format() would make it collide with
2969 # the 'self' argument of the method.
2968 # the 'self' argument of the method.
2970 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2969 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2971 except Exception:
2970 except Exception:
2972 # if formatter couldn't format, just let it go untransformed
2971 # if formatter couldn't format, just let it go untransformed
2973 pass
2972 pass
2974 return cmd
2973 return cmd
2975
2974
2976 def mktempfile(self, data=None, prefix='ipython_edit_'):
2975 def mktempfile(self, data=None, prefix='ipython_edit_'):
2977 """Make a new tempfile and return its filename.
2976 """Make a new tempfile and return its filename.
2978
2977
2979 This makes a call to tempfile.mktemp, but it registers the created
2978 This makes a call to tempfile.mktemp, but it registers the created
2980 filename internally so ipython cleans it up at exit time.
2979 filename internally so ipython cleans it up at exit time.
2981
2980
2982 Optional inputs:
2981 Optional inputs:
2983
2982
2984 - data(None): if data is given, it gets written out to the temp file
2983 - data(None): if data is given, it gets written out to the temp file
2985 immediately, and the file is closed again."""
2984 immediately, and the file is closed again."""
2986
2985
2987 filename = tempfile.mktemp('.py', prefix)
2986 filename = tempfile.mktemp('.py', prefix)
2988 self.tempfiles.append(filename)
2987 self.tempfiles.append(filename)
2989
2988
2990 if data:
2989 if data:
2991 tmp_file = open(filename,'w')
2990 tmp_file = open(filename,'w')
2992 tmp_file.write(data)
2991 tmp_file.write(data)
2993 tmp_file.close()
2992 tmp_file.close()
2994 return filename
2993 return filename
2995
2994
2996 # TODO: This should be removed when Term is refactored.
2995 # TODO: This should be removed when Term is refactored.
2997 def write(self,data):
2996 def write(self,data):
2998 """Write a string to the default output"""
2997 """Write a string to the default output"""
2999 io.stdout.write(data)
2998 io.stdout.write(data)
3000
2999
3001 # TODO: This should be removed when Term is refactored.
3000 # TODO: This should be removed when Term is refactored.
3002 def write_err(self,data):
3001 def write_err(self,data):
3003 """Write a string to the default error output"""
3002 """Write a string to the default error output"""
3004 io.stderr.write(data)
3003 io.stderr.write(data)
3005
3004
3006 def ask_yes_no(self, prompt, default=None):
3005 def ask_yes_no(self, prompt, default=None):
3007 if self.quiet:
3006 if self.quiet:
3008 return True
3007 return True
3009 return ask_yes_no(prompt,default)
3008 return ask_yes_no(prompt,default)
3010
3009
3011 def show_usage(self):
3010 def show_usage(self):
3012 """Show a usage message"""
3011 """Show a usage message"""
3013 page.page(IPython.core.usage.interactive_usage)
3012 page.page(IPython.core.usage.interactive_usage)
3014
3013
3015 def extract_input_lines(self, range_str, raw=False):
3014 def extract_input_lines(self, range_str, raw=False):
3016 """Return as a string a set of input history slices.
3015 """Return as a string a set of input history slices.
3017
3016
3018 Parameters
3017 Parameters
3019 ----------
3018 ----------
3020 range_str : string
3019 range_str : string
3021 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3020 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3022 since this function is for use by magic functions which get their
3021 since this function is for use by magic functions which get their
3023 arguments as strings. The number before the / is the session
3022 arguments as strings. The number before the / is the session
3024 number: ~n goes n back from the current session.
3023 number: ~n goes n back from the current session.
3025
3024
3026 Optional Parameters:
3025 Optional Parameters:
3027 - raw(False): by default, the processed input is used. If this is
3026 - raw(False): by default, the processed input is used. If this is
3028 true, the raw input history is used instead.
3027 true, the raw input history is used instead.
3029
3028
3030 Note that slices can be called with two notations:
3029 Note that slices can be called with two notations:
3031
3030
3032 N:M -> standard python form, means including items N...(M-1).
3031 N:M -> standard python form, means including items N...(M-1).
3033
3032
3034 N-M -> include items N..M (closed endpoint).
3033 N-M -> include items N..M (closed endpoint).
3035 """
3034 """
3036 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3035 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3037 return "\n".join(x for _, _, x in lines)
3036 return "\n".join(x for _, _, x in lines)
3038
3037
3039 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
3038 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
3040 """Get a code string from history, file, url, or a string or macro.
3039 """Get a code string from history, file, url, or a string or macro.
3041
3040
3042 This is mainly used by magic functions.
3041 This is mainly used by magic functions.
3043
3042
3044 Parameters
3043 Parameters
3045 ----------
3044 ----------
3046
3045
3047 target : str
3046 target : str
3048
3047
3049 A string specifying code to retrieve. This will be tried respectively
3048 A string specifying code to retrieve. This will be tried respectively
3050 as: ranges of input history (see %history for syntax), url,
3049 as: ranges of input history (see %history for syntax), url,
3051 correspnding .py file, filename, or an expression evaluating to a
3050 correspnding .py file, filename, or an expression evaluating to a
3052 string or Macro in the user namespace.
3051 string or Macro in the user namespace.
3053
3052
3054 raw : bool
3053 raw : bool
3055 If true (default), retrieve raw history. Has no effect on the other
3054 If true (default), retrieve raw history. Has no effect on the other
3056 retrieval mechanisms.
3055 retrieval mechanisms.
3057
3056
3058 py_only : bool (default False)
3057 py_only : bool (default False)
3059 Only try to fetch python code, do not try alternative methods to decode file
3058 Only try to fetch python code, do not try alternative methods to decode file
3060 if unicode fails.
3059 if unicode fails.
3061
3060
3062 Returns
3061 Returns
3063 -------
3062 -------
3064 A string of code.
3063 A string of code.
3065
3064
3066 ValueError is raised if nothing is found, and TypeError if it evaluates
3065 ValueError is raised if nothing is found, and TypeError if it evaluates
3067 to an object of another type. In each case, .args[0] is a printable
3066 to an object of another type. In each case, .args[0] is a printable
3068 message.
3067 message.
3069 """
3068 """
3070 code = self.extract_input_lines(target, raw=raw) # Grab history
3069 code = self.extract_input_lines(target, raw=raw) # Grab history
3071 if code:
3070 if code:
3072 return code
3071 return code
3073 utarget = unquote_filename(target)
3072 utarget = unquote_filename(target)
3074 try:
3073 try:
3075 if utarget.startswith(('http://', 'https://')):
3074 if utarget.startswith(('http://', 'https://')):
3076 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3075 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3077 except UnicodeDecodeError:
3076 except UnicodeDecodeError:
3078 if not py_only :
3077 if not py_only :
3079 from urllib import urlopen # Deferred import
3078 from urllib import urlopen # Deferred import
3080 response = urlopen(target)
3079 response = urlopen(target)
3081 return response.read().decode('latin1')
3080 return response.read().decode('latin1')
3082 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3081 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3083
3082
3084 potential_target = [target]
3083 potential_target = [target]
3085 try :
3084 try :
3086 potential_target.insert(0,get_py_filename(target))
3085 potential_target.insert(0,get_py_filename(target))
3087 except IOError:
3086 except IOError:
3088 pass
3087 pass
3089
3088
3090 for tgt in potential_target :
3089 for tgt in potential_target :
3091 if os.path.isfile(tgt): # Read file
3090 if os.path.isfile(tgt): # Read file
3092 try :
3091 try :
3093 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3092 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3094 except UnicodeDecodeError :
3093 except UnicodeDecodeError :
3095 if not py_only :
3094 if not py_only :
3096 with io_open(tgt,'r', encoding='latin1') as f :
3095 with io_open(tgt,'r', encoding='latin1') as f :
3097 return f.read()
3096 return f.read()
3098 raise ValueError(("'%s' seem to be unreadable.") % target)
3097 raise ValueError(("'%s' seem to be unreadable.") % target)
3099 elif os.path.isdir(os.path.expanduser(tgt)):
3098 elif os.path.isdir(os.path.expanduser(tgt)):
3100 raise ValueError("'%s' is a directory, not a regular file." % target)
3099 raise ValueError("'%s' is a directory, not a regular file." % target)
3101
3100
3102 try: # User namespace
3101 try: # User namespace
3103 codeobj = eval(target, self.user_ns)
3102 codeobj = eval(target, self.user_ns)
3104 except Exception:
3103 except Exception:
3105 raise ValueError(("'%s' was not found in history, as a file, url, "
3104 raise ValueError(("'%s' was not found in history, as a file, url, "
3106 "nor in the user namespace.") % target)
3105 "nor in the user namespace.") % target)
3107 if isinstance(codeobj, basestring):
3106 if isinstance(codeobj, basestring):
3108 return codeobj
3107 return codeobj
3109 elif isinstance(codeobj, Macro):
3108 elif isinstance(codeobj, Macro):
3110 return codeobj.value
3109 return codeobj.value
3111
3110
3112 raise TypeError("%s is neither a string nor a macro." % target,
3111 raise TypeError("%s is neither a string nor a macro." % target,
3113 codeobj)
3112 codeobj)
3114
3113
3115 #-------------------------------------------------------------------------
3114 #-------------------------------------------------------------------------
3116 # Things related to IPython exiting
3115 # Things related to IPython exiting
3117 #-------------------------------------------------------------------------
3116 #-------------------------------------------------------------------------
3118 def atexit_operations(self):
3117 def atexit_operations(self):
3119 """This will be executed at the time of exit.
3118 """This will be executed at the time of exit.
3120
3119
3121 Cleanup operations and saving of persistent data that is done
3120 Cleanup operations and saving of persistent data that is done
3122 unconditionally by IPython should be performed here.
3121 unconditionally by IPython should be performed here.
3123
3122
3124 For things that may depend on startup flags or platform specifics (such
3123 For things that may depend on startup flags or platform specifics (such
3125 as having readline or not), register a separate atexit function in the
3124 as having readline or not), register a separate atexit function in the
3126 code that has the appropriate information, rather than trying to
3125 code that has the appropriate information, rather than trying to
3127 clutter
3126 clutter
3128 """
3127 """
3129 # Close the history session (this stores the end time and line count)
3128 # Close the history session (this stores the end time and line count)
3130 # this must be *before* the tempfile cleanup, in case of temporary
3129 # this must be *before* the tempfile cleanup, in case of temporary
3131 # history db
3130 # history db
3132 self.history_manager.end_session()
3131 self.history_manager.end_session()
3133
3132
3134 # Cleanup all tempfiles left around
3133 # Cleanup all tempfiles left around
3135 for tfile in self.tempfiles:
3134 for tfile in self.tempfiles:
3136 try:
3135 try:
3137 os.unlink(tfile)
3136 os.unlink(tfile)
3138 except OSError:
3137 except OSError:
3139 pass
3138 pass
3140
3139
3141 # Clear all user namespaces to release all references cleanly.
3140 # Clear all user namespaces to release all references cleanly.
3142 self.reset(new_session=False)
3141 self.reset(new_session=False)
3143
3142
3144 # Run user hooks
3143 # Run user hooks
3145 self.hooks.shutdown_hook()
3144 self.hooks.shutdown_hook()
3146
3145
3147 def cleanup(self):
3146 def cleanup(self):
3148 self.restore_sys_module_state()
3147 self.restore_sys_module_state()
3149
3148
3150
3149
3151 class InteractiveShellABC(object):
3150 class InteractiveShellABC(object):
3152 """An abstract base class for InteractiveShell."""
3151 """An abstract base class for InteractiveShell."""
3153 __metaclass__ = abc.ABCMeta
3152 __metaclass__ = abc.ABCMeta
3154
3153
3155 InteractiveShellABC.register(InteractiveShell)
3154 InteractiveShellABC.register(InteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now