##// END OF EJS Templates
Remove Pydb integration as Pydb is unmaintained and not ion PyPI...
Matthias Bussonnier -
Show More
@@ -0,0 +1,1 b''
1 Integration with pydb has been removed since pydb development has been stopped since 2012, and pydb is not installable from PyPI
@@ -1,1325 +1,1324 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Word completion for IPython.
2 """Word completion for IPython.
3
3
4 This module is a fork of the rlcompleter module in the Python standard
4 This module is a fork of the rlcompleter module in the Python standard
5 library. The original enhancements made to rlcompleter have been sent
5 library. The original enhancements made to rlcompleter have been sent
6 upstream and were accepted as of Python 2.3, but we need a lot more
6 upstream and were accepted as of Python 2.3, but we need a lot more
7 functionality specific to IPython, so this module will continue to live as an
7 functionality specific to IPython, so this module will continue to live as an
8 IPython-specific utility.
8 IPython-specific utility.
9
9
10 Original rlcompleter documentation:
10 Original rlcompleter documentation:
11
11
12 This requires the latest extension to the readline module (the
12 This requires the latest extension to the readline module (the
13 completes keywords, built-ins and globals in __main__; when completing
13 completes keywords, built-ins and globals in __main__; when completing
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 completes its attributes.
15 completes its attributes.
16
16
17 It's very cool to do "import string" type "string.", hit the
17 It's very cool to do "import string" type "string.", hit the
18 completion key (twice), and see the list of names defined by the
18 completion key (twice), and see the list of names defined by the
19 string module!
19 string module!
20
20
21 Tip: to use the tab key as the completion key, call
21 Tip: to use the tab key as the completion key, call
22
22
23 readline.parse_and_bind("tab: complete")
23 readline.parse_and_bind("tab: complete")
24
24
25 Notes:
25 Notes:
26
26
27 - Exceptions raised by the completer function are *ignored* (and
27 - Exceptions raised by the completer function are *ignored* (and
28 generally cause the completion to fail). This is a feature -- since
28 generally cause the completion to fail). This is a feature -- since
29 readline sets the tty device in raw (or cbreak) mode, printing a
29 readline sets the tty device in raw (or cbreak) mode, printing a
30 traceback wouldn't work well without some complicated hoopla to save,
30 traceback wouldn't work well without some complicated hoopla to save,
31 reset and restore the tty state.
31 reset and restore the tty state.
32
32
33 - The evaluation of the NAME.NAME... form may cause arbitrary
33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 application defined code to be executed if an object with a
34 application defined code to be executed if an object with a
35 ``__getattr__`` hook is found. Since it is the responsibility of the
35 ``__getattr__`` hook is found. Since it is the responsibility of the
36 application (or the user) to enable this feature, I consider this an
36 application (or the user) to enable this feature, I consider this an
37 acceptable risk. More complicated expressions (e.g. function calls or
37 acceptable risk. More complicated expressions (e.g. function calls or
38 indexing operations) are *not* evaluated.
38 indexing operations) are *not* evaluated.
39
39
40 - GNU readline is also used by the built-in functions input() and
40 - GNU readline is also used by the built-in functions input() and
41 raw_input(), and thus these also benefit/suffer from the completer
41 raw_input(), and thus these also benefit/suffer from the completer
42 features. Clearly an interactive application can benefit by
42 features. Clearly an interactive application can benefit by
43 specifying its own completer function and using raw_input() for all
43 specifying its own completer function and using raw_input() for all
44 its input.
44 its input.
45
45
46 - When the original stdin is not a tty device, GNU readline is never
46 - When the original stdin is not a tty device, GNU readline is never
47 used, and this module (and the readline module) are silently inactive.
47 used, and this module (and the readline module) are silently inactive.
48 """
48 """
49
49
50 # Copyright (c) IPython Development Team.
50 # Copyright (c) IPython Development Team.
51 # Distributed under the terms of the Modified BSD License.
51 # Distributed under the terms of the Modified BSD License.
52 #
52 #
53 # Some of this code originated from rlcompleter in the Python standard library
53 # Some of this code originated from rlcompleter in the Python standard library
54 # Copyright (C) 2001 Python Software Foundation, www.python.org
54 # Copyright (C) 2001 Python Software Foundation, www.python.org
55
55
56 from __future__ import print_function
56 from __future__ import print_function
57
57
58 import __main__
58 import __main__
59 import glob
59 import glob
60 import inspect
60 import inspect
61 import itertools
61 import itertools
62 import keyword
62 import keyword
63 import os
63 import os
64 import re
64 import re
65 import sys
65 import sys
66 import unicodedata
66 import unicodedata
67 import string
67 import string
68
68
69 from traitlets.config.configurable import Configurable
69 from traitlets.config.configurable import Configurable
70 from IPython.core.error import TryNext
70 from IPython.core.error import TryNext
71 from IPython.core.inputsplitter import ESC_MAGIC
71 from IPython.core.inputsplitter import ESC_MAGIC
72 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
72 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
73 from IPython.utils import generics
73 from IPython.utils import generics
74 from IPython.utils.decorators import undoc
74 from IPython.utils.decorators import undoc
75 from IPython.utils.dir2 import dir2, get_real_method
75 from IPython.utils.dir2 import dir2, get_real_method
76 from IPython.utils.process import arg_split
76 from IPython.utils.process import arg_split
77 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
77 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
78 from traitlets import Bool, Enum, observe
78 from traitlets import Bool, Enum, observe
79
79
80 import jedi
80 import jedi
81 import jedi.api.helpers
81 import jedi.api.helpers
82 import jedi.parser.user_context
82 import jedi.parser.user_context
83
83
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85 # Globals
85 # Globals
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87
87
88 # Public API
88 # Public API
89 __all__ = ['Completer','IPCompleter']
89 __all__ = ['Completer','IPCompleter']
90
90
91 if sys.platform == 'win32':
91 if sys.platform == 'win32':
92 PROTECTABLES = ' '
92 PROTECTABLES = ' '
93 else:
93 else:
94 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
94 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
95
95
96
96
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98 # Main functions and classes
98 # Main functions and classes
99 #-----------------------------------------------------------------------------
99 #-----------------------------------------------------------------------------
100
100
101 def has_open_quotes(s):
101 def has_open_quotes(s):
102 """Return whether a string has open quotes.
102 """Return whether a string has open quotes.
103
103
104 This simply counts whether the number of quote characters of either type in
104 This simply counts whether the number of quote characters of either type in
105 the string is odd.
105 the string is odd.
106
106
107 Returns
107 Returns
108 -------
108 -------
109 If there is an open quote, the quote character is returned. Else, return
109 If there is an open quote, the quote character is returned. Else, return
110 False.
110 False.
111 """
111 """
112 # We check " first, then ', so complex cases with nested quotes will get
112 # We check " first, then ', so complex cases with nested quotes will get
113 # the " to take precedence.
113 # the " to take precedence.
114 if s.count('"') % 2:
114 if s.count('"') % 2:
115 return '"'
115 return '"'
116 elif s.count("'") % 2:
116 elif s.count("'") % 2:
117 return "'"
117 return "'"
118 else:
118 else:
119 return False
119 return False
120
120
121
121
122 def protect_filename(s):
122 def protect_filename(s):
123 """Escape a string to protect certain characters."""
123 """Escape a string to protect certain characters."""
124
124
125 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
125 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
126 for ch in s])
126 for ch in s])
127
127
128 def expand_user(path):
128 def expand_user(path):
129 """Expand '~'-style usernames in strings.
129 """Expand '~'-style usernames in strings.
130
130
131 This is similar to :func:`os.path.expanduser`, but it computes and returns
131 This is similar to :func:`os.path.expanduser`, but it computes and returns
132 extra information that will be useful if the input was being used in
132 extra information that will be useful if the input was being used in
133 computing completions, and you wish to return the completions with the
133 computing completions, and you wish to return the completions with the
134 original '~' instead of its expanded value.
134 original '~' instead of its expanded value.
135
135
136 Parameters
136 Parameters
137 ----------
137 ----------
138 path : str
138 path : str
139 String to be expanded. If no ~ is present, the output is the same as the
139 String to be expanded. If no ~ is present, the output is the same as the
140 input.
140 input.
141
141
142 Returns
142 Returns
143 -------
143 -------
144 newpath : str
144 newpath : str
145 Result of ~ expansion in the input path.
145 Result of ~ expansion in the input path.
146 tilde_expand : bool
146 tilde_expand : bool
147 Whether any expansion was performed or not.
147 Whether any expansion was performed or not.
148 tilde_val : str
148 tilde_val : str
149 The value that ~ was replaced with.
149 The value that ~ was replaced with.
150 """
150 """
151 # Default values
151 # Default values
152 tilde_expand = False
152 tilde_expand = False
153 tilde_val = ''
153 tilde_val = ''
154 newpath = path
154 newpath = path
155
155
156 if path.startswith('~'):
156 if path.startswith('~'):
157 tilde_expand = True
157 tilde_expand = True
158 rest = len(path)-1
158 rest = len(path)-1
159 newpath = os.path.expanduser(path)
159 newpath = os.path.expanduser(path)
160 if rest:
160 if rest:
161 tilde_val = newpath[:-rest]
161 tilde_val = newpath[:-rest]
162 else:
162 else:
163 tilde_val = newpath
163 tilde_val = newpath
164
164
165 return newpath, tilde_expand, tilde_val
165 return newpath, tilde_expand, tilde_val
166
166
167
167
168 def compress_user(path, tilde_expand, tilde_val):
168 def compress_user(path, tilde_expand, tilde_val):
169 """Does the opposite of expand_user, with its outputs.
169 """Does the opposite of expand_user, with its outputs.
170 """
170 """
171 if tilde_expand:
171 if tilde_expand:
172 return path.replace(tilde_val, '~')
172 return path.replace(tilde_val, '~')
173 else:
173 else:
174 return path
174 return path
175
175
176
176
177 def completions_sorting_key(word):
177 def completions_sorting_key(word):
178 """key for sorting completions
178 """key for sorting completions
179
179
180 This does several things:
180 This does several things:
181
181
182 - Lowercase all completions, so they are sorted alphabetically with
182 - Lowercase all completions, so they are sorted alphabetically with
183 upper and lower case words mingled
183 upper and lower case words mingled
184 - Demote any completions starting with underscores to the end
184 - Demote any completions starting with underscores to the end
185 - Insert any %magic and %%cellmagic completions in the alphabetical order
185 - Insert any %magic and %%cellmagic completions in the alphabetical order
186 by their name
186 by their name
187 """
187 """
188 # Case insensitive sort
188 # Case insensitive sort
189 word = word.lower()
189 word = word.lower()
190
190
191 prio1, prio2 = 0, 0
191 prio1, prio2 = 0, 0
192
192
193 if word.startswith('__'):
193 if word.startswith('__'):
194 prio1 = 2
194 prio1 = 2
195 elif word.startswith('_'):
195 elif word.startswith('_'):
196 prio1 = 1
196 prio1 = 1
197
197
198 if word.endswith('='):
198 if word.endswith('='):
199 prio1 = -1
199 prio1 = -1
200
200
201 if word.startswith('%%'):
201 if word.startswith('%%'):
202 # If there's another % in there, this is something else, so leave it alone
202 # If there's another % in there, this is something else, so leave it alone
203 if not "%" in word[2:]:
203 if not "%" in word[2:]:
204 word = word[2:]
204 word = word[2:]
205 prio2 = 2
205 prio2 = 2
206 elif word.startswith('%'):
206 elif word.startswith('%'):
207 if not "%" in word[1:]:
207 if not "%" in word[1:]:
208 word = word[1:]
208 word = word[1:]
209 prio2 = 1
209 prio2 = 1
210
210
211 return prio1, word, prio2
211 return prio1, word, prio2
212
212
213
213
214 @undoc
214 @undoc
215 class Bunch(object): pass
215 class Bunch(object): pass
216
216
217
217
218 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
218 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
219 GREEDY_DELIMS = ' =\r\n'
219 GREEDY_DELIMS = ' =\r\n'
220
220
221
221
222 class CompletionSplitter(object):
222 class CompletionSplitter(object):
223 """An object to split an input line in a manner similar to readline.
223 """An object to split an input line in a manner similar to readline.
224
224
225 By having our own implementation, we can expose readline-like completion in
225 By having our own implementation, we can expose readline-like completion in
226 a uniform manner to all frontends. This object only needs to be given the
226 a uniform manner to all frontends. This object only needs to be given the
227 line of text to be split and the cursor position on said line, and it
227 line of text to be split and the cursor position on said line, and it
228 returns the 'word' to be completed on at the cursor after splitting the
228 returns the 'word' to be completed on at the cursor after splitting the
229 entire line.
229 entire line.
230
230
231 What characters are used as splitting delimiters can be controlled by
231 What characters are used as splitting delimiters can be controlled by
232 setting the `delims` attribute (this is a property that internally
232 setting the `delims` attribute (this is a property that internally
233 automatically builds the necessary regular expression)"""
233 automatically builds the necessary regular expression)"""
234
234
235 # Private interface
235 # Private interface
236
236
237 # A string of delimiter characters. The default value makes sense for
237 # A string of delimiter characters. The default value makes sense for
238 # IPython's most typical usage patterns.
238 # IPython's most typical usage patterns.
239 _delims = DELIMS
239 _delims = DELIMS
240
240
241 # The expression (a normal string) to be compiled into a regular expression
241 # The expression (a normal string) to be compiled into a regular expression
242 # for actual splitting. We store it as an attribute mostly for ease of
242 # for actual splitting. We store it as an attribute mostly for ease of
243 # debugging, since this type of code can be so tricky to debug.
243 # debugging, since this type of code can be so tricky to debug.
244 _delim_expr = None
244 _delim_expr = None
245
245
246 # The regular expression that does the actual splitting
246 # The regular expression that does the actual splitting
247 _delim_re = None
247 _delim_re = None
248
248
249 def __init__(self, delims=None):
249 def __init__(self, delims=None):
250 delims = CompletionSplitter._delims if delims is None else delims
250 delims = CompletionSplitter._delims if delims is None else delims
251 self.delims = delims
251 self.delims = delims
252
252
253 @property
253 @property
254 def delims(self):
254 def delims(self):
255 """Return the string of delimiter characters."""
255 """Return the string of delimiter characters."""
256 return self._delims
256 return self._delims
257
257
258 @delims.setter
258 @delims.setter
259 def delims(self, delims):
259 def delims(self, delims):
260 """Set the delimiters for line splitting."""
260 """Set the delimiters for line splitting."""
261 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
261 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
262 self._delim_re = re.compile(expr)
262 self._delim_re = re.compile(expr)
263 self._delims = delims
263 self._delims = delims
264 self._delim_expr = expr
264 self._delim_expr = expr
265
265
266 def split_line(self, line, cursor_pos=None):
266 def split_line(self, line, cursor_pos=None):
267 """Split a line of text with a cursor at the given position.
267 """Split a line of text with a cursor at the given position.
268 """
268 """
269 l = line if cursor_pos is None else line[:cursor_pos]
269 l = line if cursor_pos is None else line[:cursor_pos]
270 return self._delim_re.split(l)[-1]
270 return self._delim_re.split(l)[-1]
271
271
272
272
273 class Completer(Configurable):
273 class Completer(Configurable):
274
274
275 greedy = Bool(False,
275 greedy = Bool(False,
276 help="""Activate greedy completion
276 help="""Activate greedy completion
277 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
277 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
278
278
279 This will enable completion on elements of lists, results of function calls, etc.,
279 This will enable completion on elements of lists, results of function calls, etc.,
280 but can be unsafe because the code is actually evaluated on TAB.
280 but can be unsafe because the code is actually evaluated on TAB.
281 """
281 """
282 ).tag(config=True)
282 ).tag(config=True)
283
283
284
284
285 def __init__(self, namespace=None, global_namespace=None, **kwargs):
285 def __init__(self, namespace=None, global_namespace=None, **kwargs):
286 """Create a new completer for the command line.
286 """Create a new completer for the command line.
287
287
288 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
288 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
289
289
290 If unspecified, the default namespace where completions are performed
290 If unspecified, the default namespace where completions are performed
291 is __main__ (technically, __main__.__dict__). Namespaces should be
291 is __main__ (technically, __main__.__dict__). Namespaces should be
292 given as dictionaries.
292 given as dictionaries.
293
293
294 An optional second namespace can be given. This allows the completer
294 An optional second namespace can be given. This allows the completer
295 to handle cases where both the local and global scopes need to be
295 to handle cases where both the local and global scopes need to be
296 distinguished.
296 distinguished.
297
297
298 Completer instances should be used as the completion mechanism of
298 Completer instances should be used as the completion mechanism of
299 readline via the set_completer() call:
299 readline via the set_completer() call:
300
300
301 readline.set_completer(Completer(my_namespace).complete)
301 readline.set_completer(Completer(my_namespace).complete)
302 """
302 """
303
303
304 # Don't bind to namespace quite yet, but flag whether the user wants a
304 # Don't bind to namespace quite yet, but flag whether the user wants a
305 # specific namespace or to use __main__.__dict__. This will allow us
305 # specific namespace or to use __main__.__dict__. This will allow us
306 # to bind to __main__.__dict__ at completion time, not now.
306 # to bind to __main__.__dict__ at completion time, not now.
307 if namespace is None:
307 if namespace is None:
308 self.use_main_ns = 1
308 self.use_main_ns = 1
309 else:
309 else:
310 self.use_main_ns = 0
310 self.use_main_ns = 0
311 self.namespace = namespace
311 self.namespace = namespace
312
312
313 # The global namespace, if given, can be bound directly
313 # The global namespace, if given, can be bound directly
314 if global_namespace is None:
314 if global_namespace is None:
315 self.global_namespace = {}
315 self.global_namespace = {}
316 else:
316 else:
317 self.global_namespace = global_namespace
317 self.global_namespace = global_namespace
318
318
319 super(Completer, self).__init__(**kwargs)
319 super(Completer, self).__init__(**kwargs)
320
320
321 def complete(self, text, state):
321 def complete(self, text, state):
322 """Return the next possible completion for 'text'.
322 """Return the next possible completion for 'text'.
323
323
324 This is called successively with state == 0, 1, 2, ... until it
324 This is called successively with state == 0, 1, 2, ... until it
325 returns None. The completion should begin with 'text'.
325 returns None. The completion should begin with 'text'.
326
326
327 """
327 """
328 if self.use_main_ns:
328 if self.use_main_ns:
329 self.namespace = __main__.__dict__
329 self.namespace = __main__.__dict__
330
330
331 if state == 0:
331 if state == 0:
332 if "." in text:
332 if "." in text:
333 self.matches = self.attr_matches(text)
333 self.matches = self.attr_matches(text)
334 else:
334 else:
335 self.matches = self.global_matches(text)
335 self.matches = self.global_matches(text)
336 try:
336 try:
337 return self.matches[state]
337 return self.matches[state]
338 except IndexError:
338 except IndexError:
339 return None
339 return None
340
340
341 def global_matches(self, text):
341 def global_matches(self, text):
342 """Compute matches when text is a simple name.
342 """Compute matches when text is a simple name.
343
343
344 Return a list of all keywords, built-in functions and names currently
344 Return a list of all keywords, built-in functions and names currently
345 defined in self.namespace or self.global_namespace that match.
345 defined in self.namespace or self.global_namespace that match.
346
346
347 """
347 """
348 matches = []
348 matches = []
349 match_append = matches.append
349 match_append = matches.append
350 n = len(text)
350 n = len(text)
351 for lst in [keyword.kwlist,
351 for lst in [keyword.kwlist,
352 builtin_mod.__dict__.keys(),
352 builtin_mod.__dict__.keys(),
353 self.namespace.keys(),
353 self.namespace.keys(),
354 self.global_namespace.keys()]:
354 self.global_namespace.keys()]:
355 for word in lst:
355 for word in lst:
356 if word[:n] == text and word != "__builtins__":
356 if word[:n] == text and word != "__builtins__":
357 match_append(word)
357 match_append(word)
358 return [cast_unicode_py2(m) for m in matches]
358 return [cast_unicode_py2(m) for m in matches]
359
359
360 def attr_matches(self, text):
360 def attr_matches(self, text):
361 """Compute matches when text contains a dot.
361 """Compute matches when text contains a dot.
362
362
363 Assuming the text is of the form NAME.NAME....[NAME], and is
363 Assuming the text is of the form NAME.NAME....[NAME], and is
364 evaluatable in self.namespace or self.global_namespace, it will be
364 evaluatable in self.namespace or self.global_namespace, it will be
365 evaluated and its attributes (as revealed by dir()) are used as
365 evaluated and its attributes (as revealed by dir()) are used as
366 possible completions. (For class instances, class members are are
366 possible completions. (For class instances, class members are are
367 also considered.)
367 also considered.)
368
368
369 WARNING: this can still invoke arbitrary C code, if an object
369 WARNING: this can still invoke arbitrary C code, if an object
370 with a __getattr__ hook is evaluated.
370 with a __getattr__ hook is evaluated.
371
371
372 """
372 """
373
373
374 # Another option, seems to work great. Catches things like ''.<tab>
374 # Another option, seems to work great. Catches things like ''.<tab>
375 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
375 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
376
376
377 if m:
377 if m:
378 expr, attr = m.group(1, 3)
378 expr, attr = m.group(1, 3)
379 elif self.greedy:
379 elif self.greedy:
380 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
380 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
381 if not m2:
381 if not m2:
382 return []
382 return []
383 expr, attr = m2.group(1,2)
383 expr, attr = m2.group(1,2)
384 else:
384 else:
385 return []
385 return []
386
386
387 try:
387 try:
388 obj = eval(expr, self.namespace)
388 obj = eval(expr, self.namespace)
389 except:
389 except:
390 try:
390 try:
391 obj = eval(expr, self.global_namespace)
391 obj = eval(expr, self.global_namespace)
392 except:
392 except:
393 return []
393 return []
394
394
395 if self.limit_to__all__ and hasattr(obj, '__all__'):
395 if self.limit_to__all__ and hasattr(obj, '__all__'):
396 words = get__all__entries(obj)
396 words = get__all__entries(obj)
397 else:
397 else:
398 words = dir2(obj)
398 words = dir2(obj)
399
399
400 try:
400 try:
401 words = generics.complete_object(obj, words)
401 words = generics.complete_object(obj, words)
402 except TryNext:
402 except TryNext:
403 pass
403 pass
404 except Exception:
404 except Exception:
405 # Silence errors from completion function
405 # Silence errors from completion function
406 #raise # dbg
406 #raise # dbg
407 pass
407 pass
408 # Build match list to return
408 # Build match list to return
409 n = len(attr)
409 n = len(attr)
410 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
410 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
411
411
412
412
413 def get__all__entries(obj):
413 def get__all__entries(obj):
414 """returns the strings in the __all__ attribute"""
414 """returns the strings in the __all__ attribute"""
415 try:
415 try:
416 words = getattr(obj, '__all__')
416 words = getattr(obj, '__all__')
417 except:
417 except:
418 return []
418 return []
419
419
420 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
420 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
421
421
422
422
423 def match_dict_keys(keys, prefix, delims):
423 def match_dict_keys(keys, prefix, delims):
424 """Used by dict_key_matches, matching the prefix to a list of keys"""
424 """Used by dict_key_matches, matching the prefix to a list of keys"""
425 if not prefix:
425 if not prefix:
426 return None, 0, [repr(k) for k in keys
426 return None, 0, [repr(k) for k in keys
427 if isinstance(k, (string_types, bytes))]
427 if isinstance(k, (string_types, bytes))]
428 quote_match = re.search('["\']', prefix)
428 quote_match = re.search('["\']', prefix)
429 quote = quote_match.group()
429 quote = quote_match.group()
430 try:
430 try:
431 prefix_str = eval(prefix + quote, {})
431 prefix_str = eval(prefix + quote, {})
432 except Exception:
432 except Exception:
433 return None, 0, []
433 return None, 0, []
434
434
435 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
435 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
436 token_match = re.search(pattern, prefix, re.UNICODE)
436 token_match = re.search(pattern, prefix, re.UNICODE)
437 token_start = token_match.start()
437 token_start = token_match.start()
438 token_prefix = token_match.group()
438 token_prefix = token_match.group()
439
439
440 # TODO: support bytes in Py3k
440 # TODO: support bytes in Py3k
441 matched = []
441 matched = []
442 for key in keys:
442 for key in keys:
443 try:
443 try:
444 if not key.startswith(prefix_str):
444 if not key.startswith(prefix_str):
445 continue
445 continue
446 except (AttributeError, TypeError, UnicodeError):
446 except (AttributeError, TypeError, UnicodeError):
447 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
447 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
448 continue
448 continue
449
449
450 # reformat remainder of key to begin with prefix
450 # reformat remainder of key to begin with prefix
451 rem = key[len(prefix_str):]
451 rem = key[len(prefix_str):]
452 # force repr wrapped in '
452 # force repr wrapped in '
453 rem_repr = repr(rem + '"')
453 rem_repr = repr(rem + '"')
454 if rem_repr.startswith('u') and prefix[0] not in 'uU':
454 if rem_repr.startswith('u') and prefix[0] not in 'uU':
455 # Found key is unicode, but prefix is Py2 string.
455 # Found key is unicode, but prefix is Py2 string.
456 # Therefore attempt to interpret key as string.
456 # Therefore attempt to interpret key as string.
457 try:
457 try:
458 rem_repr = repr(rem.encode('ascii') + '"')
458 rem_repr = repr(rem.encode('ascii') + '"')
459 except UnicodeEncodeError:
459 except UnicodeEncodeError:
460 continue
460 continue
461
461
462 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
462 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
463 if quote == '"':
463 if quote == '"':
464 # The entered prefix is quoted with ",
464 # The entered prefix is quoted with ",
465 # but the match is quoted with '.
465 # but the match is quoted with '.
466 # A contained " hence needs escaping for comparison:
466 # A contained " hence needs escaping for comparison:
467 rem_repr = rem_repr.replace('"', '\\"')
467 rem_repr = rem_repr.replace('"', '\\"')
468
468
469 # then reinsert prefix from start of token
469 # then reinsert prefix from start of token
470 matched.append('%s%s' % (token_prefix, rem_repr))
470 matched.append('%s%s' % (token_prefix, rem_repr))
471 return quote, token_start, matched
471 return quote, token_start, matched
472
472
473
473
474 def _safe_isinstance(obj, module, class_name):
474 def _safe_isinstance(obj, module, class_name):
475 """Checks if obj is an instance of module.class_name if loaded
475 """Checks if obj is an instance of module.class_name if loaded
476 """
476 """
477 return (module in sys.modules and
477 return (module in sys.modules and
478 isinstance(obj, getattr(__import__(module), class_name)))
478 isinstance(obj, getattr(__import__(module), class_name)))
479
479
480
480
481 def back_unicode_name_matches(text):
481 def back_unicode_name_matches(text):
482 u"""Match unicode characters back to unicode name
482 u"""Match unicode characters back to unicode name
483
483
484 This does ☃ -> \\snowman
484 This does ☃ -> \\snowman
485
485
486 Note that snowman is not a valid python3 combining character but will be expanded.
486 Note that snowman is not a valid python3 combining character but will be expanded.
487 Though it will not recombine back to the snowman character by the completion machinery.
487 Though it will not recombine back to the snowman character by the completion machinery.
488
488
489 This will not either back-complete standard sequences like \\n, \\b ...
489 This will not either back-complete standard sequences like \\n, \\b ...
490
490
491 Used on Python 3 only.
491 Used on Python 3 only.
492 """
492 """
493 if len(text)<2:
493 if len(text)<2:
494 return u'', ()
494 return u'', ()
495 maybe_slash = text[-2]
495 maybe_slash = text[-2]
496 if maybe_slash != '\\':
496 if maybe_slash != '\\':
497 return u'', ()
497 return u'', ()
498
498
499 char = text[-1]
499 char = text[-1]
500 # no expand on quote for completion in strings.
500 # no expand on quote for completion in strings.
501 # nor backcomplete standard ascii keys
501 # nor backcomplete standard ascii keys
502 if char in string.ascii_letters or char in ['"',"'"]:
502 if char in string.ascii_letters or char in ['"',"'"]:
503 return u'', ()
503 return u'', ()
504 try :
504 try :
505 unic = unicodedata.name(char)
505 unic = unicodedata.name(char)
506 return '\\'+char,['\\'+unic]
506 return '\\'+char,['\\'+unic]
507 except KeyError:
507 except KeyError:
508 pass
508 pass
509 return u'', ()
509 return u'', ()
510
510
511 def back_latex_name_matches(text):
511 def back_latex_name_matches(text):
512 u"""Match latex characters back to unicode name
512 u"""Match latex characters back to unicode name
513
513
514 This does ->\\sqrt
514 This does ->\\sqrt
515
515
516 Used on Python 3 only.
516 Used on Python 3 only.
517 """
517 """
518 if len(text)<2:
518 if len(text)<2:
519 return u'', ()
519 return u'', ()
520 maybe_slash = text[-2]
520 maybe_slash = text[-2]
521 if maybe_slash != '\\':
521 if maybe_slash != '\\':
522 return u'', ()
522 return u'', ()
523
523
524
524
525 char = text[-1]
525 char = text[-1]
526 # no expand on quote for completion in strings.
526 # no expand on quote for completion in strings.
527 # nor backcomplete standard ascii keys
527 # nor backcomplete standard ascii keys
528 if char in string.ascii_letters or char in ['"',"'"]:
528 if char in string.ascii_letters or char in ['"',"'"]:
529 return u'', ()
529 return u'', ()
530 try :
530 try :
531 latex = reverse_latex_symbol[char]
531 latex = reverse_latex_symbol[char]
532 # '\\' replace the \ as well
532 # '\\' replace the \ as well
533 return '\\'+char,[latex]
533 return '\\'+char,[latex]
534 except KeyError:
534 except KeyError:
535 pass
535 pass
536 return u'', ()
536 return u'', ()
537
537
538
538
539 class IPCompleter(Completer):
539 class IPCompleter(Completer):
540 """Extension of the completer class with IPython-specific features"""
540 """Extension of the completer class with IPython-specific features"""
541
541
542 @observe('greedy')
542 @observe('greedy')
543 def _greedy_changed(self, change):
543 def _greedy_changed(self, change):
544 """update the splitter and readline delims when greedy is changed"""
544 """update the splitter and readline delims when greedy is changed"""
545 if change['new']:
545 if change['new']:
546 self.splitter.delims = GREEDY_DELIMS
546 self.splitter.delims = GREEDY_DELIMS
547 else:
547 else:
548 self.splitter.delims = DELIMS
548 self.splitter.delims = DELIMS
549
549
550 if self.readline:
550 if self.readline:
551 self.readline.set_completer_delims(self.splitter.delims)
551 self.readline.set_completer_delims(self.splitter.delims)
552
552
553 merge_completions = Bool(True,
553 merge_completions = Bool(True,
554 help="""Whether to merge completion results into a single list
554 help="""Whether to merge completion results into a single list
555
555
556 If False, only the completion results from the first non-empty
556 If False, only the completion results from the first non-empty
557 completer will be returned.
557 completer will be returned.
558 """
558 """
559 ).tag(config=True)
559 ).tag(config=True)
560 omit__names = Enum((0,1,2), default_value=2,
560 omit__names = Enum((0,1,2), default_value=2,
561 help="""Instruct the completer to omit private method names
561 help="""Instruct the completer to omit private method names
562
562
563 Specifically, when completing on ``object.<tab>``.
563 Specifically, when completing on ``object.<tab>``.
564
564
565 When 2 [default]: all names that start with '_' will be excluded.
565 When 2 [default]: all names that start with '_' will be excluded.
566
566
567 When 1: all 'magic' names (``__foo__``) will be excluded.
567 When 1: all 'magic' names (``__foo__``) will be excluded.
568
568
569 When 0: nothing will be excluded.
569 When 0: nothing will be excluded.
570 """
570 """
571 ).tag(config=True)
571 ).tag(config=True)
572 limit_to__all__ = Bool(False,
572 limit_to__all__ = Bool(False,
573 help="""
573 help="""
574 DEPRECATED as of version 5.0.
574 DEPRECATED as of version 5.0.
575
575
576 Instruct the completer to use __all__ for the completion
576 Instruct the completer to use __all__ for the completion
577
577
578 Specifically, when completing on ``object.<tab>``.
578 Specifically, when completing on ``object.<tab>``.
579
579
580 When True: only those names in obj.__all__ will be included.
580 When True: only those names in obj.__all__ will be included.
581
581
582 When False [default]: the __all__ attribute is ignored
582 When False [default]: the __all__ attribute is ignored
583 """,
583 """,
584 ).tag(config=True)
584 ).tag(config=True)
585
585
586 def __init__(self, shell=None, namespace=None, global_namespace=None,
586 def __init__(self, shell=None, namespace=None, global_namespace=None,
587 use_readline=True, config=None, **kwargs):
587 use_readline=True, config=None, **kwargs):
588 """IPCompleter() -> completer
588 """IPCompleter() -> completer
589
589
590 Return a completer object suitable for use by the readline library
590 Return a completer object suitable for use by the readline library
591 via readline.set_completer().
591 via readline.set_completer().
592
592
593 Inputs:
593 Inputs:
594
594
595 - shell: a pointer to the ipython shell itself. This is needed
595 - shell: a pointer to the ipython shell itself. This is needed
596 because this completer knows about magic functions, and those can
596 because this completer knows about magic functions, and those can
597 only be accessed via the ipython instance.
597 only be accessed via the ipython instance.
598
598
599 - namespace: an optional dict where completions are performed.
599 - namespace: an optional dict where completions are performed.
600
600
601 - global_namespace: secondary optional dict for completions, to
601 - global_namespace: secondary optional dict for completions, to
602 handle cases (such as IPython embedded inside functions) where
602 handle cases (such as IPython embedded inside functions) where
603 both Python scopes are visible.
603 both Python scopes are visible.
604
604
605 use_readline : bool, optional
605 use_readline : bool, optional
606 If true, use the readline library. This completer can still function
606 If true, use the readline library. This completer can still function
607 without readline, though in that case callers must provide some extra
607 without readline, though in that case callers must provide some extra
608 information on each call about the current line."""
608 information on each call about the current line."""
609
609
610 self.magic_escape = ESC_MAGIC
610 self.magic_escape = ESC_MAGIC
611 self.splitter = CompletionSplitter()
611 self.splitter = CompletionSplitter()
612
612
613 # Readline configuration, only used by the rlcompleter method.
613 # Readline configuration, only used by the rlcompleter method.
614 if use_readline:
614 if use_readline:
615 # We store the right version of readline so that later code
615 # We store the right version of readline so that later code
616 import IPython.utils.rlineimpl as readline
616 import IPython.utils.rlineimpl as readline
617 self.readline = readline
617 self.readline = readline
618 else:
618 else:
619 self.readline = None
619 self.readline = None
620
620
621 # _greedy_changed() depends on splitter and readline being defined:
621 # _greedy_changed() depends on splitter and readline being defined:
622 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
622 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
623 config=config, **kwargs)
623 config=config, **kwargs)
624
624
625 # List where completion matches will be stored
625 # List where completion matches will be stored
626 self.matches = []
626 self.matches = []
627 self.shell = shell
627 self.shell = shell
628 # Regexp to split filenames with spaces in them
628 # Regexp to split filenames with spaces in them
629 self.space_name_re = re.compile(r'([^\\] )')
629 self.space_name_re = re.compile(r'([^\\] )')
630 # Hold a local ref. to glob.glob for speed
630 # Hold a local ref. to glob.glob for speed
631 self.glob = glob.glob
631 self.glob = glob.glob
632
632
633 # Determine if we are running on 'dumb' terminals, like (X)Emacs
633 # Determine if we are running on 'dumb' terminals, like (X)Emacs
634 # buffers, to avoid completion problems.
634 # buffers, to avoid completion problems.
635 term = os.environ.get('TERM','xterm')
635 term = os.environ.get('TERM','xterm')
636 self.dumb_terminal = term in ['dumb','emacs']
636 self.dumb_terminal = term in ['dumb','emacs']
637
637
638 # Special handling of backslashes needed in win32 platforms
638 # Special handling of backslashes needed in win32 platforms
639 if sys.platform == "win32":
639 if sys.platform == "win32":
640 self.clean_glob = self._clean_glob_win32
640 self.clean_glob = self._clean_glob_win32
641 else:
641 else:
642 self.clean_glob = self._clean_glob
642 self.clean_glob = self._clean_glob
643
643
644 #regexp to parse docstring for function signature
644 #regexp to parse docstring for function signature
645 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
645 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
646 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
646 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
647 #use this if positional argument name is also needed
647 #use this if positional argument name is also needed
648 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
648 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
649
649
650 # All active matcher routines for completion
650 # All active matcher routines for completion
651 self.matchers = [
651 self.matchers = [
652 self.file_matches,
652 self.file_matches,
653 self.magic_matches,
653 self.magic_matches,
654 self.python_func_kw_matches,
654 self.python_func_kw_matches,
655 self.dict_key_matches,
655 self.dict_key_matches,
656 ]
656 ]
657
657
658 def all_completions(self, text):
658 def all_completions(self, text):
659 """
659 """
660 Wrapper around the complete method for the benefit of emacs
660 Wrapper around the complete method for the benefit of emacs.
661 and pydb.
662 """
661 """
663 return self.complete(text)[1]
662 return self.complete(text)[1]
664
663
665 def _clean_glob(self, text):
664 def _clean_glob(self, text):
666 return self.glob("%s*" % text)
665 return self.glob("%s*" % text)
667
666
668 def _clean_glob_win32(self,text):
667 def _clean_glob_win32(self,text):
669 return [f.replace("\\","/")
668 return [f.replace("\\","/")
670 for f in self.glob("%s*" % text)]
669 for f in self.glob("%s*" % text)]
671
670
672 def file_matches(self, text):
671 def file_matches(self, text):
673 """Match filenames, expanding ~USER type strings.
672 """Match filenames, expanding ~USER type strings.
674
673
675 Most of the seemingly convoluted logic in this completer is an
674 Most of the seemingly convoluted logic in this completer is an
676 attempt to handle filenames with spaces in them. And yet it's not
675 attempt to handle filenames with spaces in them. And yet it's not
677 quite perfect, because Python's readline doesn't expose all of the
676 quite perfect, because Python's readline doesn't expose all of the
678 GNU readline details needed for this to be done correctly.
677 GNU readline details needed for this to be done correctly.
679
678
680 For a filename with a space in it, the printed completions will be
679 For a filename with a space in it, the printed completions will be
681 only the parts after what's already been typed (instead of the
680 only the parts after what's already been typed (instead of the
682 full completions, as is normally done). I don't think with the
681 full completions, as is normally done). I don't think with the
683 current (as of Python 2.3) Python readline it's possible to do
682 current (as of Python 2.3) Python readline it's possible to do
684 better."""
683 better."""
685
684
686 # chars that require escaping with backslash - i.e. chars
685 # chars that require escaping with backslash - i.e. chars
687 # that readline treats incorrectly as delimiters, but we
686 # that readline treats incorrectly as delimiters, but we
688 # don't want to treat as delimiters in filename matching
687 # don't want to treat as delimiters in filename matching
689 # when escaped with backslash
688 # when escaped with backslash
690 if text.startswith('!'):
689 if text.startswith('!'):
691 text = text[1:]
690 text = text[1:]
692 text_prefix = u'!'
691 text_prefix = u'!'
693 else:
692 else:
694 text_prefix = u''
693 text_prefix = u''
695
694
696 text_until_cursor = self.text_until_cursor
695 text_until_cursor = self.text_until_cursor
697 # track strings with open quotes
696 # track strings with open quotes
698 open_quotes = has_open_quotes(text_until_cursor)
697 open_quotes = has_open_quotes(text_until_cursor)
699
698
700 if '(' in text_until_cursor or '[' in text_until_cursor:
699 if '(' in text_until_cursor or '[' in text_until_cursor:
701 lsplit = text
700 lsplit = text
702 else:
701 else:
703 try:
702 try:
704 # arg_split ~ shlex.split, but with unicode bugs fixed by us
703 # arg_split ~ shlex.split, but with unicode bugs fixed by us
705 lsplit = arg_split(text_until_cursor)[-1]
704 lsplit = arg_split(text_until_cursor)[-1]
706 except ValueError:
705 except ValueError:
707 # typically an unmatched ", or backslash without escaped char.
706 # typically an unmatched ", or backslash without escaped char.
708 if open_quotes:
707 if open_quotes:
709 lsplit = text_until_cursor.split(open_quotes)[-1]
708 lsplit = text_until_cursor.split(open_quotes)[-1]
710 else:
709 else:
711 return []
710 return []
712 except IndexError:
711 except IndexError:
713 # tab pressed on empty line
712 # tab pressed on empty line
714 lsplit = ""
713 lsplit = ""
715
714
716 if not open_quotes and lsplit != protect_filename(lsplit):
715 if not open_quotes and lsplit != protect_filename(lsplit):
717 # if protectables are found, do matching on the whole escaped name
716 # if protectables are found, do matching on the whole escaped name
718 has_protectables = True
717 has_protectables = True
719 text0,text = text,lsplit
718 text0,text = text,lsplit
720 else:
719 else:
721 has_protectables = False
720 has_protectables = False
722 text = os.path.expanduser(text)
721 text = os.path.expanduser(text)
723
722
724 if text == "":
723 if text == "":
725 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
724 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
726
725
727 # Compute the matches from the filesystem
726 # Compute the matches from the filesystem
728 m0 = self.clean_glob(text.replace('\\',''))
727 m0 = self.clean_glob(text.replace('\\',''))
729
728
730 if has_protectables:
729 if has_protectables:
731 # If we had protectables, we need to revert our changes to the
730 # If we had protectables, we need to revert our changes to the
732 # beginning of filename so that we don't double-write the part
731 # beginning of filename so that we don't double-write the part
733 # of the filename we have so far
732 # of the filename we have so far
734 len_lsplit = len(lsplit)
733 len_lsplit = len(lsplit)
735 matches = [text_prefix + text0 +
734 matches = [text_prefix + text0 +
736 protect_filename(f[len_lsplit:]) for f in m0]
735 protect_filename(f[len_lsplit:]) for f in m0]
737 else:
736 else:
738 if open_quotes:
737 if open_quotes:
739 # if we have a string with an open quote, we don't need to
738 # if we have a string with an open quote, we don't need to
740 # protect the names at all (and we _shouldn't_, as it
739 # protect the names at all (and we _shouldn't_, as it
741 # would cause bugs when the filesystem call is made).
740 # would cause bugs when the filesystem call is made).
742 matches = m0
741 matches = m0
743 else:
742 else:
744 matches = [text_prefix +
743 matches = [text_prefix +
745 protect_filename(f) for f in m0]
744 protect_filename(f) for f in m0]
746
745
747 # Mark directories in input list by appending '/' to their names.
746 # Mark directories in input list by appending '/' to their names.
748 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
747 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
749
748
750 def magic_matches(self, text):
749 def magic_matches(self, text):
751 """Match magics"""
750 """Match magics"""
752 # Get all shell magics now rather than statically, so magics loaded at
751 # Get all shell magics now rather than statically, so magics loaded at
753 # runtime show up too.
752 # runtime show up too.
754 lsm = self.shell.magics_manager.lsmagic()
753 lsm = self.shell.magics_manager.lsmagic()
755 line_magics = lsm['line']
754 line_magics = lsm['line']
756 cell_magics = lsm['cell']
755 cell_magics = lsm['cell']
757 pre = self.magic_escape
756 pre = self.magic_escape
758 pre2 = pre+pre
757 pre2 = pre+pre
759
758
760 # Completion logic:
759 # Completion logic:
761 # - user gives %%: only do cell magics
760 # - user gives %%: only do cell magics
762 # - user gives %: do both line and cell magics
761 # - user gives %: do both line and cell magics
763 # - no prefix: do both
762 # - no prefix: do both
764 # In other words, line magics are skipped if the user gives %% explicitly
763 # In other words, line magics are skipped if the user gives %% explicitly
765 bare_text = text.lstrip(pre)
764 bare_text = text.lstrip(pre)
766 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
765 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
767 if not text.startswith(pre2):
766 if not text.startswith(pre2):
768 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
767 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
769 return [cast_unicode_py2(c) for c in comp]
768 return [cast_unicode_py2(c) for c in comp]
770
769
771 def python_jedi_matches(self, text, line_buffer, cursor_pos):
770 def python_jedi_matches(self, text, line_buffer, cursor_pos):
772 """Match attributes or global Python names using Jedi."""
771 """Match attributes or global Python names using Jedi."""
773 if line_buffer.startswith('aimport ') or line_buffer.startswith('%aimport '):
772 if line_buffer.startswith('aimport ') or line_buffer.startswith('%aimport '):
774 return ()
773 return ()
775 namespaces = []
774 namespaces = []
776 if self.namespace is None:
775 if self.namespace is None:
777 import __main__
776 import __main__
778 namespaces.append(__main__.__dict__)
777 namespaces.append(__main__.__dict__)
779 else:
778 else:
780 namespaces.append(self.namespace)
779 namespaces.append(self.namespace)
781 if self.global_namespace is not None:
780 if self.global_namespace is not None:
782 namespaces.append(self.global_namespace)
781 namespaces.append(self.global_namespace)
783
782
784 # cursor_pos is an it, jedi wants line and column
783 # cursor_pos is an it, jedi wants line and column
785
784
786 interpreter = jedi.Interpreter(line_buffer, namespaces, column=cursor_pos)
785 interpreter = jedi.Interpreter(line_buffer, namespaces, column=cursor_pos)
787 path = jedi.parser.user_context.UserContext(line_buffer, \
786 path = jedi.parser.user_context.UserContext(line_buffer, \
788 (1, len(line_buffer))).get_path_until_cursor()
787 (1, len(line_buffer))).get_path_until_cursor()
789 path, dot, like = jedi.api.helpers.completion_parts(path)
788 path, dot, like = jedi.api.helpers.completion_parts(path)
790 if text.startswith('.'):
789 if text.startswith('.'):
791 # text will be `.` on completions like `a[0].<tab>`
790 # text will be `.` on completions like `a[0].<tab>`
792 before = dot
791 before = dot
793 else:
792 else:
794 before = line_buffer[:len(line_buffer) - len(like)]
793 before = line_buffer[:len(line_buffer) - len(like)]
795
794
796
795
797 def trim_start(completion):
796 def trim_start(completion):
798 """completions need to start with `text`, trim the beginning until it does"""
797 """completions need to start with `text`, trim the beginning until it does"""
799 ltext = text.lower()
798 ltext = text.lower()
800 lcomp = completion.lower()
799 lcomp = completion.lower()
801 if ltext in lcomp and not (lcomp.startswith(ltext)):
800 if ltext in lcomp and not (lcomp.startswith(ltext)):
802 start_index = lcomp.index(ltext)
801 start_index = lcomp.index(ltext)
803 if cursor_pos:
802 if cursor_pos:
804 if start_index >= cursor_pos:
803 if start_index >= cursor_pos:
805 start_index = min(start_index, cursor_pos)
804 start_index = min(start_index, cursor_pos)
806 return completion[start_index:]
805 return completion[start_index:]
807 return completion
806 return completion
808
807
809 completions = interpreter.completions()
808 completions = interpreter.completions()
810
809
811 completion_text = [c.name_with_symbols for c in completions]
810 completion_text = [c.name_with_symbols for c in completions]
812
811
813 if self.omit__names:
812 if self.omit__names:
814 if self.omit__names == 1:
813 if self.omit__names == 1:
815 # true if txt is _not_ a __ name, false otherwise:
814 # true if txt is _not_ a __ name, false otherwise:
816 no__name = lambda txt: not txt.startswith('__')
815 no__name = lambda txt: not txt.startswith('__')
817 else:
816 else:
818 # true if txt is _not_ a _ name, false otherwise:
817 # true if txt is _not_ a _ name, false otherwise:
819 no__name = lambda txt: not txt.startswith('_')
818 no__name = lambda txt: not txt.startswith('_')
820 completion_text = filter(no__name, completion_text)
819 completion_text = filter(no__name, completion_text)
821
820
822
821
823 return [trim_start(before + c_text) for c_text in completion_text]
822 return [trim_start(before + c_text) for c_text in completion_text]
824
823
825
824
826 def python_matches(self, text):
825 def python_matches(self, text):
827 """Match attributes or global python names"""
826 """Match attributes or global python names"""
828 if "." in text:
827 if "." in text:
829 try:
828 try:
830 matches = self.attr_matches(text)
829 matches = self.attr_matches(text)
831 if text.endswith('.') and self.omit__names:
830 if text.endswith('.') and self.omit__names:
832 if self.omit__names == 1:
831 if self.omit__names == 1:
833 # true if txt is _not_ a __ name, false otherwise:
832 # true if txt is _not_ a __ name, false otherwise:
834 no__name = (lambda txt:
833 no__name = (lambda txt:
835 re.match(r'.*\.__.*?__',txt) is None)
834 re.match(r'.*\.__.*?__',txt) is None)
836 else:
835 else:
837 # true if txt is _not_ a _ name, false otherwise:
836 # true if txt is _not_ a _ name, false otherwise:
838 no__name = (lambda txt:
837 no__name = (lambda txt:
839 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
838 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
840 matches = filter(no__name, matches)
839 matches = filter(no__name, matches)
841 except NameError:
840 except NameError:
842 # catches <undefined attributes>.<tab>
841 # catches <undefined attributes>.<tab>
843 matches = []
842 matches = []
844 else:
843 else:
845 matches = self.global_matches(text)
844 matches = self.global_matches(text)
846 return matches
845 return matches
847
846
848 def _default_arguments_from_docstring(self, doc):
847 def _default_arguments_from_docstring(self, doc):
849 """Parse the first line of docstring for call signature.
848 """Parse the first line of docstring for call signature.
850
849
851 Docstring should be of the form 'min(iterable[, key=func])\n'.
850 Docstring should be of the form 'min(iterable[, key=func])\n'.
852 It can also parse cython docstring of the form
851 It can also parse cython docstring of the form
853 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
852 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
854 """
853 """
855 if doc is None:
854 if doc is None:
856 return []
855 return []
857
856
858 #care only the firstline
857 #care only the firstline
859 line = doc.lstrip().splitlines()[0]
858 line = doc.lstrip().splitlines()[0]
860
859
861 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
860 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
862 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
861 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
863 sig = self.docstring_sig_re.search(line)
862 sig = self.docstring_sig_re.search(line)
864 if sig is None:
863 if sig is None:
865 return []
864 return []
866 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
865 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
867 sig = sig.groups()[0].split(',')
866 sig = sig.groups()[0].split(',')
868 ret = []
867 ret = []
869 for s in sig:
868 for s in sig:
870 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
869 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
871 ret += self.docstring_kwd_re.findall(s)
870 ret += self.docstring_kwd_re.findall(s)
872 return ret
871 return ret
873
872
874 def _default_arguments(self, obj):
873 def _default_arguments(self, obj):
875 """Return the list of default arguments of obj if it is callable,
874 """Return the list of default arguments of obj if it is callable,
876 or empty list otherwise."""
875 or empty list otherwise."""
877 call_obj = obj
876 call_obj = obj
878 ret = []
877 ret = []
879 if inspect.isbuiltin(obj):
878 if inspect.isbuiltin(obj):
880 pass
879 pass
881 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
880 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
882 if inspect.isclass(obj):
881 if inspect.isclass(obj):
883 #for cython embededsignature=True the constructor docstring
882 #for cython embededsignature=True the constructor docstring
884 #belongs to the object itself not __init__
883 #belongs to the object itself not __init__
885 ret += self._default_arguments_from_docstring(
884 ret += self._default_arguments_from_docstring(
886 getattr(obj, '__doc__', ''))
885 getattr(obj, '__doc__', ''))
887 # for classes, check for __init__,__new__
886 # for classes, check for __init__,__new__
888 call_obj = (getattr(obj, '__init__', None) or
887 call_obj = (getattr(obj, '__init__', None) or
889 getattr(obj, '__new__', None))
888 getattr(obj, '__new__', None))
890 # for all others, check if they are __call__able
889 # for all others, check if they are __call__able
891 elif hasattr(obj, '__call__'):
890 elif hasattr(obj, '__call__'):
892 call_obj = obj.__call__
891 call_obj = obj.__call__
893 ret += self._default_arguments_from_docstring(
892 ret += self._default_arguments_from_docstring(
894 getattr(call_obj, '__doc__', ''))
893 getattr(call_obj, '__doc__', ''))
895
894
896 if PY3:
895 if PY3:
897 _keeps = (inspect.Parameter.KEYWORD_ONLY,
896 _keeps = (inspect.Parameter.KEYWORD_ONLY,
898 inspect.Parameter.POSITIONAL_OR_KEYWORD)
897 inspect.Parameter.POSITIONAL_OR_KEYWORD)
899 signature = inspect.signature
898 signature = inspect.signature
900 else:
899 else:
901 import IPython.utils.signatures
900 import IPython.utils.signatures
902 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
901 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
903 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
902 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
904 signature = IPython.utils.signatures.signature
903 signature = IPython.utils.signatures.signature
905
904
906 try:
905 try:
907 sig = signature(call_obj)
906 sig = signature(call_obj)
908 ret.extend(k for k, v in sig.parameters.items() if
907 ret.extend(k for k, v in sig.parameters.items() if
909 v.kind in _keeps)
908 v.kind in _keeps)
910 except ValueError:
909 except ValueError:
911 pass
910 pass
912
911
913 return list(set(ret))
912 return list(set(ret))
914
913
915 def python_func_kw_matches(self,text):
914 def python_func_kw_matches(self,text):
916 """Match named parameters (kwargs) of the last open function"""
915 """Match named parameters (kwargs) of the last open function"""
917
916
918 if "." in text: # a parameter cannot be dotted
917 if "." in text: # a parameter cannot be dotted
919 return []
918 return []
920 try: regexp = self.__funcParamsRegex
919 try: regexp = self.__funcParamsRegex
921 except AttributeError:
920 except AttributeError:
922 regexp = self.__funcParamsRegex = re.compile(r'''
921 regexp = self.__funcParamsRegex = re.compile(r'''
923 '.*?(?<!\\)' | # single quoted strings or
922 '.*?(?<!\\)' | # single quoted strings or
924 ".*?(?<!\\)" | # double quoted strings or
923 ".*?(?<!\\)" | # double quoted strings or
925 \w+ | # identifier
924 \w+ | # identifier
926 \S # other characters
925 \S # other characters
927 ''', re.VERBOSE | re.DOTALL)
926 ''', re.VERBOSE | re.DOTALL)
928 # 1. find the nearest identifier that comes before an unclosed
927 # 1. find the nearest identifier that comes before an unclosed
929 # parenthesis before the cursor
928 # parenthesis before the cursor
930 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
929 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
931 tokens = regexp.findall(self.text_until_cursor)
930 tokens = regexp.findall(self.text_until_cursor)
932 tokens.reverse()
931 tokens.reverse()
933 iterTokens = iter(tokens); openPar = 0
932 iterTokens = iter(tokens); openPar = 0
934
933
935 for token in iterTokens:
934 for token in iterTokens:
936 if token == ')':
935 if token == ')':
937 openPar -= 1
936 openPar -= 1
938 elif token == '(':
937 elif token == '(':
939 openPar += 1
938 openPar += 1
940 if openPar > 0:
939 if openPar > 0:
941 # found the last unclosed parenthesis
940 # found the last unclosed parenthesis
942 break
941 break
943 else:
942 else:
944 return []
943 return []
945 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
944 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
946 ids = []
945 ids = []
947 isId = re.compile(r'\w+$').match
946 isId = re.compile(r'\w+$').match
948
947
949 while True:
948 while True:
950 try:
949 try:
951 ids.append(next(iterTokens))
950 ids.append(next(iterTokens))
952 if not isId(ids[-1]):
951 if not isId(ids[-1]):
953 ids.pop(); break
952 ids.pop(); break
954 if not next(iterTokens) == '.':
953 if not next(iterTokens) == '.':
955 break
954 break
956 except StopIteration:
955 except StopIteration:
957 break
956 break
958 # lookup the candidate callable matches either using global_matches
957 # lookup the candidate callable matches either using global_matches
959 # or attr_matches for dotted names
958 # or attr_matches for dotted names
960 if len(ids) == 1:
959 if len(ids) == 1:
961 callableMatches = self.global_matches(ids[0])
960 callableMatches = self.global_matches(ids[0])
962 else:
961 else:
963 callableMatches = self.attr_matches('.'.join(ids[::-1]))
962 callableMatches = self.attr_matches('.'.join(ids[::-1]))
964 argMatches = []
963 argMatches = []
965 for callableMatch in callableMatches:
964 for callableMatch in callableMatches:
966 try:
965 try:
967 namedArgs = self._default_arguments(eval(callableMatch,
966 namedArgs = self._default_arguments(eval(callableMatch,
968 self.namespace))
967 self.namespace))
969 except:
968 except:
970 continue
969 continue
971
970
972 for namedArg in namedArgs:
971 for namedArg in namedArgs:
973 if namedArg.startswith(text):
972 if namedArg.startswith(text):
974 argMatches.append(u"%s=" %namedArg)
973 argMatches.append(u"%s=" %namedArg)
975 return argMatches
974 return argMatches
976
975
977 def dict_key_matches(self, text):
976 def dict_key_matches(self, text):
978 "Match string keys in a dictionary, after e.g. 'foo[' "
977 "Match string keys in a dictionary, after e.g. 'foo[' "
979 def get_keys(obj):
978 def get_keys(obj):
980 # Objects can define their own completions by defining an
979 # Objects can define their own completions by defining an
981 # _ipy_key_completions_() method.
980 # _ipy_key_completions_() method.
982 method = get_real_method(obj, '_ipython_key_completions_')
981 method = get_real_method(obj, '_ipython_key_completions_')
983 if method is not None:
982 if method is not None:
984 return method()
983 return method()
985
984
986 # Special case some common in-memory dict-like types
985 # Special case some common in-memory dict-like types
987 if isinstance(obj, dict) or\
986 if isinstance(obj, dict) or\
988 _safe_isinstance(obj, 'pandas', 'DataFrame'):
987 _safe_isinstance(obj, 'pandas', 'DataFrame'):
989 try:
988 try:
990 return list(obj.keys())
989 return list(obj.keys())
991 except Exception:
990 except Exception:
992 return []
991 return []
993 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
992 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
994 _safe_isinstance(obj, 'numpy', 'void'):
993 _safe_isinstance(obj, 'numpy', 'void'):
995 return obj.dtype.names or []
994 return obj.dtype.names or []
996 return []
995 return []
997
996
998 try:
997 try:
999 regexps = self.__dict_key_regexps
998 regexps = self.__dict_key_regexps
1000 except AttributeError:
999 except AttributeError:
1001 dict_key_re_fmt = r'''(?x)
1000 dict_key_re_fmt = r'''(?x)
1002 ( # match dict-referring expression wrt greedy setting
1001 ( # match dict-referring expression wrt greedy setting
1003 %s
1002 %s
1004 )
1003 )
1005 \[ # open bracket
1004 \[ # open bracket
1006 \s* # and optional whitespace
1005 \s* # and optional whitespace
1007 ([uUbB]? # string prefix (r not handled)
1006 ([uUbB]? # string prefix (r not handled)
1008 (?: # unclosed string
1007 (?: # unclosed string
1009 '(?:[^']|(?<!\\)\\')*
1008 '(?:[^']|(?<!\\)\\')*
1010 |
1009 |
1011 "(?:[^"]|(?<!\\)\\")*
1010 "(?:[^"]|(?<!\\)\\")*
1012 )
1011 )
1013 )?
1012 )?
1014 $
1013 $
1015 '''
1014 '''
1016 regexps = self.__dict_key_regexps = {
1015 regexps = self.__dict_key_regexps = {
1017 False: re.compile(dict_key_re_fmt % '''
1016 False: re.compile(dict_key_re_fmt % '''
1018 # identifiers separated by .
1017 # identifiers separated by .
1019 (?!\d)\w+
1018 (?!\d)\w+
1020 (?:\.(?!\d)\w+)*
1019 (?:\.(?!\d)\w+)*
1021 '''),
1020 '''),
1022 True: re.compile(dict_key_re_fmt % '''
1021 True: re.compile(dict_key_re_fmt % '''
1023 .+
1022 .+
1024 ''')
1023 ''')
1025 }
1024 }
1026
1025
1027 match = regexps[self.greedy].search(self.text_until_cursor)
1026 match = regexps[self.greedy].search(self.text_until_cursor)
1028 if match is None:
1027 if match is None:
1029 return []
1028 return []
1030
1029
1031 expr, prefix = match.groups()
1030 expr, prefix = match.groups()
1032 try:
1031 try:
1033 obj = eval(expr, self.namespace)
1032 obj = eval(expr, self.namespace)
1034 except Exception:
1033 except Exception:
1035 try:
1034 try:
1036 obj = eval(expr, self.global_namespace)
1035 obj = eval(expr, self.global_namespace)
1037 except Exception:
1036 except Exception:
1038 return []
1037 return []
1039
1038
1040 keys = get_keys(obj)
1039 keys = get_keys(obj)
1041 if not keys:
1040 if not keys:
1042 return keys
1041 return keys
1043 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1042 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1044 if not matches:
1043 if not matches:
1045 return matches
1044 return matches
1046
1045
1047 # get the cursor position of
1046 # get the cursor position of
1048 # - the text being completed
1047 # - the text being completed
1049 # - the start of the key text
1048 # - the start of the key text
1050 # - the start of the completion
1049 # - the start of the completion
1051 text_start = len(self.text_until_cursor) - len(text)
1050 text_start = len(self.text_until_cursor) - len(text)
1052 if prefix:
1051 if prefix:
1053 key_start = match.start(2)
1052 key_start = match.start(2)
1054 completion_start = key_start + token_offset
1053 completion_start = key_start + token_offset
1055 else:
1054 else:
1056 key_start = completion_start = match.end()
1055 key_start = completion_start = match.end()
1057
1056
1058 # grab the leading prefix, to make sure all completions start with `text`
1057 # grab the leading prefix, to make sure all completions start with `text`
1059 if text_start > key_start:
1058 if text_start > key_start:
1060 leading = ''
1059 leading = ''
1061 else:
1060 else:
1062 leading = text[text_start:completion_start]
1061 leading = text[text_start:completion_start]
1063
1062
1064 # the index of the `[` character
1063 # the index of the `[` character
1065 bracket_idx = match.end(1)
1064 bracket_idx = match.end(1)
1066
1065
1067 # append closing quote and bracket as appropriate
1066 # append closing quote and bracket as appropriate
1068 # this is *not* appropriate if the opening quote or bracket is outside
1067 # this is *not* appropriate if the opening quote or bracket is outside
1069 # the text given to this method
1068 # the text given to this method
1070 suf = ''
1069 suf = ''
1071 continuation = self.line_buffer[len(self.text_until_cursor):]
1070 continuation = self.line_buffer[len(self.text_until_cursor):]
1072 if key_start > text_start and closing_quote:
1071 if key_start > text_start and closing_quote:
1073 # quotes were opened inside text, maybe close them
1072 # quotes were opened inside text, maybe close them
1074 if continuation.startswith(closing_quote):
1073 if continuation.startswith(closing_quote):
1075 continuation = continuation[len(closing_quote):]
1074 continuation = continuation[len(closing_quote):]
1076 else:
1075 else:
1077 suf += closing_quote
1076 suf += closing_quote
1078 if bracket_idx > text_start:
1077 if bracket_idx > text_start:
1079 # brackets were opened inside text, maybe close them
1078 # brackets were opened inside text, maybe close them
1080 if not continuation.startswith(']'):
1079 if not continuation.startswith(']'):
1081 suf += ']'
1080 suf += ']'
1082
1081
1083 return [leading + k + suf for k in matches]
1082 return [leading + k + suf for k in matches]
1084
1083
1085 def unicode_name_matches(self, text):
1084 def unicode_name_matches(self, text):
1086 u"""Match Latex-like syntax for unicode characters base
1085 u"""Match Latex-like syntax for unicode characters base
1087 on the name of the character.
1086 on the name of the character.
1088
1087
1089 This does \\GREEK SMALL LETTER ETA -> η
1088 This does \\GREEK SMALL LETTER ETA -> η
1090
1089
1091 Works only on valid python 3 identifier, or on combining characters that
1090 Works only on valid python 3 identifier, or on combining characters that
1092 will combine to form a valid identifier.
1091 will combine to form a valid identifier.
1093
1092
1094 Used on Python 3 only.
1093 Used on Python 3 only.
1095 """
1094 """
1096 slashpos = text.rfind('\\')
1095 slashpos = text.rfind('\\')
1097 if slashpos > -1:
1096 if slashpos > -1:
1098 s = text[slashpos+1:]
1097 s = text[slashpos+1:]
1099 try :
1098 try :
1100 unic = unicodedata.lookup(s)
1099 unic = unicodedata.lookup(s)
1101 # allow combining chars
1100 # allow combining chars
1102 if ('a'+unic).isidentifier():
1101 if ('a'+unic).isidentifier():
1103 return '\\'+s,[unic]
1102 return '\\'+s,[unic]
1104 except KeyError:
1103 except KeyError:
1105 pass
1104 pass
1106 return u'', []
1105 return u'', []
1107
1106
1108
1107
1109
1108
1110
1109
1111 def latex_matches(self, text):
1110 def latex_matches(self, text):
1112 u"""Match Latex syntax for unicode characters.
1111 u"""Match Latex syntax for unicode characters.
1113
1112
1114 This does both \\alp -> \\alpha and \\alpha -> α
1113 This does both \\alp -> \\alpha and \\alpha -> α
1115
1114
1116 Used on Python 3 only.
1115 Used on Python 3 only.
1117 """
1116 """
1118 slashpos = text.rfind('\\')
1117 slashpos = text.rfind('\\')
1119 if slashpos > -1:
1118 if slashpos > -1:
1120 s = text[slashpos:]
1119 s = text[slashpos:]
1121 if s in latex_symbols:
1120 if s in latex_symbols:
1122 # Try to complete a full latex symbol to unicode
1121 # Try to complete a full latex symbol to unicode
1123 # \\alpha -> α
1122 # \\alpha -> α
1124 return s, [latex_symbols[s]]
1123 return s, [latex_symbols[s]]
1125 else:
1124 else:
1126 # If a user has partially typed a latex symbol, give them
1125 # If a user has partially typed a latex symbol, give them
1127 # a full list of options \al -> [\aleph, \alpha]
1126 # a full list of options \al -> [\aleph, \alpha]
1128 matches = [k for k in latex_symbols if k.startswith(s)]
1127 matches = [k for k in latex_symbols if k.startswith(s)]
1129 return s, matches
1128 return s, matches
1130 return u'', []
1129 return u'', []
1131
1130
1132 def dispatch_custom_completer(self, text):
1131 def dispatch_custom_completer(self, text):
1133 line = self.line_buffer
1132 line = self.line_buffer
1134 if not line.strip():
1133 if not line.strip():
1135 return None
1134 return None
1136
1135
1137 # Create a little structure to pass all the relevant information about
1136 # Create a little structure to pass all the relevant information about
1138 # the current completion to any custom completer.
1137 # the current completion to any custom completer.
1139 event = Bunch()
1138 event = Bunch()
1140 event.line = line
1139 event.line = line
1141 event.symbol = text
1140 event.symbol = text
1142 cmd = line.split(None,1)[0]
1141 cmd = line.split(None,1)[0]
1143 event.command = cmd
1142 event.command = cmd
1144 event.text_until_cursor = self.text_until_cursor
1143 event.text_until_cursor = self.text_until_cursor
1145
1144
1146 # for foo etc, try also to find completer for %foo
1145 # for foo etc, try also to find completer for %foo
1147 if not cmd.startswith(self.magic_escape):
1146 if not cmd.startswith(self.magic_escape):
1148 try_magic = self.custom_completers.s_matches(
1147 try_magic = self.custom_completers.s_matches(
1149 self.magic_escape + cmd)
1148 self.magic_escape + cmd)
1150 else:
1149 else:
1151 try_magic = []
1150 try_magic = []
1152
1151
1153 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1152 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1154 try_magic,
1153 try_magic,
1155 self.custom_completers.flat_matches(self.text_until_cursor)):
1154 self.custom_completers.flat_matches(self.text_until_cursor)):
1156 try:
1155 try:
1157 res = c(event)
1156 res = c(event)
1158 if res:
1157 if res:
1159 # first, try case sensitive match
1158 # first, try case sensitive match
1160 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1159 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1161 if withcase:
1160 if withcase:
1162 return withcase
1161 return withcase
1163 # if none, then case insensitive ones are ok too
1162 # if none, then case insensitive ones are ok too
1164 text_low = text.lower()
1163 text_low = text.lower()
1165 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1164 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1166 except TryNext:
1165 except TryNext:
1167 pass
1166 pass
1168
1167
1169 return None
1168 return None
1170
1169
1171 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1170 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1172 """Find completions for the given text and line context.
1171 """Find completions for the given text and line context.
1173
1172
1174 Note that both the text and the line_buffer are optional, but at least
1173 Note that both the text and the line_buffer are optional, but at least
1175 one of them must be given.
1174 one of them must be given.
1176
1175
1177 Parameters
1176 Parameters
1178 ----------
1177 ----------
1179 text : string, optional
1178 text : string, optional
1180 Text to perform the completion on. If not given, the line buffer
1179 Text to perform the completion on. If not given, the line buffer
1181 is split using the instance's CompletionSplitter object.
1180 is split using the instance's CompletionSplitter object.
1182
1181
1183 line_buffer : string, optional
1182 line_buffer : string, optional
1184 If not given, the completer attempts to obtain the current line
1183 If not given, the completer attempts to obtain the current line
1185 buffer via readline. This keyword allows clients which are
1184 buffer via readline. This keyword allows clients which are
1186 requesting for text completions in non-readline contexts to inform
1185 requesting for text completions in non-readline contexts to inform
1187 the completer of the entire text.
1186 the completer of the entire text.
1188
1187
1189 cursor_pos : int, optional
1188 cursor_pos : int, optional
1190 Index of the cursor in the full line buffer. Should be provided by
1189 Index of the cursor in the full line buffer. Should be provided by
1191 remote frontends where kernel has no access to frontend state.
1190 remote frontends where kernel has no access to frontend state.
1192
1191
1193 Returns
1192 Returns
1194 -------
1193 -------
1195 text : str
1194 text : str
1196 Text that was actually used in the completion.
1195 Text that was actually used in the completion.
1197
1196
1198 matches : list
1197 matches : list
1199 A list of completion matches.
1198 A list of completion matches.
1200 """
1199 """
1201 # if the cursor position isn't given, the only sane assumption we can
1200 # if the cursor position isn't given, the only sane assumption we can
1202 # make is that it's at the end of the line (the common case)
1201 # make is that it's at the end of the line (the common case)
1203 if cursor_pos is None:
1202 if cursor_pos is None:
1204 cursor_pos = len(line_buffer) if text is None else len(text)
1203 cursor_pos = len(line_buffer) if text is None else len(text)
1205
1204
1206 if PY3:
1205 if PY3:
1207
1206
1208 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1207 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1209 latex_text, latex_matches = self.latex_matches(base_text)
1208 latex_text, latex_matches = self.latex_matches(base_text)
1210 if latex_matches:
1209 if latex_matches:
1211 return latex_text, latex_matches
1210 return latex_text, latex_matches
1212 name_text = ''
1211 name_text = ''
1213 name_matches = []
1212 name_matches = []
1214 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1213 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1215 name_text, name_matches = meth(base_text)
1214 name_text, name_matches = meth(base_text)
1216 if name_text:
1215 if name_text:
1217 return name_text, name_matches
1216 return name_text, name_matches
1218
1217
1219 # if text is either None or an empty string, rely on the line buffer
1218 # if text is either None or an empty string, rely on the line buffer
1220 if not text:
1219 if not text:
1221 text = self.splitter.split_line(line_buffer, cursor_pos)
1220 text = self.splitter.split_line(line_buffer, cursor_pos)
1222
1221
1223 # If no line buffer is given, assume the input text is all there was
1222 # If no line buffer is given, assume the input text is all there was
1224 if line_buffer is None:
1223 if line_buffer is None:
1225 line_buffer = text
1224 line_buffer = text
1226
1225
1227 self.line_buffer = line_buffer
1226 self.line_buffer = line_buffer
1228 self.text_until_cursor = self.line_buffer[:cursor_pos]
1227 self.text_until_cursor = self.line_buffer[:cursor_pos]
1229
1228
1230 # Start with a clean slate of completions
1229 # Start with a clean slate of completions
1231 self.matches[:] = []
1230 self.matches[:] = []
1232 custom_res = self.dispatch_custom_completer(text)
1231 custom_res = self.dispatch_custom_completer(text)
1233 if custom_res is not None:
1232 if custom_res is not None:
1234 # did custom completers produce something?
1233 # did custom completers produce something?
1235 self.matches = custom_res
1234 self.matches = custom_res
1236 else:
1235 else:
1237 # Extend the list of completions with the results of each
1236 # Extend the list of completions with the results of each
1238 # matcher, so we return results to the user from all
1237 # matcher, so we return results to the user from all
1239 # namespaces.
1238 # namespaces.
1240 if self.merge_completions:
1239 if self.merge_completions:
1241 self.matches = []
1240 self.matches = []
1242 for matcher in self.matchers:
1241 for matcher in self.matchers:
1243 try:
1242 try:
1244 self.matches.extend(matcher(text))
1243 self.matches.extend(matcher(text))
1245 except:
1244 except:
1246 # Show the ugly traceback if the matcher causes an
1245 # Show the ugly traceback if the matcher causes an
1247 # exception, but do NOT crash the kernel!
1246 # exception, but do NOT crash the kernel!
1248 sys.excepthook(*sys.exc_info())
1247 sys.excepthook(*sys.exc_info())
1249 else:
1248 else:
1250 for matcher in self.matchers:
1249 for matcher in self.matchers:
1251 self.matches = matcher(text)
1250 self.matches = matcher(text)
1252 if self.matches:
1251 if self.matches:
1253 break
1252 break
1254 # FIXME: we should extend our api to return a dict with completions for
1253 # FIXME: we should extend our api to return a dict with completions for
1255 # different types of objects. The rlcomplete() method could then
1254 # different types of objects. The rlcomplete() method could then
1256 # simply collapse the dict into a list for readline, but we'd have
1255 # simply collapse the dict into a list for readline, but we'd have
1257 # richer completion semantics in other evironments.
1256 # richer completion semantics in other evironments.
1258 self.matches.extend(self.python_jedi_matches(text, line_buffer, cursor_pos))
1257 self.matches.extend(self.python_jedi_matches(text, line_buffer, cursor_pos))
1259
1258
1260 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1259 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1261
1260
1262 return text, self.matches
1261 return text, self.matches
1263
1262
1264 def rlcomplete(self, text, state):
1263 def rlcomplete(self, text, state):
1265 """Return the state-th possible completion for 'text'.
1264 """Return the state-th possible completion for 'text'.
1266
1265
1267 This is called successively with state == 0, 1, 2, ... until it
1266 This is called successively with state == 0, 1, 2, ... until it
1268 returns None. The completion should begin with 'text'.
1267 returns None. The completion should begin with 'text'.
1269
1268
1270 Parameters
1269 Parameters
1271 ----------
1270 ----------
1272 text : string
1271 text : string
1273 Text to perform the completion on.
1272 Text to perform the completion on.
1274
1273
1275 state : int
1274 state : int
1276 Counter used by readline.
1275 Counter used by readline.
1277 """
1276 """
1278 if state==0:
1277 if state==0:
1279
1278
1280 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1279 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1281 cursor_pos = self.readline.get_endidx()
1280 cursor_pos = self.readline.get_endidx()
1282
1281
1283 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1282 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1284 # (text, line_buffer, cursor_pos) ) # dbg
1283 # (text, line_buffer, cursor_pos) ) # dbg
1285
1284
1286 # if there is only a tab on a line with only whitespace, instead of
1285 # if there is only a tab on a line with only whitespace, instead of
1287 # the mostly useless 'do you want to see all million completions'
1286 # the mostly useless 'do you want to see all million completions'
1288 # message, just do the right thing and give the user his tab!
1287 # message, just do the right thing and give the user his tab!
1289 # Incidentally, this enables pasting of tabbed text from an editor
1288 # Incidentally, this enables pasting of tabbed text from an editor
1290 # (as long as autoindent is off).
1289 # (as long as autoindent is off).
1291
1290
1292 # It should be noted that at least pyreadline still shows file
1291 # It should be noted that at least pyreadline still shows file
1293 # completions - is there a way around it?
1292 # completions - is there a way around it?
1294
1293
1295 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1294 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1296 # we don't interfere with their own tab-completion mechanism.
1295 # we don't interfere with their own tab-completion mechanism.
1297 if not (self.dumb_terminal or line_buffer.strip()):
1296 if not (self.dumb_terminal or line_buffer.strip()):
1298 self.readline.insert_text('\t')
1297 self.readline.insert_text('\t')
1299 sys.stdout.flush()
1298 sys.stdout.flush()
1300 return None
1299 return None
1301
1300
1302 # Note: debugging exceptions that may occur in completion is very
1301 # Note: debugging exceptions that may occur in completion is very
1303 # tricky, because readline unconditionally silences them. So if
1302 # tricky, because readline unconditionally silences them. So if
1304 # during development you suspect a bug in the completion code, turn
1303 # during development you suspect a bug in the completion code, turn
1305 # this flag on temporarily by uncommenting the second form (don't
1304 # this flag on temporarily by uncommenting the second form (don't
1306 # flip the value in the first line, as the '# dbg' marker can be
1305 # flip the value in the first line, as the '# dbg' marker can be
1307 # automatically detected and is used elsewhere).
1306 # automatically detected and is used elsewhere).
1308 DEBUG = False
1307 DEBUG = False
1309 #DEBUG = True # dbg
1308 #DEBUG = True # dbg
1310 if DEBUG:
1309 if DEBUG:
1311 try:
1310 try:
1312 self.complete(text, line_buffer, cursor_pos)
1311 self.complete(text, line_buffer, cursor_pos)
1313 except:
1312 except:
1314 import traceback; traceback.print_exc()
1313 import traceback; traceback.print_exc()
1315 else:
1314 else:
1316 # The normal production version is here
1315 # The normal production version is here
1317
1316
1318 # This method computes the self.matches array
1317 # This method computes the self.matches array
1319 self.complete(text, line_buffer, cursor_pos)
1318 self.complete(text, line_buffer, cursor_pos)
1320
1319
1321 try:
1320 try:
1322 return self.matches[state]
1321 return self.matches[state]
1323 except IndexError:
1322 except IndexError:
1324 return None
1323 return None
1325
1324
@@ -1,637 +1,591 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 http://www.python.org/2.2.3/license.html"""
16 http://www.python.org/2.2.3/license.html"""
17
17
18 #*****************************************************************************
18 #*****************************************************************************
19 #
19 #
20 # This file is licensed under the PSF license.
20 # This file is licensed under the PSF license.
21 #
21 #
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 #
24 #
25 #
25 #
26 #*****************************************************************************
26 #*****************************************************************************
27 from __future__ import print_function
27 from __future__ import print_function
28
28
29 import bdb
29 import bdb
30 import functools
30 import functools
31 import inspect
31 import inspect
32 import sys
32 import sys
33
33
34 from IPython import get_ipython
34 from IPython import get_ipython
35 from IPython.utils import PyColorize, ulinecache
35 from IPython.utils import PyColorize, ulinecache
36 from IPython.utils import coloransi, py3compat
36 from IPython.utils import coloransi, py3compat
37 from IPython.core.excolors import exception_colors
37 from IPython.core.excolors import exception_colors
38 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.testing.skipdoctest import skip_doctest
39
39
40 # See if we can use pydb.
41 has_pydb = False
42 prompt = 'ipdb> '
40 prompt = 'ipdb> '
41
43 #We have to check this directly from sys.argv, config struct not yet available
42 #We have to check this directly from sys.argv, config struct not yet available
44 if '--pydb' in sys.argv:
43 from pdb import Pdb as OldPdb
45 try:
46 import pydb
47 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
48 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
49 # better protect against it.
50 has_pydb = True
51 except ImportError:
52 print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available")
53
54 if has_pydb:
55 from pydb import Pdb as OldPdb
56 prompt = 'ipydb> '
57 else:
58 from pdb import Pdb as OldPdb
59
44
60 # Allow the set_trace code to operate outside of an ipython instance, even if
45 # Allow the set_trace code to operate outside of an ipython instance, even if
61 # it does so with some limitations. The rest of this support is implemented in
46 # it does so with some limitations. The rest of this support is implemented in
62 # the Tracer constructor.
47 # the Tracer constructor.
63
48
64 def make_arrow(pad):
49 def make_arrow(pad):
65 """generate the leading arrow in front of traceback or debugger"""
50 """generate the leading arrow in front of traceback or debugger"""
66 if pad >= 2:
51 if pad >= 2:
67 return '-'*(pad-2) + '> '
52 return '-'*(pad-2) + '> '
68 elif pad == 1:
53 elif pad == 1:
69 return '>'
54 return '>'
70 return ''
55 return ''
71
56
72
57
73 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
58 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
74 """Exception hook which handles `BdbQuit` exceptions.
59 """Exception hook which handles `BdbQuit` exceptions.
75
60
76 All other exceptions are processed using the `excepthook`
61 All other exceptions are processed using the `excepthook`
77 parameter.
62 parameter.
78 """
63 """
79 if et==bdb.BdbQuit:
64 if et==bdb.BdbQuit:
80 print('Exiting Debugger.')
65 print('Exiting Debugger.')
81 elif excepthook is not None:
66 elif excepthook is not None:
82 excepthook(et, ev, tb)
67 excepthook(et, ev, tb)
83 else:
68 else:
84 # Backwards compatibility. Raise deprecation warning?
69 # Backwards compatibility. Raise deprecation warning?
85 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
70 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
86
71
87 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
72 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
88 print('Exiting Debugger.')
73 print('Exiting Debugger.')
89
74
90
75
91 class Tracer(object):
76 class Tracer(object):
92 """Class for local debugging, similar to pdb.set_trace.
77 """Class for local debugging, similar to pdb.set_trace.
93
78
94 Instances of this class, when called, behave like pdb.set_trace, but
79 Instances of this class, when called, behave like pdb.set_trace, but
95 providing IPython's enhanced capabilities.
80 providing IPython's enhanced capabilities.
96
81
97 This is implemented as a class which must be initialized in your own code
82 This is implemented as a class which must be initialized in your own code
98 and not as a standalone function because we need to detect at runtime
83 and not as a standalone function because we need to detect at runtime
99 whether IPython is already active or not. That detection is done in the
84 whether IPython is already active or not. That detection is done in the
100 constructor, ensuring that this code plays nicely with a running IPython,
85 constructor, ensuring that this code plays nicely with a running IPython,
101 while functioning acceptably (though with limitations) if outside of it.
86 while functioning acceptably (though with limitations) if outside of it.
102 """
87 """
103
88
104 @skip_doctest
89 @skip_doctest
105 def __init__(self, colors=None):
90 def __init__(self, colors=None):
106 """Create a local debugger instance.
91 """Create a local debugger instance.
107
92
108 Parameters
93 Parameters
109 ----------
94 ----------
110
95
111 colors : str, optional
96 colors : str, optional
112 The name of the color scheme to use, it must be one of IPython's
97 The name of the color scheme to use, it must be one of IPython's
113 valid color schemes. If not given, the function will default to
98 valid color schemes. If not given, the function will default to
114 the current IPython scheme when running inside IPython, and to
99 the current IPython scheme when running inside IPython, and to
115 'NoColor' otherwise.
100 'NoColor' otherwise.
116
101
117 Examples
102 Examples
118 --------
103 --------
119 ::
104 ::
120
105
121 from IPython.core.debugger import Tracer; debug_here = Tracer()
106 from IPython.core.debugger import Tracer; debug_here = Tracer()
122
107
123 Later in your code::
108 Later in your code::
124
109
125 debug_here() # -> will open up the debugger at that point.
110 debug_here() # -> will open up the debugger at that point.
126
111
127 Once the debugger activates, you can use all of its regular commands to
112 Once the debugger activates, you can use all of its regular commands to
128 step through code, set breakpoints, etc. See the pdb documentation
113 step through code, set breakpoints, etc. See the pdb documentation
129 from the Python standard library for usage details.
114 from the Python standard library for usage details.
130 """
115 """
131
116
132 ip = get_ipython()
117 ip = get_ipython()
133 if ip is None:
118 if ip is None:
134 # Outside of ipython, we set our own exception hook manually
119 # Outside of ipython, we set our own exception hook manually
135 sys.excepthook = functools.partial(BdbQuit_excepthook,
120 sys.excepthook = functools.partial(BdbQuit_excepthook,
136 excepthook=sys.excepthook)
121 excepthook=sys.excepthook)
137 def_colors = 'NoColor'
122 def_colors = 'NoColor'
138 try:
123 try:
139 # Limited tab completion support
124 # Limited tab completion support
140 import readline
125 import readline
141 readline.parse_and_bind('tab: complete')
126 readline.parse_and_bind('tab: complete')
142 except ImportError:
127 except ImportError:
143 pass
128 pass
144 else:
129 else:
145 # In ipython, we use its custom exception handler mechanism
130 # In ipython, we use its custom exception handler mechanism
146 def_colors = ip.colors
131 def_colors = ip.colors
147 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
132 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
148
133
149 if colors is None:
134 if colors is None:
150 colors = def_colors
135 colors = def_colors
151
136
152 # The stdlib debugger internally uses a modified repr from the `repr`
137 # The stdlib debugger internally uses a modified repr from the `repr`
153 # module, that limits the length of printed strings to a hardcoded
138 # module, that limits the length of printed strings to a hardcoded
154 # limit of 30 characters. That much trimming is too aggressive, let's
139 # limit of 30 characters. That much trimming is too aggressive, let's
155 # at least raise that limit to 80 chars, which should be enough for
140 # at least raise that limit to 80 chars, which should be enough for
156 # most interactive uses.
141 # most interactive uses.
157 try:
142 try:
158 try:
143 try:
159 from reprlib import aRepr # Py 3
144 from reprlib import aRepr # Py 3
160 except ImportError:
145 except ImportError:
161 from repr import aRepr # Py 2
146 from repr import aRepr # Py 2
162 aRepr.maxstring = 80
147 aRepr.maxstring = 80
163 except:
148 except:
164 # This is only a user-facing convenience, so any error we encounter
149 # This is only a user-facing convenience, so any error we encounter
165 # here can be warned about but can be otherwise ignored. These
150 # here can be warned about but can be otherwise ignored. These
166 # printouts will tell us about problems if this API changes
151 # printouts will tell us about problems if this API changes
167 import traceback
152 import traceback
168 traceback.print_exc()
153 traceback.print_exc()
169
154
170 self.debugger = Pdb(colors)
155 self.debugger = Pdb(colors)
171
156
172 def __call__(self):
157 def __call__(self):
173 """Starts an interactive debugger at the point where called.
158 """Starts an interactive debugger at the point where called.
174
159
175 This is similar to the pdb.set_trace() function from the std lib, but
160 This is similar to the pdb.set_trace() function from the std lib, but
176 using IPython's enhanced debugger."""
161 using IPython's enhanced debugger."""
177
162
178 self.debugger.set_trace(sys._getframe().f_back)
163 self.debugger.set_trace(sys._getframe().f_back)
179
164
180
165
181 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
166 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
182 """Make new_fn have old_fn's doc string. This is particularly useful
167 """Make new_fn have old_fn's doc string. This is particularly useful
183 for the ``do_...`` commands that hook into the help system.
168 for the ``do_...`` commands that hook into the help system.
184 Adapted from from a comp.lang.python posting
169 Adapted from from a comp.lang.python posting
185 by Duncan Booth."""
170 by Duncan Booth."""
186 def wrapper(*args, **kw):
171 def wrapper(*args, **kw):
187 return new_fn(*args, **kw)
172 return new_fn(*args, **kw)
188 if old_fn.__doc__:
173 if old_fn.__doc__:
189 wrapper.__doc__ = old_fn.__doc__ + additional_text
174 wrapper.__doc__ = old_fn.__doc__ + additional_text
190 return wrapper
175 return wrapper
191
176
192
177
193 def _file_lines(fname):
178 def _file_lines(fname):
194 """Return the contents of a named file as a list of lines.
179 """Return the contents of a named file as a list of lines.
195
180
196 This function never raises an IOError exception: if the file can't be
181 This function never raises an IOError exception: if the file can't be
197 read, it simply returns an empty list."""
182 read, it simply returns an empty list."""
198
183
199 try:
184 try:
200 outfile = open(fname)
185 outfile = open(fname)
201 except IOError:
186 except IOError:
202 return []
187 return []
203 else:
188 else:
204 out = outfile.readlines()
189 out = outfile.readlines()
205 outfile.close()
190 outfile.close()
206 return out
191 return out
207
192
208
193
209 class Pdb(OldPdb):
194 class Pdb(OldPdb):
210 """Modified Pdb class, does not load readline."""
195 """Modified Pdb class, does not load readline."""
211
196
212 def __init__(self,color_scheme='NoColor',completekey=None,
197 def __init__(self,color_scheme='NoColor',completekey=None,
213 stdin=None, stdout=None, context=5):
198 stdin=None, stdout=None, context=5):
214
199
215 # Parent constructor:
200 # Parent constructor:
216 try:
201 try:
217 self.context=int(context)
202 self.context=int(context)
218 if self.context <= 0:
203 if self.context <= 0:
219 raise ValueError("Context must be a positive integer")
204 raise ValueError("Context must be a positive integer")
220 except (TypeError, ValueError):
205 except (TypeError, ValueError):
221 raise ValueError("Context must be a positive integer")
206 raise ValueError("Context must be a positive integer")
222
207
223 if has_pydb and completekey is None:
208 OldPdb.__init__(self,completekey,stdin,stdout)
224 OldPdb.__init__(self,stdin=stdin,stdout=sys.stdout)
225 else:
226 OldPdb.__init__(self,completekey,stdin,stdout)
227
209
228 # IPython changes...
210 # IPython changes...
229 self.is_pydb = has_pydb
230
231 self.shell = get_ipython()
211 self.shell = get_ipython()
232
212
233 if self.shell is None:
213 if self.shell is None:
234 # No IPython instance running, we must create one
214 # No IPython instance running, we must create one
235 from IPython.terminal.interactiveshell import \
215 from IPython.terminal.interactiveshell import \
236 TerminalInteractiveShell
216 TerminalInteractiveShell
237 self.shell = TerminalInteractiveShell.instance()
217 self.shell = TerminalInteractiveShell.instance()
238
218
239 if self.is_pydb:
240
241 # interactiveshell.py's ipalias seems to want pdb's checkline
242 # which located in pydb.fn
243 import pydb.fns
244 self.checkline = lambda filename, lineno: \
245 pydb.fns.checkline(self, filename, lineno)
246
247 self.curframe = None
248 self.do_restart = self.new_do_restart
249
250 self.old_all_completions = self.shell.Completer.all_completions
251 self.shell.Completer.all_completions=self.all_completions
252
253 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
254 OldPdb.do_list)
255 self.do_l = self.do_list
256 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
257 OldPdb.do_frame)
258
259 self.aliases = {}
219 self.aliases = {}
260
220
261 # Create color table: we copy the default one from the traceback
221 # Create color table: we copy the default one from the traceback
262 # module and add a few attributes needed for debugging
222 # module and add a few attributes needed for debugging
263 self.color_scheme_table = exception_colors()
223 self.color_scheme_table = exception_colors()
264
224
265 # shorthands
225 # shorthands
266 C = coloransi.TermColors
226 C = coloransi.TermColors
267 cst = self.color_scheme_table
227 cst = self.color_scheme_table
268
228
269 cst['NoColor'].colors.prompt = C.NoColor
229 cst['NoColor'].colors.prompt = C.NoColor
270 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
230 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
271 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
231 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
272
232
273 cst['Linux'].colors.prompt = C.Green
233 cst['Linux'].colors.prompt = C.Green
274 cst['Linux'].colors.breakpoint_enabled = C.LightRed
234 cst['Linux'].colors.breakpoint_enabled = C.LightRed
275 cst['Linux'].colors.breakpoint_disabled = C.Red
235 cst['Linux'].colors.breakpoint_disabled = C.Red
276
236
277 cst['LightBG'].colors.prompt = C.Blue
237 cst['LightBG'].colors.prompt = C.Blue
278 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
238 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
279 cst['LightBG'].colors.breakpoint_disabled = C.Red
239 cst['LightBG'].colors.breakpoint_disabled = C.Red
280
240
281 self.set_colors(color_scheme)
241 self.set_colors(color_scheme)
282
242
283 # Add a python parser so we can syntax highlight source while
243 # Add a python parser so we can syntax highlight source while
284 # debugging.
244 # debugging.
285 self.parser = PyColorize.Parser()
245 self.parser = PyColorize.Parser()
286
246
287 # Set the prompt - the default prompt is '(Pdb)'
247 # Set the prompt - the default prompt is '(Pdb)'
288 Colors = cst.active_colors
248 Colors = cst.active_colors
289 if color_scheme == 'NoColor':
249 if color_scheme == 'NoColor':
290 self.prompt = prompt
250 self.prompt = prompt
291 else:
251 else:
292 # The colour markers are wrapped by bytes 01 and 02 so that readline
252 # The colour markers are wrapped by bytes 01 and 02 so that readline
293 # can calculate the width.
253 # can calculate the width.
294 self.prompt = u'\x01%s\x02%s\x01%s\x02' % (Colors.prompt, prompt, Colors.Normal)
254 self.prompt = u'\x01%s\x02%s\x01%s\x02' % (Colors.prompt, prompt, Colors.Normal)
295
255
296 def set_colors(self, scheme):
256 def set_colors(self, scheme):
297 """Shorthand access to the color table scheme selector method."""
257 """Shorthand access to the color table scheme selector method."""
298 self.color_scheme_table.set_active_scheme(scheme)
258 self.color_scheme_table.set_active_scheme(scheme)
299
259
300 def interaction(self, frame, traceback):
260 def interaction(self, frame, traceback):
301 self.shell.set_completer_frame(frame)
261 self.shell.set_completer_frame(frame)
302 while True:
262 while True:
303 try:
263 try:
304 OldPdb.interaction(self, frame, traceback)
264 OldPdb.interaction(self, frame, traceback)
305 break
265 break
306 except KeyboardInterrupt:
266 except KeyboardInterrupt:
307 self.shell.write('\n' + self.shell.get_exception_only())
267 self.shell.write('\n' + self.shell.get_exception_only())
308 break
268 break
309 finally:
269 finally:
310 # Pdb sets readline delimiters, so set them back to our own
270 # Pdb sets readline delimiters, so set them back to our own
311 if self.shell.readline is not None:
271 if self.shell.readline is not None:
312 self.shell.readline.set_completer_delims(self.shell.readline_delims)
272 self.shell.readline.set_completer_delims(self.shell.readline_delims)
313
273
314 def new_do_up(self, arg):
274 def new_do_up(self, arg):
315 OldPdb.do_up(self, arg)
275 OldPdb.do_up(self, arg)
316 self.shell.set_completer_frame(self.curframe)
276 self.shell.set_completer_frame(self.curframe)
317 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
277 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
318
278
319 def new_do_down(self, arg):
279 def new_do_down(self, arg):
320 OldPdb.do_down(self, arg)
280 OldPdb.do_down(self, arg)
321 self.shell.set_completer_frame(self.curframe)
281 self.shell.set_completer_frame(self.curframe)
322
282
323 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
283 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
324
284
325 def new_do_frame(self, arg):
285 def new_do_frame(self, arg):
326 OldPdb.do_frame(self, arg)
286 OldPdb.do_frame(self, arg)
327 self.shell.set_completer_frame(self.curframe)
287 self.shell.set_completer_frame(self.curframe)
328
288
329 def new_do_quit(self, arg):
289 def new_do_quit(self, arg):
330
290
331 if hasattr(self, 'old_all_completions'):
291 if hasattr(self, 'old_all_completions'):
332 self.shell.Completer.all_completions=self.old_all_completions
292 self.shell.Completer.all_completions=self.old_all_completions
333
293
334 return OldPdb.do_quit(self, arg)
294 return OldPdb.do_quit(self, arg)
335
295
336 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
296 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
337
297
338 def new_do_restart(self, arg):
298 def new_do_restart(self, arg):
339 """Restart command. In the context of ipython this is exactly the same
299 """Restart command. In the context of ipython this is exactly the same
340 thing as 'quit'."""
300 thing as 'quit'."""
341 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
301 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
342 return self.do_quit(arg)
302 return self.do_quit(arg)
343
303
344 def postloop(self):
304 def postloop(self):
345 self.shell.set_completer_frame(None)
305 self.shell.set_completer_frame(None)
346
306
347 def print_stack_trace(self, context=None):
307 def print_stack_trace(self, context=None):
348 if context is None:
308 if context is None:
349 context = self.context
309 context = self.context
350 try:
310 try:
351 context=int(context)
311 context=int(context)
352 if context <= 0:
312 if context <= 0:
353 raise ValueError("Context must be a positive integer")
313 raise ValueError("Context must be a positive integer")
354 except (TypeError, ValueError):
314 except (TypeError, ValueError):
355 raise ValueError("Context must be a positive integer")
315 raise ValueError("Context must be a positive integer")
356 try:
316 try:
357 for frame_lineno in self.stack:
317 for frame_lineno in self.stack:
358 self.print_stack_entry(frame_lineno, context=context)
318 self.print_stack_entry(frame_lineno, context=context)
359 except KeyboardInterrupt:
319 except KeyboardInterrupt:
360 pass
320 pass
361
321
362 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
322 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
363 context=None):
323 context=None):
364 if context is None:
324 if context is None:
365 context = self.context
325 context = self.context
366 try:
326 try:
367 context=int(context)
327 context=int(context)
368 if context <= 0:
328 if context <= 0:
369 raise ValueError("Context must be a positive integer")
329 raise ValueError("Context must be a positive integer")
370 except (TypeError, ValueError):
330 except (TypeError, ValueError):
371 raise ValueError("Context must be a positive integer")
331 raise ValueError("Context must be a positive integer")
372 print(self.format_stack_entry(frame_lineno, '', context))
332 print(self.format_stack_entry(frame_lineno, '', context))
373
333
374 # vds: >>
334 # vds: >>
375 frame, lineno = frame_lineno
335 frame, lineno = frame_lineno
376 filename = frame.f_code.co_filename
336 filename = frame.f_code.co_filename
377 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
337 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
378 # vds: <<
338 # vds: <<
379
339
380 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
340 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
381 if context is None:
341 if context is None:
382 context = self.context
342 context = self.context
383 try:
343 try:
384 context=int(context)
344 context=int(context)
385 if context <= 0:
345 if context <= 0:
386 print("Context must be a positive integer")
346 print("Context must be a positive integer")
387 except (TypeError, ValueError):
347 except (TypeError, ValueError):
388 print("Context must be a positive integer")
348 print("Context must be a positive integer")
389 try:
349 try:
390 import reprlib # Py 3
350 import reprlib # Py 3
391 except ImportError:
351 except ImportError:
392 import repr as reprlib # Py 2
352 import repr as reprlib # Py 2
393
353
394 ret = []
354 ret = []
395
355
396 Colors = self.color_scheme_table.active_colors
356 Colors = self.color_scheme_table.active_colors
397 ColorsNormal = Colors.Normal
357 ColorsNormal = Colors.Normal
398 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
358 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
399 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
359 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
400 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
360 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
401 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
361 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
402 ColorsNormal)
362 ColorsNormal)
403
363
404 frame, lineno = frame_lineno
364 frame, lineno = frame_lineno
405
365
406 return_value = ''
366 return_value = ''
407 if '__return__' in frame.f_locals:
367 if '__return__' in frame.f_locals:
408 rv = frame.f_locals['__return__']
368 rv = frame.f_locals['__return__']
409 #return_value += '->'
369 #return_value += '->'
410 return_value += reprlib.repr(rv) + '\n'
370 return_value += reprlib.repr(rv) + '\n'
411 ret.append(return_value)
371 ret.append(return_value)
412
372
413 #s = filename + '(' + `lineno` + ')'
373 #s = filename + '(' + `lineno` + ')'
414 filename = self.canonic(frame.f_code.co_filename)
374 filename = self.canonic(frame.f_code.co_filename)
415 link = tpl_link % py3compat.cast_unicode(filename)
375 link = tpl_link % py3compat.cast_unicode(filename)
416
376
417 if frame.f_code.co_name:
377 if frame.f_code.co_name:
418 func = frame.f_code.co_name
378 func = frame.f_code.co_name
419 else:
379 else:
420 func = "<lambda>"
380 func = "<lambda>"
421
381
422 call = ''
382 call = ''
423 if func != '?':
383 if func != '?':
424 if '__args__' in frame.f_locals:
384 if '__args__' in frame.f_locals:
425 args = reprlib.repr(frame.f_locals['__args__'])
385 args = reprlib.repr(frame.f_locals['__args__'])
426 else:
386 else:
427 args = '()'
387 args = '()'
428 call = tpl_call % (func, args)
388 call = tpl_call % (func, args)
429
389
430 # The level info should be generated in the same format pdb uses, to
390 # The level info should be generated in the same format pdb uses, to
431 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
391 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
432 if frame is self.curframe:
392 if frame is self.curframe:
433 ret.append('> ')
393 ret.append('> ')
434 else:
394 else:
435 ret.append(' ')
395 ret.append(' ')
436 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
396 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
437
397
438 start = lineno - 1 - context//2
398 start = lineno - 1 - context//2
439 lines = ulinecache.getlines(filename)
399 lines = ulinecache.getlines(filename)
440 start = min(start, len(lines) - context)
400 start = min(start, len(lines) - context)
441 start = max(start, 0)
401 start = max(start, 0)
442 lines = lines[start : start + context]
402 lines = lines[start : start + context]
443
403
444 for i,line in enumerate(lines):
404 for i,line in enumerate(lines):
445 show_arrow = (start + 1 + i == lineno)
405 show_arrow = (start + 1 + i == lineno)
446 linetpl = (frame is self.curframe or show_arrow) \
406 linetpl = (frame is self.curframe or show_arrow) \
447 and tpl_line_em \
407 and tpl_line_em \
448 or tpl_line
408 or tpl_line
449 ret.append(self.__format_line(linetpl, filename,
409 ret.append(self.__format_line(linetpl, filename,
450 start + 1 + i, line,
410 start + 1 + i, line,
451 arrow = show_arrow) )
411 arrow = show_arrow) )
452 return ''.join(ret)
412 return ''.join(ret)
453
413
454 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
414 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
455 bp_mark = ""
415 bp_mark = ""
456 bp_mark_color = ""
416 bp_mark_color = ""
457
417
458 scheme = self.color_scheme_table.active_scheme_name
418 scheme = self.color_scheme_table.active_scheme_name
459 new_line, err = self.parser.format2(line, 'str', scheme)
419 new_line, err = self.parser.format2(line, 'str', scheme)
460 if not err: line = new_line
420 if not err: line = new_line
461
421
462 bp = None
422 bp = None
463 if lineno in self.get_file_breaks(filename):
423 if lineno in self.get_file_breaks(filename):
464 bps = self.get_breaks(filename, lineno)
424 bps = self.get_breaks(filename, lineno)
465 bp = bps[-1]
425 bp = bps[-1]
466
426
467 if bp:
427 if bp:
468 Colors = self.color_scheme_table.active_colors
428 Colors = self.color_scheme_table.active_colors
469 bp_mark = str(bp.number)
429 bp_mark = str(bp.number)
470 bp_mark_color = Colors.breakpoint_enabled
430 bp_mark_color = Colors.breakpoint_enabled
471 if not bp.enabled:
431 if not bp.enabled:
472 bp_mark_color = Colors.breakpoint_disabled
432 bp_mark_color = Colors.breakpoint_disabled
473
433
474 numbers_width = 7
434 numbers_width = 7
475 if arrow:
435 if arrow:
476 # This is the line with the error
436 # This is the line with the error
477 pad = numbers_width - len(str(lineno)) - len(bp_mark)
437 pad = numbers_width - len(str(lineno)) - len(bp_mark)
478 num = '%s%s' % (make_arrow(pad), str(lineno))
438 num = '%s%s' % (make_arrow(pad), str(lineno))
479 else:
439 else:
480 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
440 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
481
441
482 return tpl_line % (bp_mark_color + bp_mark, num, line)
442 return tpl_line % (bp_mark_color + bp_mark, num, line)
483
443
484
444
485 def list_command_pydb(self, arg):
486 """List command to use if we have a newer pydb installed"""
487 filename, first, last = OldPdb.parse_list_cmd(self, arg)
488 if filename is not None:
489 self.print_list_lines(filename, first, last)
490
491 def print_list_lines(self, filename, first, last):
445 def print_list_lines(self, filename, first, last):
492 """The printing (as opposed to the parsing part of a 'list'
446 """The printing (as opposed to the parsing part of a 'list'
493 command."""
447 command."""
494 try:
448 try:
495 Colors = self.color_scheme_table.active_colors
449 Colors = self.color_scheme_table.active_colors
496 ColorsNormal = Colors.Normal
450 ColorsNormal = Colors.Normal
497 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
451 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
498 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
452 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
499 src = []
453 src = []
500 if filename == "<string>" and hasattr(self, "_exec_filename"):
454 if filename == "<string>" and hasattr(self, "_exec_filename"):
501 filename = self._exec_filename
455 filename = self._exec_filename
502
456
503 for lineno in range(first, last+1):
457 for lineno in range(first, last+1):
504 line = ulinecache.getline(filename, lineno)
458 line = ulinecache.getline(filename, lineno)
505 if not line:
459 if not line:
506 break
460 break
507
461
508 if lineno == self.curframe.f_lineno:
462 if lineno == self.curframe.f_lineno:
509 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
463 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
510 else:
464 else:
511 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
465 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
512
466
513 src.append(line)
467 src.append(line)
514 self.lineno = lineno
468 self.lineno = lineno
515
469
516 print(''.join(src))
470 print(''.join(src))
517
471
518 except KeyboardInterrupt:
472 except KeyboardInterrupt:
519 pass
473 pass
520
474
521 def do_list(self, arg):
475 def do_list(self, arg):
522 self.lastcmd = 'list'
476 self.lastcmd = 'list'
523 last = None
477 last = None
524 if arg:
478 if arg:
525 try:
479 try:
526 x = eval(arg, {}, {})
480 x = eval(arg, {}, {})
527 if type(x) == type(()):
481 if type(x) == type(()):
528 first, last = x
482 first, last = x
529 first = int(first)
483 first = int(first)
530 last = int(last)
484 last = int(last)
531 if last < first:
485 if last < first:
532 # Assume it's a count
486 # Assume it's a count
533 last = first + last
487 last = first + last
534 else:
488 else:
535 first = max(1, int(x) - 5)
489 first = max(1, int(x) - 5)
536 except:
490 except:
537 print('*** Error in argument:', repr(arg))
491 print('*** Error in argument:', repr(arg))
538 return
492 return
539 elif self.lineno is None:
493 elif self.lineno is None:
540 first = max(1, self.curframe.f_lineno - 5)
494 first = max(1, self.curframe.f_lineno - 5)
541 else:
495 else:
542 first = self.lineno + 1
496 first = self.lineno + 1
543 if last is None:
497 if last is None:
544 last = first + 10
498 last = first + 10
545 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
499 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
546
500
547 # vds: >>
501 # vds: >>
548 lineno = first
502 lineno = first
549 filename = self.curframe.f_code.co_filename
503 filename = self.curframe.f_code.co_filename
550 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
504 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
551 # vds: <<
505 # vds: <<
552
506
553 do_l = do_list
507 do_l = do_list
554
508
555 def getsourcelines(self, obj):
509 def getsourcelines(self, obj):
556 lines, lineno = inspect.findsource(obj)
510 lines, lineno = inspect.findsource(obj)
557 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
511 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
558 # must be a module frame: do not try to cut a block out of it
512 # must be a module frame: do not try to cut a block out of it
559 return lines, 1
513 return lines, 1
560 elif inspect.ismodule(obj):
514 elif inspect.ismodule(obj):
561 return lines, 1
515 return lines, 1
562 return inspect.getblock(lines[lineno:]), lineno+1
516 return inspect.getblock(lines[lineno:]), lineno+1
563
517
564 def do_longlist(self, arg):
518 def do_longlist(self, arg):
565 self.lastcmd = 'longlist'
519 self.lastcmd = 'longlist'
566 try:
520 try:
567 lines, lineno = self.getsourcelines(self.curframe)
521 lines, lineno = self.getsourcelines(self.curframe)
568 except OSError as err:
522 except OSError as err:
569 self.error(err)
523 self.error(err)
570 return
524 return
571 last = lineno + len(lines)
525 last = lineno + len(lines)
572 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
526 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
573 do_ll = do_longlist
527 do_ll = do_longlist
574
528
575 def do_pdef(self, arg):
529 def do_pdef(self, arg):
576 """Print the call signature for any callable object.
530 """Print the call signature for any callable object.
577
531
578 The debugger interface to %pdef"""
532 The debugger interface to %pdef"""
579 namespaces = [('Locals', self.curframe.f_locals),
533 namespaces = [('Locals', self.curframe.f_locals),
580 ('Globals', self.curframe.f_globals)]
534 ('Globals', self.curframe.f_globals)]
581 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
535 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
582
536
583 def do_pdoc(self, arg):
537 def do_pdoc(self, arg):
584 """Print the docstring for an object.
538 """Print the docstring for an object.
585
539
586 The debugger interface to %pdoc."""
540 The debugger interface to %pdoc."""
587 namespaces = [('Locals', self.curframe.f_locals),
541 namespaces = [('Locals', self.curframe.f_locals),
588 ('Globals', self.curframe.f_globals)]
542 ('Globals', self.curframe.f_globals)]
589 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
543 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
590
544
591 def do_pfile(self, arg):
545 def do_pfile(self, arg):
592 """Print (or run through pager) the file where an object is defined.
546 """Print (or run through pager) the file where an object is defined.
593
547
594 The debugger interface to %pfile.
548 The debugger interface to %pfile.
595 """
549 """
596 namespaces = [('Locals', self.curframe.f_locals),
550 namespaces = [('Locals', self.curframe.f_locals),
597 ('Globals', self.curframe.f_globals)]
551 ('Globals', self.curframe.f_globals)]
598 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
552 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
599
553
600 def do_pinfo(self, arg):
554 def do_pinfo(self, arg):
601 """Provide detailed information about an object.
555 """Provide detailed information about an object.
602
556
603 The debugger interface to %pinfo, i.e., obj?."""
557 The debugger interface to %pinfo, i.e., obj?."""
604 namespaces = [('Locals', self.curframe.f_locals),
558 namespaces = [('Locals', self.curframe.f_locals),
605 ('Globals', self.curframe.f_globals)]
559 ('Globals', self.curframe.f_globals)]
606 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
560 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
607
561
608 def do_pinfo2(self, arg):
562 def do_pinfo2(self, arg):
609 """Provide extra detailed information about an object.
563 """Provide extra detailed information about an object.
610
564
611 The debugger interface to %pinfo2, i.e., obj??."""
565 The debugger interface to %pinfo2, i.e., obj??."""
612 namespaces = [('Locals', self.curframe.f_locals),
566 namespaces = [('Locals', self.curframe.f_locals),
613 ('Globals', self.curframe.f_globals)]
567 ('Globals', self.curframe.f_globals)]
614 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
568 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
615
569
616 def do_psource(self, arg):
570 def do_psource(self, arg):
617 """Print (or run through pager) the source code for an object."""
571 """Print (or run through pager) the source code for an object."""
618 namespaces = [('Locals', self.curframe.f_locals),
572 namespaces = [('Locals', self.curframe.f_locals),
619 ('Globals', self.curframe.f_globals)]
573 ('Globals', self.curframe.f_globals)]
620 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
574 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
621
575
622 if sys.version_info > (3, ):
576 if sys.version_info > (3, ):
623 def do_where(self, arg):
577 def do_where(self, arg):
624 """w(here)
578 """w(here)
625 Print a stack trace, with the most recent frame at the bottom.
579 Print a stack trace, with the most recent frame at the bottom.
626 An arrow indicates the "current frame", which determines the
580 An arrow indicates the "current frame", which determines the
627 context of most commands. 'bt' is an alias for this command.
581 context of most commands. 'bt' is an alias for this command.
628
582
629 Take a number as argument as an (optional) number of context line to
583 Take a number as argument as an (optional) number of context line to
630 print"""
584 print"""
631 if arg:
585 if arg:
632 context = int(arg)
586 context = int(arg)
633 self.print_stack_trace(context)
587 self.print_stack_trace(context)
634 else:
588 else:
635 self.print_stack_trace()
589 self.print_stack_trace()
636
590
637 do_w = do_where
591 do_w = do_where
@@ -1,3246 +1,3240 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 from __future__ import absolute_import, print_function
13 from __future__ import absolute_import, print_function
14
14
15 import __future__
15 import __future__
16 import abc
16 import abc
17 import ast
17 import ast
18 import atexit
18 import atexit
19 import functools
19 import functools
20 import os
20 import os
21 import re
21 import re
22 import runpy
22 import runpy
23 import sys
23 import sys
24 import tempfile
24 import tempfile
25 import traceback
25 import traceback
26 import types
26 import types
27 import subprocess
27 import subprocess
28 import warnings
28 import warnings
29 from io import open as io_open
29 from io import open as io_open
30
30
31 from pickleshare import PickleShareDB
31 from pickleshare import PickleShareDB
32
32
33 from traitlets.config.configurable import SingletonConfigurable
33 from traitlets.config.configurable import SingletonConfigurable
34 from IPython.core import debugger, oinspect
34 from IPython.core import oinspect
35 from IPython.core import magic
35 from IPython.core import magic
36 from IPython.core import page
36 from IPython.core import page
37 from IPython.core import prefilter
37 from IPython.core import prefilter
38 from IPython.core import shadowns
38 from IPython.core import shadowns
39 from IPython.core import ultratb
39 from IPython.core import ultratb
40 from IPython.core.alias import Alias, AliasManager
40 from IPython.core.alias import Alias, AliasManager
41 from IPython.core.autocall import ExitAutocall
41 from IPython.core.autocall import ExitAutocall
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.events import EventManager, available_events
43 from IPython.core.events import EventManager, available_events
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 InputRejected, UsageError
48 from IPython.core.error import InputRejected, 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 ESC_MAGIC, ESC_MAGIC2
52 from IPython.core.inputsplitter import 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.core.usage import default_banner
59 from IPython.core.usage import default_banner
60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest_py2, 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.contexts import NoOpContext
65 from IPython.utils.contexts import NoOpContext
66 from IPython.utils.decorators import undoc
66 from IPython.utils.decorators import undoc
67 from IPython.utils.io import ask_yes_no
67 from IPython.utils.io import ask_yes_no
68 from IPython.utils.ipstruct import Struct
68 from IPython.utils.ipstruct import Struct
69 from IPython.paths import get_ipython_dir
69 from IPython.paths import get_ipython_dir
70 from IPython.utils.path import get_home_dir, get_py_filename, unquote_filename, ensure_dir_exists
70 from IPython.utils.path import get_home_dir, get_py_filename, unquote_filename, ensure_dir_exists
71 from IPython.utils.process import system, getoutput
71 from IPython.utils.process import system, getoutput
72 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
73 with_metaclass, iteritems)
73 with_metaclass, iteritems)
74 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.strdispatch import StrDispatch
75 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.syspathcontext import prepended_to_syspath
76 from IPython.utils.text import (format_screen, LSString, SList,
76 from IPython.utils.text import (format_screen, LSString, SList,
77 DollarFormatter)
77 DollarFormatter)
78 from traitlets import (
78 from traitlets import (
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
80 observe, default,
80 observe, default,
81 )
81 )
82 from warnings import warn
82 from warnings import warn
83 from logging import error
83 from logging import error
84 import IPython.core.hooks
84 import IPython.core.hooks
85
85
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87 # Globals
87 # Globals
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89
89
90 # compiled regexps for autoindent management
90 # compiled regexps for autoindent management
91 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
91 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
92
92
93 #-----------------------------------------------------------------------------
93 #-----------------------------------------------------------------------------
94 # Utilities
94 # Utilities
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96
96
97 @undoc
97 @undoc
98 def softspace(file, newvalue):
98 def softspace(file, newvalue):
99 """Copied from code.py, to remove the dependency"""
99 """Copied from code.py, to remove the dependency"""
100
100
101 oldvalue = 0
101 oldvalue = 0
102 try:
102 try:
103 oldvalue = file.softspace
103 oldvalue = file.softspace
104 except AttributeError:
104 except AttributeError:
105 pass
105 pass
106 try:
106 try:
107 file.softspace = newvalue
107 file.softspace = newvalue
108 except (AttributeError, TypeError):
108 except (AttributeError, TypeError):
109 # "attribute-less object" or "read-only attributes"
109 # "attribute-less object" or "read-only attributes"
110 pass
110 pass
111 return oldvalue
111 return oldvalue
112
112
113 @undoc
113 @undoc
114 def no_op(*a, **kw): pass
114 def no_op(*a, **kw): pass
115
115
116
116
117 class SpaceInInput(Exception): pass
117 class SpaceInInput(Exception): pass
118
118
119
119
120 def get_default_colors():
120 def get_default_colors():
121 if sys.platform=='darwin':
121 if sys.platform=='darwin':
122 return "LightBG"
122 return "LightBG"
123 elif os.name=='nt':
123 elif os.name=='nt':
124 return 'Linux'
124 return 'Linux'
125 else:
125 else:
126 return 'Linux'
126 return 'Linux'
127
127
128
128
129 class SeparateUnicode(Unicode):
129 class SeparateUnicode(Unicode):
130 r"""A Unicode subclass to validate separate_in, separate_out, etc.
130 r"""A Unicode subclass to validate separate_in, separate_out, etc.
131
131
132 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
132 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
133 """
133 """
134
134
135 def validate(self, obj, value):
135 def validate(self, obj, value):
136 if value == '0': value = ''
136 if value == '0': value = ''
137 value = value.replace('\\n','\n')
137 value = value.replace('\\n','\n')
138 return super(SeparateUnicode, self).validate(obj, value)
138 return super(SeparateUnicode, self).validate(obj, value)
139
139
140
140
141 @undoc
141 @undoc
142 class DummyMod(object):
142 class DummyMod(object):
143 """A dummy module used for IPython's interactive module when
143 """A dummy module used for IPython's interactive module when
144 a namespace must be assigned to the module's __dict__."""
144 a namespace must be assigned to the module's __dict__."""
145 pass
145 pass
146
146
147
147
148 class ExecutionResult(object):
148 class ExecutionResult(object):
149 """The result of a call to :meth:`InteractiveShell.run_cell`
149 """The result of a call to :meth:`InteractiveShell.run_cell`
150
150
151 Stores information about what took place.
151 Stores information about what took place.
152 """
152 """
153 execution_count = None
153 execution_count = None
154 error_before_exec = None
154 error_before_exec = None
155 error_in_exec = None
155 error_in_exec = None
156 result = None
156 result = None
157
157
158 @property
158 @property
159 def success(self):
159 def success(self):
160 return (self.error_before_exec is None) and (self.error_in_exec is None)
160 return (self.error_before_exec is None) and (self.error_in_exec is None)
161
161
162 def raise_error(self):
162 def raise_error(self):
163 """Reraises error if `success` is `False`, otherwise does nothing"""
163 """Reraises error if `success` is `False`, otherwise does nothing"""
164 if self.error_before_exec is not None:
164 if self.error_before_exec is not None:
165 raise self.error_before_exec
165 raise self.error_before_exec
166 if self.error_in_exec is not None:
166 if self.error_in_exec is not None:
167 raise self.error_in_exec
167 raise self.error_in_exec
168
168
169
169
170 class InteractiveShell(SingletonConfigurable):
170 class InteractiveShell(SingletonConfigurable):
171 """An enhanced, interactive shell for Python."""
171 """An enhanced, interactive shell for Python."""
172
172
173 _instance = None
173 _instance = None
174
174
175 ast_transformers = List([], help=
175 ast_transformers = List([], help=
176 """
176 """
177 A list of ast.NodeTransformer subclass instances, which will be applied
177 A list of ast.NodeTransformer subclass instances, which will be applied
178 to user input before code is run.
178 to user input before code is run.
179 """
179 """
180 ).tag(config=True)
180 ).tag(config=True)
181
181
182 autocall = Enum((0,1,2), default_value=0, help=
182 autocall = Enum((0,1,2), default_value=0, help=
183 """
183 """
184 Make IPython automatically call any callable object even if you didn't
184 Make IPython automatically call any callable object even if you didn't
185 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
185 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
186 automatically. The value can be '0' to disable the feature, '1' for
186 automatically. The value can be '0' to disable the feature, '1' for
187 'smart' autocall, where it is not applied if there are no more
187 'smart' autocall, where it is not applied if there are no more
188 arguments on the line, and '2' for 'full' autocall, where all callable
188 arguments on the line, and '2' for 'full' autocall, where all callable
189 objects are automatically called (even if no arguments are present).
189 objects are automatically called (even if no arguments are present).
190 """
190 """
191 ).tag(config=True)
191 ).tag(config=True)
192 # TODO: remove all autoindent logic and put into frontends.
192 # TODO: remove all autoindent logic and put into frontends.
193 # We can't do this yet because even runlines uses the autoindent.
193 # We can't do this yet because even runlines uses the autoindent.
194 autoindent = Bool(True, help=
194 autoindent = Bool(True, help=
195 """
195 """
196 Autoindent IPython code entered interactively.
196 Autoindent IPython code entered interactively.
197 """
197 """
198 ).tag(config=True)
198 ).tag(config=True)
199 automagic = Bool(True, help=
199 automagic = Bool(True, help=
200 """
200 """
201 Enable magic commands to be called without the leading %.
201 Enable magic commands to be called without the leading %.
202 """
202 """
203 ).tag(config=True)
203 ).tag(config=True)
204
204
205 banner1 = Unicode(default_banner,
205 banner1 = Unicode(default_banner,
206 help="""The part of the banner to be printed before the profile"""
206 help="""The part of the banner to be printed before the profile"""
207 ).tag(config=True)
207 ).tag(config=True)
208 banner2 = Unicode('',
208 banner2 = Unicode('',
209 help="""The part of the banner to be printed after the profile"""
209 help="""The part of the banner to be printed after the profile"""
210 ).tag(config=True)
210 ).tag(config=True)
211
211
212 cache_size = Integer(1000, help=
212 cache_size = Integer(1000, help=
213 """
213 """
214 Set the size of the output cache. The default is 1000, you can
214 Set the size of the output cache. The default is 1000, you can
215 change it permanently in your config file. Setting it to 0 completely
215 change it permanently in your config file. Setting it to 0 completely
216 disables the caching system, and the minimum value accepted is 20 (if
216 disables the caching system, and the minimum value accepted is 20 (if
217 you provide a value less than 20, it is reset to 0 and a warning is
217 you provide a value less than 20, it is reset to 0 and a warning is
218 issued). This limit is defined because otherwise you'll spend more
218 issued). This limit is defined because otherwise you'll spend more
219 time re-flushing a too small cache than working
219 time re-flushing a too small cache than working
220 """
220 """
221 ).tag(config=True)
221 ).tag(config=True)
222 color_info = Bool(True, help=
222 color_info = Bool(True, help=
223 """
223 """
224 Use colors for displaying information about objects. Because this
224 Use colors for displaying information about objects. Because this
225 information is passed through a pager (like 'less'), and some pagers
225 information is passed through a pager (like 'less'), and some pagers
226 get confused with color codes, this capability can be turned off.
226 get confused with color codes, this capability can be turned off.
227 """
227 """
228 ).tag(config=True)
228 ).tag(config=True)
229 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
229 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
230 default_value=get_default_colors(),
230 default_value=get_default_colors(),
231 help="Set the color scheme (NoColor, Linux, or LightBG)."
231 help="Set the color scheme (NoColor, Linux, or LightBG)."
232 ).tag(config=True)
232 ).tag(config=True)
233 colors_force = Bool(False, help=
233 colors_force = Bool(False, help=
234 """
234 """
235 Force use of ANSI color codes, regardless of OS and readline
235 Force use of ANSI color codes, regardless of OS and readline
236 availability.
236 availability.
237 """
237 """
238 # FIXME: This is essentially a hack to allow ZMQShell to show colors
238 # FIXME: This is essentially a hack to allow ZMQShell to show colors
239 # without readline on Win32. When the ZMQ formatting system is
239 # without readline on Win32. When the ZMQ formatting system is
240 # refactored, this should be removed.
240 # refactored, this should be removed.
241 )
241 )
242 debug = Bool(False).tag(config=True)
242 debug = Bool(False).tag(config=True)
243 deep_reload = Bool(False, help=
243 deep_reload = Bool(False, help=
244 """
244 """
245 **Deprecated**
245 **Deprecated**
246
246
247 Will be removed in IPython 6.0
247 Will be removed in IPython 6.0
248
248
249 Enable deep (recursive) reloading by default. IPython can use the
249 Enable deep (recursive) reloading by default. IPython can use the
250 deep_reload module which reloads changes in modules recursively (it
250 deep_reload module which reloads changes in modules recursively (it
251 replaces the reload() function, so you don't need to change anything to
251 replaces the reload() function, so you don't need to change anything to
252 use it). `deep_reload` forces a full reload of modules whose code may
252 use it). `deep_reload` forces a full reload of modules whose code may
253 have changed, which the default reload() function does not. When
253 have changed, which the default reload() function does not. When
254 deep_reload is off, IPython will use the normal reload(), but
254 deep_reload is off, IPython will use the normal reload(), but
255 deep_reload will still be available as dreload().
255 deep_reload will still be available as dreload().
256 """
256 """
257 ).tag(config=True)
257 ).tag(config=True)
258 disable_failing_post_execute = Bool(False,
258 disable_failing_post_execute = Bool(False,
259 help="Don't call post-execute functions that have failed in the past."
259 help="Don't call post-execute functions that have failed in the past."
260 ).tag(config=True)
260 ).tag(config=True)
261 display_formatter = Instance(DisplayFormatter, allow_none=True)
261 display_formatter = Instance(DisplayFormatter, allow_none=True)
262 displayhook_class = Type(DisplayHook)
262 displayhook_class = Type(DisplayHook)
263 display_pub_class = Type(DisplayPublisher)
263 display_pub_class = Type(DisplayPublisher)
264 data_pub_class = None
264 data_pub_class = None
265
265
266 exit_now = Bool(False)
266 exit_now = Bool(False)
267 exiter = Instance(ExitAutocall)
267 exiter = Instance(ExitAutocall)
268 @default('exiter')
268 @default('exiter')
269 def _exiter_default(self):
269 def _exiter_default(self):
270 return ExitAutocall(self)
270 return ExitAutocall(self)
271 # Monotonically increasing execution counter
271 # Monotonically increasing execution counter
272 execution_count = Integer(1)
272 execution_count = Integer(1)
273 filename = Unicode("<ipython console>")
273 filename = Unicode("<ipython console>")
274 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
274 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
275
275
276 # Input splitter, to transform input line by line and detect when a block
276 # Input splitter, to transform input line by line and detect when a block
277 # is ready to be executed.
277 # is ready to be executed.
278 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
278 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
279 (), {'line_input_checker': True})
279 (), {'line_input_checker': True})
280
280
281 # This InputSplitter instance is used to transform completed cells before
281 # This InputSplitter instance is used to transform completed cells before
282 # running them. It allows cell magics to contain blank lines.
282 # running them. It allows cell magics to contain blank lines.
283 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
283 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
284 (), {'line_input_checker': False})
284 (), {'line_input_checker': False})
285
285
286 logstart = Bool(False, help=
286 logstart = Bool(False, help=
287 """
287 """
288 Start logging to the default log file in overwrite mode.
288 Start logging to the default log file in overwrite mode.
289 Use `logappend` to specify a log file to **append** logs to.
289 Use `logappend` to specify a log file to **append** logs to.
290 """
290 """
291 ).tag(config=True)
291 ).tag(config=True)
292 logfile = Unicode('', help=
292 logfile = Unicode('', help=
293 """
293 """
294 The name of the logfile to use.
294 The name of the logfile to use.
295 """
295 """
296 ).tag(config=True)
296 ).tag(config=True)
297 logappend = Unicode('', help=
297 logappend = Unicode('', help=
298 """
298 """
299 Start logging to the given file in append mode.
299 Start logging to the given file in append mode.
300 Use `logfile` to specify a log file to **overwrite** logs to.
300 Use `logfile` to specify a log file to **overwrite** logs to.
301 """
301 """
302 ).tag(config=True)
302 ).tag(config=True)
303 object_info_string_level = Enum((0,1,2), default_value=0,
303 object_info_string_level = Enum((0,1,2), default_value=0,
304 ).tag(config=True)
304 ).tag(config=True)
305 pdb = Bool(False, help=
305 pdb = Bool(False, help=
306 """
306 """
307 Automatically call the pdb debugger after every exception.
307 Automatically call the pdb debugger after every exception.
308 """
308 """
309 ).tag(config=True)
309 ).tag(config=True)
310 multiline_history = Bool(sys.platform != 'win32',
310 multiline_history = Bool(sys.platform != 'win32',
311 help="Save multi-line entries as one entry in readline history"
311 help="Save multi-line entries as one entry in readline history"
312 ).tag(config=True)
312 ).tag(config=True)
313 display_page = Bool(False,
313 display_page = Bool(False,
314 help="""If True, anything that would be passed to the pager
314 help="""If True, anything that would be passed to the pager
315 will be displayed as regular output instead."""
315 will be displayed as regular output instead."""
316 ).tag(config=True)
316 ).tag(config=True)
317
317
318 # deprecated prompt traits:
318 # deprecated prompt traits:
319
319
320 prompt_in1 = Unicode('In [\\#]: ',
320 prompt_in1 = Unicode('In [\\#]: ',
321 help="Deprecated, will be removed in IPython 5.0, use PromptManager.in_template"
321 help="Deprecated, will be removed in IPython 5.0, use PromptManager.in_template"
322 ).tag(config=True)
322 ).tag(config=True)
323 prompt_in2 = Unicode(' .\\D.: ',
323 prompt_in2 = Unicode(' .\\D.: ',
324 help="Deprecated, will be removed in IPython 5.0, use PromptManager.in2_template"
324 help="Deprecated, will be removed in IPython 5.0, use PromptManager.in2_template"
325 ).tag(config=True)
325 ).tag(config=True)
326 prompt_out = Unicode('Out[\\#]: ',
326 prompt_out = Unicode('Out[\\#]: ',
327 help="Deprecated, will be removed in IPython 5.0, use PromptManager.out_template"
327 help="Deprecated, will be removed in IPython 5.0, use PromptManager.out_template"
328 ).tag(config=True)
328 ).tag(config=True)
329 prompts_pad_left = Bool(True,
329 prompts_pad_left = Bool(True,
330 help="Deprecated, will be removed in IPython 5.0, use PromptManager.justify"
330 help="Deprecated, will be removed in IPython 5.0, use PromptManager.justify"
331 ).tag(config=True)
331 ).tag(config=True)
332
332
333 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
333 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
334 def _prompt_trait_changed(self, change):
334 def _prompt_trait_changed(self, change):
335 table = {
335 table = {
336 'prompt_in1' : 'in_template',
336 'prompt_in1' : 'in_template',
337 'prompt_in2' : 'in2_template',
337 'prompt_in2' : 'in2_template',
338 'prompt_out' : 'out_template',
338 'prompt_out' : 'out_template',
339 'prompts_pad_left' : 'justify',
339 'prompts_pad_left' : 'justify',
340 }
340 }
341 name = change['name']
341 name = change['name']
342 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
342 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
343 name=name, newname=table[name])
343 name=name, newname=table[name])
344 )
344 )
345 # protect against weird cases where self.config may not exist:
345 # protect against weird cases where self.config may not exist:
346 if self.config is not None:
346 if self.config is not None:
347 # propagate to corresponding PromptManager trait
347 # propagate to corresponding PromptManager trait
348 setattr(self.config.PromptManager, table[name], change['new'])
348 setattr(self.config.PromptManager, table[name], change['new'])
349
349
350 show_rewritten_input = Bool(True,
350 show_rewritten_input = Bool(True,
351 help="Show rewritten input, e.g. for autocall."
351 help="Show rewritten input, e.g. for autocall."
352 ).tag(config=True)
352 ).tag(config=True)
353
353
354 quiet = Bool(False).tag(config=True)
354 quiet = Bool(False).tag(config=True)
355
355
356 history_length = Integer(10000,
356 history_length = Integer(10000,
357 help='Total length of command history'
357 help='Total length of command history'
358 ).tag(config=True)
358 ).tag(config=True)
359
359
360 history_load_length = Integer(1000, help=
360 history_load_length = Integer(1000, help=
361 """
361 """
362 The number of saved history entries to be loaded
362 The number of saved history entries to be loaded
363 into the readline buffer at startup.
363 into the readline buffer at startup.
364 """
364 """
365 ).tag(config=True)
365 ).tag(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 = Bool(True).tag(config=True)
369 readline_use = Bool(True).tag(config=True)
370 readline_remove_delims = Unicode('-/~').tag(config=True)
370 readline_remove_delims = Unicode('-/~').tag(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 ]).tag(config=True)
387 ]).tag(config=True)
388
388
389 _custom_readline_config = False
389 _custom_readline_config = False
390
390
391 @observe('readline_parse_and_bind')
391 @observe('readline_parse_and_bind')
392 def _readline_parse_and_bind_changed(self, change):
392 def _readline_parse_and_bind_changed(self, change):
393 # notice that readline config is customized
393 # notice that readline config is customized
394 # indicates that it should have higher priority than inputrc
394 # indicates that it should have higher priority than inputrc
395 self._custom_readline_config = True
395 self._custom_readline_config = True
396
396
397 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
397 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
398 default_value='last_expr',
398 default_value='last_expr',
399 help="""
399 help="""
400 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
400 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
401 run interactively (displaying output from expressions)."""
401 run interactively (displaying output from expressions)."""
402 ).tag(config=True)
402 ).tag(config=True)
403
403
404 # TODO: this part of prompt management should be moved to the frontends.
404 # TODO: this part of prompt management should be moved to the frontends.
405 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
405 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
406 separate_in = SeparateUnicode('\n').tag(config=True)
406 separate_in = SeparateUnicode('\n').tag(config=True)
407 separate_out = SeparateUnicode('').tag(config=True)
407 separate_out = SeparateUnicode('').tag(config=True)
408 separate_out2 = SeparateUnicode('').tag(config=True)
408 separate_out2 = SeparateUnicode('').tag(config=True)
409 wildcards_case_sensitive = Bool(True).tag(config=True)
409 wildcards_case_sensitive = Bool(True).tag(config=True)
410 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
410 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
411 default_value='Context').tag(config=True)
411 default_value='Context').tag(config=True)
412
412
413 # Subcomponents of InteractiveShell
413 # Subcomponents of InteractiveShell
414 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
414 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
415 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
415 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
416 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
416 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
417 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
417 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
418 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
418 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
419 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
419 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
420 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
420 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
421 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
421 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
422
422
423 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
423 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
424 @property
424 @property
425 def profile(self):
425 def profile(self):
426 if self.profile_dir is not None:
426 if self.profile_dir is not None:
427 name = os.path.basename(self.profile_dir.location)
427 name = os.path.basename(self.profile_dir.location)
428 return name.replace('profile_','')
428 return name.replace('profile_','')
429
429
430
430
431 # Private interface
431 # Private interface
432 _post_execute = Dict()
432 _post_execute = Dict()
433
433
434 # Tracks any GUI loop loaded for pylab
434 # Tracks any GUI loop loaded for pylab
435 pylab_gui_select = None
435 pylab_gui_select = None
436
436
437 def __init__(self, ipython_dir=None, profile_dir=None,
437 def __init__(self, ipython_dir=None, profile_dir=None,
438 user_module=None, user_ns=None,
438 user_module=None, user_ns=None,
439 custom_exceptions=((), None), **kwargs):
439 custom_exceptions=((), None), **kwargs):
440
440
441 # This is where traits with a config_key argument are updated
441 # This is where traits with a config_key argument are updated
442 # from the values on config.
442 # from the values on config.
443 super(InteractiveShell, self).__init__(**kwargs)
443 super(InteractiveShell, self).__init__(**kwargs)
444 self.configurables = [self]
444 self.configurables = [self]
445
445
446 # These are relatively independent and stateless
446 # These are relatively independent and stateless
447 self.init_ipython_dir(ipython_dir)
447 self.init_ipython_dir(ipython_dir)
448 self.init_profile_dir(profile_dir)
448 self.init_profile_dir(profile_dir)
449 self.init_instance_attrs()
449 self.init_instance_attrs()
450 self.init_environment()
450 self.init_environment()
451
451
452 # Check if we're in a virtualenv, and set up sys.path.
452 # Check if we're in a virtualenv, and set up sys.path.
453 self.init_virtualenv()
453 self.init_virtualenv()
454
454
455 # Create namespaces (user_ns, user_global_ns, etc.)
455 # Create namespaces (user_ns, user_global_ns, etc.)
456 self.init_create_namespaces(user_module, user_ns)
456 self.init_create_namespaces(user_module, user_ns)
457 # This has to be done after init_create_namespaces because it uses
457 # This has to be done after init_create_namespaces because it uses
458 # something in self.user_ns, but before init_sys_modules, which
458 # something in self.user_ns, but before init_sys_modules, which
459 # is the first thing to modify sys.
459 # is the first thing to modify sys.
460 # TODO: When we override sys.stdout and sys.stderr before this class
460 # TODO: When we override sys.stdout and sys.stderr before this class
461 # is created, we are saving the overridden ones here. Not sure if this
461 # is created, we are saving the overridden ones here. Not sure if this
462 # is what we want to do.
462 # is what we want to do.
463 self.save_sys_module_state()
463 self.save_sys_module_state()
464 self.init_sys_modules()
464 self.init_sys_modules()
465
465
466 # While we're trying to have each part of the code directly access what
466 # While we're trying to have each part of the code directly access what
467 # it needs without keeping redundant references to objects, we have too
467 # it needs without keeping redundant references to objects, we have too
468 # much legacy code that expects ip.db to exist.
468 # much legacy code that expects ip.db to exist.
469 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
469 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
470
470
471 self.init_history()
471 self.init_history()
472 self.init_encoding()
472 self.init_encoding()
473 self.init_prefilter()
473 self.init_prefilter()
474
474
475 self.init_syntax_highlighting()
475 self.init_syntax_highlighting()
476 self.init_hooks()
476 self.init_hooks()
477 self.init_events()
477 self.init_events()
478 self.init_pushd_popd_magic()
478 self.init_pushd_popd_magic()
479 # self.init_traceback_handlers use to be here, but we moved it below
479 # self.init_traceback_handlers use to be here, but we moved it below
480 # because it and init_io have to come after init_readline.
480 # because it and init_io have to come after init_readline.
481 self.init_user_ns()
481 self.init_user_ns()
482 self.init_logger()
482 self.init_logger()
483 self.init_builtins()
483 self.init_builtins()
484
484
485 # The following was in post_config_initialization
485 # The following was in post_config_initialization
486 self.init_inspector()
486 self.init_inspector()
487 # init_readline() must come before init_io(), because init_io uses
487 # init_readline() must come before init_io(), because init_io uses
488 # readline related things.
488 # readline related things.
489 self.init_readline()
489 self.init_readline()
490 # We save this here in case user code replaces raw_input, but it needs
490 # We save this here in case user code replaces raw_input, but it needs
491 # to be after init_readline(), because PyPy's readline works by replacing
491 # to be after init_readline(), because PyPy's readline works by replacing
492 # raw_input.
492 # raw_input.
493 if py3compat.PY3:
493 if py3compat.PY3:
494 self.raw_input_original = input
494 self.raw_input_original = input
495 else:
495 else:
496 self.raw_input_original = raw_input
496 self.raw_input_original = raw_input
497 # init_completer must come after init_readline, because it needs to
497 # init_completer must come after init_readline, because it needs to
498 # know whether readline is present or not system-wide to configure the
498 # know whether readline is present or not system-wide to configure the
499 # completers, since the completion machinery can now operate
499 # completers, since the completion machinery can now operate
500 # independently of readline (e.g. over the network)
500 # independently of readline (e.g. over the network)
501 self.init_completer()
501 self.init_completer()
502 # TODO: init_io() needs to happen before init_traceback handlers
502 # TODO: init_io() needs to happen before init_traceback handlers
503 # because the traceback handlers hardcode the stdout/stderr streams.
503 # because the traceback handlers hardcode the stdout/stderr streams.
504 # This logic in in debugger.Pdb and should eventually be changed.
504 # This logic in in debugger.Pdb and should eventually be changed.
505 self.init_io()
505 self.init_io()
506 self.init_traceback_handlers(custom_exceptions)
506 self.init_traceback_handlers(custom_exceptions)
507 self.init_prompts()
507 self.init_prompts()
508 self.init_display_formatter()
508 self.init_display_formatter()
509 self.init_display_pub()
509 self.init_display_pub()
510 self.init_data_pub()
510 self.init_data_pub()
511 self.init_displayhook()
511 self.init_displayhook()
512 self.init_magics()
512 self.init_magics()
513 self.init_alias()
513 self.init_alias()
514 self.init_logstart()
514 self.init_logstart()
515 self.init_pdb()
515 self.init_pdb()
516 self.init_extension_manager()
516 self.init_extension_manager()
517 self.init_payload()
517 self.init_payload()
518 self.init_deprecation_warnings()
518 self.init_deprecation_warnings()
519 self.hooks.late_startup_hook()
519 self.hooks.late_startup_hook()
520 self.events.trigger('shell_initialized', self)
520 self.events.trigger('shell_initialized', self)
521 atexit.register(self.atexit_operations)
521 atexit.register(self.atexit_operations)
522
522
523 def get_ipython(self):
523 def get_ipython(self):
524 """Return the currently running IPython instance."""
524 """Return the currently running IPython instance."""
525 return self
525 return self
526
526
527 #-------------------------------------------------------------------------
527 #-------------------------------------------------------------------------
528 # Trait changed handlers
528 # Trait changed handlers
529 #-------------------------------------------------------------------------
529 #-------------------------------------------------------------------------
530 @observe('ipython_dir')
530 @observe('ipython_dir')
531 def _ipython_dir_changed(self, change):
531 def _ipython_dir_changed(self, change):
532 ensure_dir_exists(change['new'])
532 ensure_dir_exists(change['new'])
533
533
534 def set_autoindent(self,value=None):
534 def set_autoindent(self,value=None):
535 """Set the autoindent flag.
535 """Set the autoindent flag.
536
536
537 If called with no arguments, it acts as a toggle."""
537 If called with no arguments, it acts as a toggle."""
538 if value is None:
538 if value is None:
539 self.autoindent = not self.autoindent
539 self.autoindent = not self.autoindent
540 else:
540 else:
541 self.autoindent = value
541 self.autoindent = value
542
542
543 #-------------------------------------------------------------------------
543 #-------------------------------------------------------------------------
544 # init_* methods called by __init__
544 # init_* methods called by __init__
545 #-------------------------------------------------------------------------
545 #-------------------------------------------------------------------------
546
546
547 def init_ipython_dir(self, ipython_dir):
547 def init_ipython_dir(self, ipython_dir):
548 if ipython_dir is not None:
548 if ipython_dir is not None:
549 self.ipython_dir = ipython_dir
549 self.ipython_dir = ipython_dir
550 return
550 return
551
551
552 self.ipython_dir = get_ipython_dir()
552 self.ipython_dir = get_ipython_dir()
553
553
554 def init_profile_dir(self, profile_dir):
554 def init_profile_dir(self, profile_dir):
555 if profile_dir is not None:
555 if profile_dir is not None:
556 self.profile_dir = profile_dir
556 self.profile_dir = profile_dir
557 return
557 return
558 self.profile_dir =\
558 self.profile_dir =\
559 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
559 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
560
560
561 def init_instance_attrs(self):
561 def init_instance_attrs(self):
562 self.more = False
562 self.more = False
563
563
564 # command compiler
564 # command compiler
565 self.compile = CachingCompiler()
565 self.compile = CachingCompiler()
566
566
567 # Make an empty namespace, which extension writers can rely on both
567 # Make an empty namespace, which extension writers can rely on both
568 # existing and NEVER being used by ipython itself. This gives them a
568 # existing and NEVER being used by ipython itself. This gives them a
569 # convenient location for storing additional information and state
569 # convenient location for storing additional information and state
570 # their extensions may require, without fear of collisions with other
570 # their extensions may require, without fear of collisions with other
571 # ipython names that may develop later.
571 # ipython names that may develop later.
572 self.meta = Struct()
572 self.meta = Struct()
573
573
574 # Temporary files used for various purposes. Deleted at exit.
574 # Temporary files used for various purposes. Deleted at exit.
575 self.tempfiles = []
575 self.tempfiles = []
576 self.tempdirs = []
576 self.tempdirs = []
577
577
578 # Keep track of readline usage (later set by init_readline)
578 # Keep track of readline usage (later set by init_readline)
579 self.has_readline = False
579 self.has_readline = False
580
580
581 # keep track of where we started running (mainly for crash post-mortem)
581 # keep track of where we started running (mainly for crash post-mortem)
582 # This is not being used anywhere currently.
582 # This is not being used anywhere currently.
583 self.starting_dir = py3compat.getcwd()
583 self.starting_dir = py3compat.getcwd()
584
584
585 # Indentation management
585 # Indentation management
586 self.indent_current_nsp = 0
586 self.indent_current_nsp = 0
587
587
588 # Dict to track post-execution functions that have been registered
588 # Dict to track post-execution functions that have been registered
589 self._post_execute = {}
589 self._post_execute = {}
590
590
591 def init_environment(self):
591 def init_environment(self):
592 """Any changes we need to make to the user's environment."""
592 """Any changes we need to make to the user's environment."""
593 pass
593 pass
594
594
595 def init_encoding(self):
595 def init_encoding(self):
596 # Get system encoding at startup time. Certain terminals (like Emacs
596 # Get system encoding at startup time. Certain terminals (like Emacs
597 # under Win32 have it set to None, and we need to have a known valid
597 # under Win32 have it set to None, and we need to have a known valid
598 # encoding to use in the raw_input() method
598 # encoding to use in the raw_input() method
599 try:
599 try:
600 self.stdin_encoding = sys.stdin.encoding or 'ascii'
600 self.stdin_encoding = sys.stdin.encoding or 'ascii'
601 except AttributeError:
601 except AttributeError:
602 self.stdin_encoding = 'ascii'
602 self.stdin_encoding = 'ascii'
603
603
604 def init_syntax_highlighting(self):
604 def init_syntax_highlighting(self):
605 # Python source parser/formatter for syntax highlighting
605 # Python source parser/formatter for syntax highlighting
606 pyformat = PyColorize.Parser().format
606 pyformat = PyColorize.Parser().format
607 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
607 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
608
608
609 def init_pushd_popd_magic(self):
609 def init_pushd_popd_magic(self):
610 # for pushd/popd management
610 # for pushd/popd management
611 self.home_dir = get_home_dir()
611 self.home_dir = get_home_dir()
612
612
613 self.dir_stack = []
613 self.dir_stack = []
614
614
615 def init_logger(self):
615 def init_logger(self):
616 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
616 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
617 logmode='rotate')
617 logmode='rotate')
618
618
619 def init_logstart(self):
619 def init_logstart(self):
620 """Initialize logging in case it was requested at the command line.
620 """Initialize logging in case it was requested at the command line.
621 """
621 """
622 if self.logappend:
622 if self.logappend:
623 self.magic('logstart %s append' % self.logappend)
623 self.magic('logstart %s append' % self.logappend)
624 elif self.logfile:
624 elif self.logfile:
625 self.magic('logstart %s' % self.logfile)
625 self.magic('logstart %s' % self.logfile)
626 elif self.logstart:
626 elif self.logstart:
627 self.magic('logstart')
627 self.magic('logstart')
628
628
629 def init_deprecation_warnings(self):
629 def init_deprecation_warnings(self):
630 """
630 """
631 register default filter for deprecation warning.
631 register default filter for deprecation warning.
632
632
633 This will allow deprecation warning of function used interactively to show
633 This will allow deprecation warning of function used interactively to show
634 warning to users, and still hide deprecation warning from libraries import.
634 warning to users, and still hide deprecation warning from libraries import.
635 """
635 """
636 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
636 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
637
637
638 def init_builtins(self):
638 def init_builtins(self):
639 # A single, static flag that we set to True. Its presence indicates
639 # A single, static flag that we set to True. Its presence indicates
640 # that an IPython shell has been created, and we make no attempts at
640 # that an IPython shell has been created, and we make no attempts at
641 # removing on exit or representing the existence of more than one
641 # removing on exit or representing the existence of more than one
642 # IPython at a time.
642 # IPython at a time.
643 builtin_mod.__dict__['__IPYTHON__'] = True
643 builtin_mod.__dict__['__IPYTHON__'] = True
644
644
645 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
645 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
646 # manage on enter/exit, but with all our shells it's virtually
646 # manage on enter/exit, but with all our shells it's virtually
647 # impossible to get all the cases right. We're leaving the name in for
647 # impossible to get all the cases right. We're leaving the name in for
648 # those who adapted their codes to check for this flag, but will
648 # those who adapted their codes to check for this flag, but will
649 # eventually remove it after a few more releases.
649 # eventually remove it after a few more releases.
650 builtin_mod.__dict__['__IPYTHON__active'] = \
650 builtin_mod.__dict__['__IPYTHON__active'] = \
651 'Deprecated, check for __IPYTHON__'
651 'Deprecated, check for __IPYTHON__'
652
652
653 self.builtin_trap = BuiltinTrap(shell=self)
653 self.builtin_trap = BuiltinTrap(shell=self)
654
654
655 def init_inspector(self):
655 def init_inspector(self):
656 # Object inspector
656 # Object inspector
657 self.inspector = oinspect.Inspector(oinspect.InspectColors,
657 self.inspector = oinspect.Inspector(oinspect.InspectColors,
658 PyColorize.ANSICodeColors,
658 PyColorize.ANSICodeColors,
659 'NoColor',
659 'NoColor',
660 self.object_info_string_level)
660 self.object_info_string_level)
661
661
662 def init_io(self):
662 def init_io(self):
663 # This will just use sys.stdout and sys.stderr. If you want to
663 # This will just use sys.stdout and sys.stderr. If you want to
664 # override sys.stdout and sys.stderr themselves, you need to do that
664 # override sys.stdout and sys.stderr themselves, you need to do that
665 # *before* instantiating this class, because io holds onto
665 # *before* instantiating this class, because io holds onto
666 # references to the underlying streams.
666 # references to the underlying streams.
667 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
667 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
668 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
668 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
669 else:
669 else:
670 io.stdout = io.IOStream(sys.stdout)
670 io.stdout = io.IOStream(sys.stdout)
671 io.stderr = io.IOStream(sys.stderr)
671 io.stderr = io.IOStream(sys.stderr)
672
672
673 def init_prompts(self):
673 def init_prompts(self):
674 self.prompt_manager = PromptManager(shell=self, parent=self)
674 self.prompt_manager = PromptManager(shell=self, parent=self)
675 self.configurables.append(self.prompt_manager)
675 self.configurables.append(self.prompt_manager)
676 # Set system prompts, so that scripts can decide if they are running
676 # Set system prompts, so that scripts can decide if they are running
677 # interactively.
677 # interactively.
678 sys.ps1 = 'In : '
678 sys.ps1 = 'In : '
679 sys.ps2 = '...: '
679 sys.ps2 = '...: '
680 sys.ps3 = 'Out: '
680 sys.ps3 = 'Out: '
681
681
682 def init_display_formatter(self):
682 def init_display_formatter(self):
683 self.display_formatter = DisplayFormatter(parent=self)
683 self.display_formatter = DisplayFormatter(parent=self)
684 self.configurables.append(self.display_formatter)
684 self.configurables.append(self.display_formatter)
685
685
686 def init_display_pub(self):
686 def init_display_pub(self):
687 self.display_pub = self.display_pub_class(parent=self)
687 self.display_pub = self.display_pub_class(parent=self)
688 self.configurables.append(self.display_pub)
688 self.configurables.append(self.display_pub)
689
689
690 def init_data_pub(self):
690 def init_data_pub(self):
691 if not self.data_pub_class:
691 if not self.data_pub_class:
692 self.data_pub = None
692 self.data_pub = None
693 return
693 return
694 self.data_pub = self.data_pub_class(parent=self)
694 self.data_pub = self.data_pub_class(parent=self)
695 self.configurables.append(self.data_pub)
695 self.configurables.append(self.data_pub)
696
696
697 def init_displayhook(self):
697 def init_displayhook(self):
698 # Initialize displayhook, set in/out prompts and printing system
698 # Initialize displayhook, set in/out prompts and printing system
699 self.displayhook = self.displayhook_class(
699 self.displayhook = self.displayhook_class(
700 parent=self,
700 parent=self,
701 shell=self,
701 shell=self,
702 cache_size=self.cache_size,
702 cache_size=self.cache_size,
703 )
703 )
704 self.configurables.append(self.displayhook)
704 self.configurables.append(self.displayhook)
705 # This is a context manager that installs/revmoes the displayhook at
705 # This is a context manager that installs/revmoes the displayhook at
706 # the appropriate time.
706 # the appropriate time.
707 self.display_trap = DisplayTrap(hook=self.displayhook)
707 self.display_trap = DisplayTrap(hook=self.displayhook)
708
708
709 def init_virtualenv(self):
709 def init_virtualenv(self):
710 """Add a virtualenv to sys.path so the user can import modules from it.
710 """Add a virtualenv to sys.path so the user can import modules from it.
711 This isn't perfect: it doesn't use the Python interpreter with which the
711 This isn't perfect: it doesn't use the Python interpreter with which the
712 virtualenv was built, and it ignores the --no-site-packages option. A
712 virtualenv was built, and it ignores the --no-site-packages option. A
713 warning will appear suggesting the user installs IPython in the
713 warning will appear suggesting the user installs IPython in the
714 virtualenv, but for many cases, it probably works well enough.
714 virtualenv, but for many cases, it probably works well enough.
715
715
716 Adapted from code snippets online.
716 Adapted from code snippets online.
717
717
718 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
718 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
719 """
719 """
720 if 'VIRTUAL_ENV' not in os.environ:
720 if 'VIRTUAL_ENV' not in os.environ:
721 # Not in a virtualenv
721 # Not in a virtualenv
722 return
722 return
723
723
724 # venv detection:
724 # venv detection:
725 # stdlib venv may symlink sys.executable, so we can't use realpath.
725 # stdlib venv may symlink sys.executable, so we can't use realpath.
726 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
726 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
727 # So we just check every item in the symlink tree (generally <= 3)
727 # So we just check every item in the symlink tree (generally <= 3)
728 p = os.path.normcase(sys.executable)
728 p = os.path.normcase(sys.executable)
729 paths = [p]
729 paths = [p]
730 while os.path.islink(p):
730 while os.path.islink(p):
731 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
731 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
732 paths.append(p)
732 paths.append(p)
733 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
733 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
734 if any(p.startswith(p_venv) for p in paths):
734 if any(p.startswith(p_venv) for p in paths):
735 # Running properly in the virtualenv, don't need to do anything
735 # Running properly in the virtualenv, don't need to do anything
736 return
736 return
737
737
738 warn("Attempting to work in a virtualenv. If you encounter problems, please "
738 warn("Attempting to work in a virtualenv. If you encounter problems, please "
739 "install IPython inside the virtualenv.")
739 "install IPython inside the virtualenv.")
740 if sys.platform == "win32":
740 if sys.platform == "win32":
741 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
741 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
742 else:
742 else:
743 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
743 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
744 'python%d.%d' % sys.version_info[:2], 'site-packages')
744 'python%d.%d' % sys.version_info[:2], 'site-packages')
745
745
746 import site
746 import site
747 sys.path.insert(0, virtual_env)
747 sys.path.insert(0, virtual_env)
748 site.addsitedir(virtual_env)
748 site.addsitedir(virtual_env)
749
749
750 #-------------------------------------------------------------------------
750 #-------------------------------------------------------------------------
751 # Things related to injections into the sys module
751 # Things related to injections into the sys module
752 #-------------------------------------------------------------------------
752 #-------------------------------------------------------------------------
753
753
754 def save_sys_module_state(self):
754 def save_sys_module_state(self):
755 """Save the state of hooks in the sys module.
755 """Save the state of hooks in the sys module.
756
756
757 This has to be called after self.user_module is created.
757 This has to be called after self.user_module is created.
758 """
758 """
759 self._orig_sys_module_state = {'stdin': sys.stdin,
759 self._orig_sys_module_state = {'stdin': sys.stdin,
760 'stdout': sys.stdout,
760 'stdout': sys.stdout,
761 'stderr': sys.stderr,
761 'stderr': sys.stderr,
762 'excepthook': sys.excepthook}
762 'excepthook': sys.excepthook}
763 self._orig_sys_modules_main_name = self.user_module.__name__
763 self._orig_sys_modules_main_name = self.user_module.__name__
764 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
764 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
765
765
766 def restore_sys_module_state(self):
766 def restore_sys_module_state(self):
767 """Restore the state of the sys module."""
767 """Restore the state of the sys module."""
768 try:
768 try:
769 for k, v in iteritems(self._orig_sys_module_state):
769 for k, v in iteritems(self._orig_sys_module_state):
770 setattr(sys, k, v)
770 setattr(sys, k, v)
771 except AttributeError:
771 except AttributeError:
772 pass
772 pass
773 # Reset what what done in self.init_sys_modules
773 # Reset what what done in self.init_sys_modules
774 if self._orig_sys_modules_main_mod is not None:
774 if self._orig_sys_modules_main_mod is not None:
775 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
775 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
776
776
777 #-------------------------------------------------------------------------
777 #-------------------------------------------------------------------------
778 # Things related to the banner
778 # Things related to the banner
779 #-------------------------------------------------------------------------
779 #-------------------------------------------------------------------------
780
780
781 @property
781 @property
782 def banner(self):
782 def banner(self):
783 banner = self.banner1
783 banner = self.banner1
784 if self.profile and self.profile != 'default':
784 if self.profile and self.profile != 'default':
785 banner += '\nIPython profile: %s\n' % self.profile
785 banner += '\nIPython profile: %s\n' % self.profile
786 if self.banner2:
786 if self.banner2:
787 banner += '\n' + self.banner2
787 banner += '\n' + self.banner2
788 return banner
788 return banner
789
789
790 def show_banner(self, banner=None):
790 def show_banner(self, banner=None):
791 if banner is None:
791 if banner is None:
792 banner = self.banner
792 banner = self.banner
793 sys.stdout.write(banner)
793 sys.stdout.write(banner)
794
794
795 #-------------------------------------------------------------------------
795 #-------------------------------------------------------------------------
796 # Things related to hooks
796 # Things related to hooks
797 #-------------------------------------------------------------------------
797 #-------------------------------------------------------------------------
798
798
799 def init_hooks(self):
799 def init_hooks(self):
800 # hooks holds pointers used for user-side customizations
800 # hooks holds pointers used for user-side customizations
801 self.hooks = Struct()
801 self.hooks = Struct()
802
802
803 self.strdispatchers = {}
803 self.strdispatchers = {}
804
804
805 # Set all default hooks, defined in the IPython.hooks module.
805 # Set all default hooks, defined in the IPython.hooks module.
806 hooks = IPython.core.hooks
806 hooks = IPython.core.hooks
807 for hook_name in hooks.__all__:
807 for hook_name in hooks.__all__:
808 # default hooks have priority 100, i.e. low; user hooks should have
808 # default hooks have priority 100, i.e. low; user hooks should have
809 # 0-100 priority
809 # 0-100 priority
810 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
810 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
811
811
812 if self.display_page:
812 if self.display_page:
813 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
813 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
814
814
815 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
815 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
816 _warn_deprecated=True):
816 _warn_deprecated=True):
817 """set_hook(name,hook) -> sets an internal IPython hook.
817 """set_hook(name,hook) -> sets an internal IPython hook.
818
818
819 IPython exposes some of its internal API as user-modifiable hooks. By
819 IPython exposes some of its internal API as user-modifiable hooks. By
820 adding your function to one of these hooks, you can modify IPython's
820 adding your function to one of these hooks, you can modify IPython's
821 behavior to call at runtime your own routines."""
821 behavior to call at runtime your own routines."""
822
822
823 # At some point in the future, this should validate the hook before it
823 # At some point in the future, this should validate the hook before it
824 # accepts it. Probably at least check that the hook takes the number
824 # accepts it. Probably at least check that the hook takes the number
825 # of args it's supposed to.
825 # of args it's supposed to.
826
826
827 f = types.MethodType(hook,self)
827 f = types.MethodType(hook,self)
828
828
829 # check if the hook is for strdispatcher first
829 # check if the hook is for strdispatcher first
830 if str_key is not None:
830 if str_key is not None:
831 sdp = self.strdispatchers.get(name, StrDispatch())
831 sdp = self.strdispatchers.get(name, StrDispatch())
832 sdp.add_s(str_key, f, priority )
832 sdp.add_s(str_key, f, priority )
833 self.strdispatchers[name] = sdp
833 self.strdispatchers[name] = sdp
834 return
834 return
835 if re_key is not None:
835 if re_key is not None:
836 sdp = self.strdispatchers.get(name, StrDispatch())
836 sdp = self.strdispatchers.get(name, StrDispatch())
837 sdp.add_re(re.compile(re_key), f, priority )
837 sdp.add_re(re.compile(re_key), f, priority )
838 self.strdispatchers[name] = sdp
838 self.strdispatchers[name] = sdp
839 return
839 return
840
840
841 dp = getattr(self.hooks, name, None)
841 dp = getattr(self.hooks, name, None)
842 if name not in IPython.core.hooks.__all__:
842 if name not in IPython.core.hooks.__all__:
843 print("Warning! Hook '%s' is not one of %s" % \
843 print("Warning! Hook '%s' is not one of %s" % \
844 (name, IPython.core.hooks.__all__ ))
844 (name, IPython.core.hooks.__all__ ))
845
845
846 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
846 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
847 alternative = IPython.core.hooks.deprecated[name]
847 alternative = IPython.core.hooks.deprecated[name]
848 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
848 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
849
849
850 if not dp:
850 if not dp:
851 dp = IPython.core.hooks.CommandChainDispatcher()
851 dp = IPython.core.hooks.CommandChainDispatcher()
852
852
853 try:
853 try:
854 dp.add(f,priority)
854 dp.add(f,priority)
855 except AttributeError:
855 except AttributeError:
856 # it was not commandchain, plain old func - replace
856 # it was not commandchain, plain old func - replace
857 dp = f
857 dp = f
858
858
859 setattr(self.hooks,name, dp)
859 setattr(self.hooks,name, dp)
860
860
861 #-------------------------------------------------------------------------
861 #-------------------------------------------------------------------------
862 # Things related to events
862 # Things related to events
863 #-------------------------------------------------------------------------
863 #-------------------------------------------------------------------------
864
864
865 def init_events(self):
865 def init_events(self):
866 self.events = EventManager(self, available_events)
866 self.events = EventManager(self, available_events)
867
867
868 self.events.register("pre_execute", self._clear_warning_registry)
868 self.events.register("pre_execute", self._clear_warning_registry)
869
869
870 def register_post_execute(self, func):
870 def register_post_execute(self, func):
871 """DEPRECATED: Use ip.events.register('post_run_cell', func)
871 """DEPRECATED: Use ip.events.register('post_run_cell', func)
872
872
873 Register a function for calling after code execution.
873 Register a function for calling after code execution.
874 """
874 """
875 warn("ip.register_post_execute is deprecated, use "
875 warn("ip.register_post_execute is deprecated, use "
876 "ip.events.register('post_run_cell', func) instead.")
876 "ip.events.register('post_run_cell', func) instead.")
877 self.events.register('post_run_cell', func)
877 self.events.register('post_run_cell', func)
878
878
879 def _clear_warning_registry(self):
879 def _clear_warning_registry(self):
880 # clear the warning registry, so that different code blocks with
880 # clear the warning registry, so that different code blocks with
881 # overlapping line number ranges don't cause spurious suppression of
881 # overlapping line number ranges don't cause spurious suppression of
882 # warnings (see gh-6611 for details)
882 # warnings (see gh-6611 for details)
883 if "__warningregistry__" in self.user_global_ns:
883 if "__warningregistry__" in self.user_global_ns:
884 del self.user_global_ns["__warningregistry__"]
884 del self.user_global_ns["__warningregistry__"]
885
885
886 #-------------------------------------------------------------------------
886 #-------------------------------------------------------------------------
887 # Things related to the "main" module
887 # Things related to the "main" module
888 #-------------------------------------------------------------------------
888 #-------------------------------------------------------------------------
889
889
890 def new_main_mod(self, filename, modname):
890 def new_main_mod(self, filename, modname):
891 """Return a new 'main' module object for user code execution.
891 """Return a new 'main' module object for user code execution.
892
892
893 ``filename`` should be the path of the script which will be run in the
893 ``filename`` should be the path of the script which will be run in the
894 module. Requests with the same filename will get the same module, with
894 module. Requests with the same filename will get the same module, with
895 its namespace cleared.
895 its namespace cleared.
896
896
897 ``modname`` should be the module name - normally either '__main__' or
897 ``modname`` should be the module name - normally either '__main__' or
898 the basename of the file without the extension.
898 the basename of the file without the extension.
899
899
900 When scripts are executed via %run, we must keep a reference to their
900 When scripts are executed via %run, we must keep a reference to their
901 __main__ module around so that Python doesn't
901 __main__ module around so that Python doesn't
902 clear it, rendering references to module globals useless.
902 clear it, rendering references to module globals useless.
903
903
904 This method keeps said reference in a private dict, keyed by the
904 This method keeps said reference in a private dict, keyed by the
905 absolute path of the script. This way, for multiple executions of the
905 absolute path of the script. This way, for multiple executions of the
906 same script we only keep one copy of the namespace (the last one),
906 same script we only keep one copy of the namespace (the last one),
907 thus preventing memory leaks from old references while allowing the
907 thus preventing memory leaks from old references while allowing the
908 objects from the last execution to be accessible.
908 objects from the last execution to be accessible.
909 """
909 """
910 filename = os.path.abspath(filename)
910 filename = os.path.abspath(filename)
911 try:
911 try:
912 main_mod = self._main_mod_cache[filename]
912 main_mod = self._main_mod_cache[filename]
913 except KeyError:
913 except KeyError:
914 main_mod = self._main_mod_cache[filename] = types.ModuleType(
914 main_mod = self._main_mod_cache[filename] = types.ModuleType(
915 py3compat.cast_bytes_py2(modname),
915 py3compat.cast_bytes_py2(modname),
916 doc="Module created for script run in IPython")
916 doc="Module created for script run in IPython")
917 else:
917 else:
918 main_mod.__dict__.clear()
918 main_mod.__dict__.clear()
919 main_mod.__name__ = modname
919 main_mod.__name__ = modname
920
920
921 main_mod.__file__ = filename
921 main_mod.__file__ = filename
922 # It seems pydoc (and perhaps others) needs any module instance to
922 # It seems pydoc (and perhaps others) needs any module instance to
923 # implement a __nonzero__ method
923 # implement a __nonzero__ method
924 main_mod.__nonzero__ = lambda : True
924 main_mod.__nonzero__ = lambda : True
925
925
926 return main_mod
926 return main_mod
927
927
928 def clear_main_mod_cache(self):
928 def clear_main_mod_cache(self):
929 """Clear the cache of main modules.
929 """Clear the cache of main modules.
930
930
931 Mainly for use by utilities like %reset.
931 Mainly for use by utilities like %reset.
932
932
933 Examples
933 Examples
934 --------
934 --------
935
935
936 In [15]: import IPython
936 In [15]: import IPython
937
937
938 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
938 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
939
939
940 In [17]: len(_ip._main_mod_cache) > 0
940 In [17]: len(_ip._main_mod_cache) > 0
941 Out[17]: True
941 Out[17]: True
942
942
943 In [18]: _ip.clear_main_mod_cache()
943 In [18]: _ip.clear_main_mod_cache()
944
944
945 In [19]: len(_ip._main_mod_cache) == 0
945 In [19]: len(_ip._main_mod_cache) == 0
946 Out[19]: True
946 Out[19]: True
947 """
947 """
948 self._main_mod_cache.clear()
948 self._main_mod_cache.clear()
949
949
950 #-------------------------------------------------------------------------
950 #-------------------------------------------------------------------------
951 # Things related to debugging
951 # Things related to debugging
952 #-------------------------------------------------------------------------
952 #-------------------------------------------------------------------------
953
953
954 def init_pdb(self):
954 def init_pdb(self):
955 # Set calling of pdb on exceptions
955 # Set calling of pdb on exceptions
956 # self.call_pdb is a property
956 # self.call_pdb is a property
957 self.call_pdb = self.pdb
957 self.call_pdb = self.pdb
958
958
959 def _get_call_pdb(self):
959 def _get_call_pdb(self):
960 return self._call_pdb
960 return self._call_pdb
961
961
962 def _set_call_pdb(self,val):
962 def _set_call_pdb(self,val):
963
963
964 if val not in (0,1,False,True):
964 if val not in (0,1,False,True):
965 raise ValueError('new call_pdb value must be boolean')
965 raise ValueError('new call_pdb value must be boolean')
966
966
967 # store value in instance
967 # store value in instance
968 self._call_pdb = val
968 self._call_pdb = val
969
969
970 # notify the actual exception handlers
970 # notify the actual exception handlers
971 self.InteractiveTB.call_pdb = val
971 self.InteractiveTB.call_pdb = val
972
972
973 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
973 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
974 'Control auto-activation of pdb at exceptions')
974 'Control auto-activation of pdb at exceptions')
975
975
976 def debugger(self,force=False):
976 def debugger(self,force=False):
977 """Call the pydb/pdb debugger.
977 """Call the pdb debugger.
978
978
979 Keywords:
979 Keywords:
980
980
981 - force(False): by default, this routine checks the instance call_pdb
981 - force(False): by default, this routine checks the instance call_pdb
982 flag and does not actually invoke the debugger if the flag is false.
982 flag and does not actually invoke the debugger if the flag is false.
983 The 'force' option forces the debugger to activate even if the flag
983 The 'force' option forces the debugger to activate even if the flag
984 is false.
984 is false.
985 """
985 """
986
986
987 if not (force or self.call_pdb):
987 if not (force or self.call_pdb):
988 return
988 return
989
989
990 if not hasattr(sys,'last_traceback'):
990 if not hasattr(sys,'last_traceback'):
991 error('No traceback has been produced, nothing to debug.')
991 error('No traceback has been produced, nothing to debug.')
992 return
992 return
993
993
994 # use pydb if available
995 if debugger.has_pydb:
996 from pydb import pm
997 else:
998 # fallback to our internal debugger
999 pm = lambda : self.InteractiveTB.debugger(force=True)
1000
994
1001 with self.readline_no_record:
995 with self.readline_no_record:
1002 pm()
996 self.InteractiveTB.debugger(force=True)
1003
997
1004 #-------------------------------------------------------------------------
998 #-------------------------------------------------------------------------
1005 # Things related to IPython's various namespaces
999 # Things related to IPython's various namespaces
1006 #-------------------------------------------------------------------------
1000 #-------------------------------------------------------------------------
1007 default_user_namespaces = True
1001 default_user_namespaces = True
1008
1002
1009 def init_create_namespaces(self, user_module=None, user_ns=None):
1003 def init_create_namespaces(self, user_module=None, user_ns=None):
1010 # Create the namespace where the user will operate. user_ns is
1004 # Create the namespace where the user will operate. user_ns is
1011 # normally the only one used, and it is passed to the exec calls as
1005 # normally the only one used, and it is passed to the exec calls as
1012 # the locals argument. But we do carry a user_global_ns namespace
1006 # the locals argument. But we do carry a user_global_ns namespace
1013 # given as the exec 'globals' argument, This is useful in embedding
1007 # given as the exec 'globals' argument, This is useful in embedding
1014 # situations where the ipython shell opens in a context where the
1008 # situations where the ipython shell opens in a context where the
1015 # distinction between locals and globals is meaningful. For
1009 # distinction between locals and globals is meaningful. For
1016 # non-embedded contexts, it is just the same object as the user_ns dict.
1010 # non-embedded contexts, it is just the same object as the user_ns dict.
1017
1011
1018 # FIXME. For some strange reason, __builtins__ is showing up at user
1012 # FIXME. For some strange reason, __builtins__ is showing up at user
1019 # level as a dict instead of a module. This is a manual fix, but I
1013 # level as a dict instead of a module. This is a manual fix, but I
1020 # should really track down where the problem is coming from. Alex
1014 # should really track down where the problem is coming from. Alex
1021 # Schmolck reported this problem first.
1015 # Schmolck reported this problem first.
1022
1016
1023 # A useful post by Alex Martelli on this topic:
1017 # A useful post by Alex Martelli on this topic:
1024 # Re: inconsistent value from __builtins__
1018 # Re: inconsistent value from __builtins__
1025 # Von: Alex Martelli <aleaxit@yahoo.com>
1019 # Von: Alex Martelli <aleaxit@yahoo.com>
1026 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1020 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1027 # Gruppen: comp.lang.python
1021 # Gruppen: comp.lang.python
1028
1022
1029 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1023 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1030 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1024 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1031 # > <type 'dict'>
1025 # > <type 'dict'>
1032 # > >>> print type(__builtins__)
1026 # > >>> print type(__builtins__)
1033 # > <type 'module'>
1027 # > <type 'module'>
1034 # > Is this difference in return value intentional?
1028 # > Is this difference in return value intentional?
1035
1029
1036 # Well, it's documented that '__builtins__' can be either a dictionary
1030 # Well, it's documented that '__builtins__' can be either a dictionary
1037 # or a module, and it's been that way for a long time. Whether it's
1031 # or a module, and it's been that way for a long time. Whether it's
1038 # intentional (or sensible), I don't know. In any case, the idea is
1032 # intentional (or sensible), I don't know. In any case, the idea is
1039 # that if you need to access the built-in namespace directly, you
1033 # that if you need to access the built-in namespace directly, you
1040 # should start with "import __builtin__" (note, no 's') which will
1034 # should start with "import __builtin__" (note, no 's') which will
1041 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1035 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1042
1036
1043 # These routines return a properly built module and dict as needed by
1037 # These routines return a properly built module and dict as needed by
1044 # the rest of the code, and can also be used by extension writers to
1038 # the rest of the code, and can also be used by extension writers to
1045 # generate properly initialized namespaces.
1039 # generate properly initialized namespaces.
1046 if (user_ns is not None) or (user_module is not None):
1040 if (user_ns is not None) or (user_module is not None):
1047 self.default_user_namespaces = False
1041 self.default_user_namespaces = False
1048 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1042 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1049
1043
1050 # A record of hidden variables we have added to the user namespace, so
1044 # A record of hidden variables we have added to the user namespace, so
1051 # we can list later only variables defined in actual interactive use.
1045 # we can list later only variables defined in actual interactive use.
1052 self.user_ns_hidden = {}
1046 self.user_ns_hidden = {}
1053
1047
1054 # Now that FakeModule produces a real module, we've run into a nasty
1048 # Now that FakeModule produces a real module, we've run into a nasty
1055 # problem: after script execution (via %run), the module where the user
1049 # problem: after script execution (via %run), the module where the user
1056 # code ran is deleted. Now that this object is a true module (needed
1050 # code ran is deleted. Now that this object is a true module (needed
1057 # so doctest and other tools work correctly), the Python module
1051 # so doctest and other tools work correctly), the Python module
1058 # teardown mechanism runs over it, and sets to None every variable
1052 # teardown mechanism runs over it, and sets to None every variable
1059 # present in that module. Top-level references to objects from the
1053 # present in that module. Top-level references to objects from the
1060 # script survive, because the user_ns is updated with them. However,
1054 # script survive, because the user_ns is updated with them. However,
1061 # calling functions defined in the script that use other things from
1055 # calling functions defined in the script that use other things from
1062 # the script will fail, because the function's closure had references
1056 # the script will fail, because the function's closure had references
1063 # to the original objects, which are now all None. So we must protect
1057 # to the original objects, which are now all None. So we must protect
1064 # these modules from deletion by keeping a cache.
1058 # these modules from deletion by keeping a cache.
1065 #
1059 #
1066 # To avoid keeping stale modules around (we only need the one from the
1060 # To avoid keeping stale modules around (we only need the one from the
1067 # last run), we use a dict keyed with the full path to the script, so
1061 # last run), we use a dict keyed with the full path to the script, so
1068 # only the last version of the module is held in the cache. Note,
1062 # only the last version of the module is held in the cache. Note,
1069 # however, that we must cache the module *namespace contents* (their
1063 # however, that we must cache the module *namespace contents* (their
1070 # __dict__). Because if we try to cache the actual modules, old ones
1064 # __dict__). Because if we try to cache the actual modules, old ones
1071 # (uncached) could be destroyed while still holding references (such as
1065 # (uncached) could be destroyed while still holding references (such as
1072 # those held by GUI objects that tend to be long-lived)>
1066 # those held by GUI objects that tend to be long-lived)>
1073 #
1067 #
1074 # The %reset command will flush this cache. See the cache_main_mod()
1068 # The %reset command will flush this cache. See the cache_main_mod()
1075 # and clear_main_mod_cache() methods for details on use.
1069 # and clear_main_mod_cache() methods for details on use.
1076
1070
1077 # This is the cache used for 'main' namespaces
1071 # This is the cache used for 'main' namespaces
1078 self._main_mod_cache = {}
1072 self._main_mod_cache = {}
1079
1073
1080 # A table holding all the namespaces IPython deals with, so that
1074 # A table holding all the namespaces IPython deals with, so that
1081 # introspection facilities can search easily.
1075 # introspection facilities can search easily.
1082 self.ns_table = {'user_global':self.user_module.__dict__,
1076 self.ns_table = {'user_global':self.user_module.__dict__,
1083 'user_local':self.user_ns,
1077 'user_local':self.user_ns,
1084 'builtin':builtin_mod.__dict__
1078 'builtin':builtin_mod.__dict__
1085 }
1079 }
1086
1080
1087 @property
1081 @property
1088 def user_global_ns(self):
1082 def user_global_ns(self):
1089 return self.user_module.__dict__
1083 return self.user_module.__dict__
1090
1084
1091 def prepare_user_module(self, user_module=None, user_ns=None):
1085 def prepare_user_module(self, user_module=None, user_ns=None):
1092 """Prepare the module and namespace in which user code will be run.
1086 """Prepare the module and namespace in which user code will be run.
1093
1087
1094 When IPython is started normally, both parameters are None: a new module
1088 When IPython is started normally, both parameters are None: a new module
1095 is created automatically, and its __dict__ used as the namespace.
1089 is created automatically, and its __dict__ used as the namespace.
1096
1090
1097 If only user_module is provided, its __dict__ is used as the namespace.
1091 If only user_module is provided, its __dict__ is used as the namespace.
1098 If only user_ns is provided, a dummy module is created, and user_ns
1092 If only user_ns is provided, a dummy module is created, and user_ns
1099 becomes the global namespace. If both are provided (as they may be
1093 becomes the global namespace. If both are provided (as they may be
1100 when embedding), user_ns is the local namespace, and user_module
1094 when embedding), user_ns is the local namespace, and user_module
1101 provides the global namespace.
1095 provides the global namespace.
1102
1096
1103 Parameters
1097 Parameters
1104 ----------
1098 ----------
1105 user_module : module, optional
1099 user_module : module, optional
1106 The current user module in which IPython is being run. If None,
1100 The current user module in which IPython is being run. If None,
1107 a clean module will be created.
1101 a clean module will be created.
1108 user_ns : dict, optional
1102 user_ns : dict, optional
1109 A namespace in which to run interactive commands.
1103 A namespace in which to run interactive commands.
1110
1104
1111 Returns
1105 Returns
1112 -------
1106 -------
1113 A tuple of user_module and user_ns, each properly initialised.
1107 A tuple of user_module and user_ns, each properly initialised.
1114 """
1108 """
1115 if user_module is None and user_ns is not None:
1109 if user_module is None and user_ns is not None:
1116 user_ns.setdefault("__name__", "__main__")
1110 user_ns.setdefault("__name__", "__main__")
1117 user_module = DummyMod()
1111 user_module = DummyMod()
1118 user_module.__dict__ = user_ns
1112 user_module.__dict__ = user_ns
1119
1113
1120 if user_module is None:
1114 if user_module is None:
1121 user_module = types.ModuleType("__main__",
1115 user_module = types.ModuleType("__main__",
1122 doc="Automatically created module for IPython interactive environment")
1116 doc="Automatically created module for IPython interactive environment")
1123
1117
1124 # We must ensure that __builtin__ (without the final 's') is always
1118 # We must ensure that __builtin__ (without the final 's') is always
1125 # available and pointing to the __builtin__ *module*. For more details:
1119 # available and pointing to the __builtin__ *module*. For more details:
1126 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1120 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1127 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1121 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1128 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1122 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1129
1123
1130 if user_ns is None:
1124 if user_ns is None:
1131 user_ns = user_module.__dict__
1125 user_ns = user_module.__dict__
1132
1126
1133 return user_module, user_ns
1127 return user_module, user_ns
1134
1128
1135 def init_sys_modules(self):
1129 def init_sys_modules(self):
1136 # We need to insert into sys.modules something that looks like a
1130 # We need to insert into sys.modules something that looks like a
1137 # module but which accesses the IPython namespace, for shelve and
1131 # module but which accesses the IPython namespace, for shelve and
1138 # pickle to work interactively. Normally they rely on getting
1132 # pickle to work interactively. Normally they rely on getting
1139 # everything out of __main__, but for embedding purposes each IPython
1133 # everything out of __main__, but for embedding purposes each IPython
1140 # instance has its own private namespace, so we can't go shoving
1134 # instance has its own private namespace, so we can't go shoving
1141 # everything into __main__.
1135 # everything into __main__.
1142
1136
1143 # note, however, that we should only do this for non-embedded
1137 # note, however, that we should only do this for non-embedded
1144 # ipythons, which really mimic the __main__.__dict__ with their own
1138 # ipythons, which really mimic the __main__.__dict__ with their own
1145 # namespace. Embedded instances, on the other hand, should not do
1139 # namespace. Embedded instances, on the other hand, should not do
1146 # this because they need to manage the user local/global namespaces
1140 # this because they need to manage the user local/global namespaces
1147 # only, but they live within a 'normal' __main__ (meaning, they
1141 # only, but they live within a 'normal' __main__ (meaning, they
1148 # shouldn't overtake the execution environment of the script they're
1142 # shouldn't overtake the execution environment of the script they're
1149 # embedded in).
1143 # embedded in).
1150
1144
1151 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1145 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1152 main_name = self.user_module.__name__
1146 main_name = self.user_module.__name__
1153 sys.modules[main_name] = self.user_module
1147 sys.modules[main_name] = self.user_module
1154
1148
1155 def init_user_ns(self):
1149 def init_user_ns(self):
1156 """Initialize all user-visible namespaces to their minimum defaults.
1150 """Initialize all user-visible namespaces to their minimum defaults.
1157
1151
1158 Certain history lists are also initialized here, as they effectively
1152 Certain history lists are also initialized here, as they effectively
1159 act as user namespaces.
1153 act as user namespaces.
1160
1154
1161 Notes
1155 Notes
1162 -----
1156 -----
1163 All data structures here are only filled in, they are NOT reset by this
1157 All data structures here are only filled in, they are NOT reset by this
1164 method. If they were not empty before, data will simply be added to
1158 method. If they were not empty before, data will simply be added to
1165 therm.
1159 therm.
1166 """
1160 """
1167 # This function works in two parts: first we put a few things in
1161 # This function works in two parts: first we put a few things in
1168 # user_ns, and we sync that contents into user_ns_hidden so that these
1162 # user_ns, and we sync that contents into user_ns_hidden so that these
1169 # initial variables aren't shown by %who. After the sync, we add the
1163 # initial variables aren't shown by %who. After the sync, we add the
1170 # rest of what we *do* want the user to see with %who even on a new
1164 # rest of what we *do* want the user to see with %who even on a new
1171 # session (probably nothing, so they really only see their own stuff)
1165 # session (probably nothing, so they really only see their own stuff)
1172
1166
1173 # The user dict must *always* have a __builtin__ reference to the
1167 # The user dict must *always* have a __builtin__ reference to the
1174 # Python standard __builtin__ namespace, which must be imported.
1168 # Python standard __builtin__ namespace, which must be imported.
1175 # This is so that certain operations in prompt evaluation can be
1169 # This is so that certain operations in prompt evaluation can be
1176 # reliably executed with builtins. Note that we can NOT use
1170 # reliably executed with builtins. Note that we can NOT use
1177 # __builtins__ (note the 's'), because that can either be a dict or a
1171 # __builtins__ (note the 's'), because that can either be a dict or a
1178 # module, and can even mutate at runtime, depending on the context
1172 # module, and can even mutate at runtime, depending on the context
1179 # (Python makes no guarantees on it). In contrast, __builtin__ is
1173 # (Python makes no guarantees on it). In contrast, __builtin__ is
1180 # always a module object, though it must be explicitly imported.
1174 # always a module object, though it must be explicitly imported.
1181
1175
1182 # For more details:
1176 # For more details:
1183 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1177 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1184 ns = dict()
1178 ns = dict()
1185
1179
1186 # make global variables for user access to the histories
1180 # make global variables for user access to the histories
1187 ns['_ih'] = self.history_manager.input_hist_parsed
1181 ns['_ih'] = self.history_manager.input_hist_parsed
1188 ns['_oh'] = self.history_manager.output_hist
1182 ns['_oh'] = self.history_manager.output_hist
1189 ns['_dh'] = self.history_manager.dir_hist
1183 ns['_dh'] = self.history_manager.dir_hist
1190
1184
1191 ns['_sh'] = shadowns
1185 ns['_sh'] = shadowns
1192
1186
1193 # user aliases to input and output histories. These shouldn't show up
1187 # user aliases to input and output histories. These shouldn't show up
1194 # in %who, as they can have very large reprs.
1188 # in %who, as they can have very large reprs.
1195 ns['In'] = self.history_manager.input_hist_parsed
1189 ns['In'] = self.history_manager.input_hist_parsed
1196 ns['Out'] = self.history_manager.output_hist
1190 ns['Out'] = self.history_manager.output_hist
1197
1191
1198 # Store myself as the public api!!!
1192 # Store myself as the public api!!!
1199 ns['get_ipython'] = self.get_ipython
1193 ns['get_ipython'] = self.get_ipython
1200
1194
1201 ns['exit'] = self.exiter
1195 ns['exit'] = self.exiter
1202 ns['quit'] = self.exiter
1196 ns['quit'] = self.exiter
1203
1197
1204 # Sync what we've added so far to user_ns_hidden so these aren't seen
1198 # Sync what we've added so far to user_ns_hidden so these aren't seen
1205 # by %who
1199 # by %who
1206 self.user_ns_hidden.update(ns)
1200 self.user_ns_hidden.update(ns)
1207
1201
1208 # Anything put into ns now would show up in %who. Think twice before
1202 # Anything put into ns now would show up in %who. Think twice before
1209 # putting anything here, as we really want %who to show the user their
1203 # putting anything here, as we really want %who to show the user their
1210 # stuff, not our variables.
1204 # stuff, not our variables.
1211
1205
1212 # Finally, update the real user's namespace
1206 # Finally, update the real user's namespace
1213 self.user_ns.update(ns)
1207 self.user_ns.update(ns)
1214
1208
1215 @property
1209 @property
1216 def all_ns_refs(self):
1210 def all_ns_refs(self):
1217 """Get a list of references to all the namespace dictionaries in which
1211 """Get a list of references to all the namespace dictionaries in which
1218 IPython might store a user-created object.
1212 IPython might store a user-created object.
1219
1213
1220 Note that this does not include the displayhook, which also caches
1214 Note that this does not include the displayhook, which also caches
1221 objects from the output."""
1215 objects from the output."""
1222 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1216 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1223 [m.__dict__ for m in self._main_mod_cache.values()]
1217 [m.__dict__ for m in self._main_mod_cache.values()]
1224
1218
1225 def reset(self, new_session=True):
1219 def reset(self, new_session=True):
1226 """Clear all internal namespaces, and attempt to release references to
1220 """Clear all internal namespaces, and attempt to release references to
1227 user objects.
1221 user objects.
1228
1222
1229 If new_session is True, a new history session will be opened.
1223 If new_session is True, a new history session will be opened.
1230 """
1224 """
1231 # Clear histories
1225 # Clear histories
1232 self.history_manager.reset(new_session)
1226 self.history_manager.reset(new_session)
1233 # Reset counter used to index all histories
1227 # Reset counter used to index all histories
1234 if new_session:
1228 if new_session:
1235 self.execution_count = 1
1229 self.execution_count = 1
1236
1230
1237 # Flush cached output items
1231 # Flush cached output items
1238 if self.displayhook.do_full_cache:
1232 if self.displayhook.do_full_cache:
1239 self.displayhook.flush()
1233 self.displayhook.flush()
1240
1234
1241 # The main execution namespaces must be cleared very carefully,
1235 # The main execution namespaces must be cleared very carefully,
1242 # skipping the deletion of the builtin-related keys, because doing so
1236 # skipping the deletion of the builtin-related keys, because doing so
1243 # would cause errors in many object's __del__ methods.
1237 # would cause errors in many object's __del__ methods.
1244 if self.user_ns is not self.user_global_ns:
1238 if self.user_ns is not self.user_global_ns:
1245 self.user_ns.clear()
1239 self.user_ns.clear()
1246 ns = self.user_global_ns
1240 ns = self.user_global_ns
1247 drop_keys = set(ns.keys())
1241 drop_keys = set(ns.keys())
1248 drop_keys.discard('__builtin__')
1242 drop_keys.discard('__builtin__')
1249 drop_keys.discard('__builtins__')
1243 drop_keys.discard('__builtins__')
1250 drop_keys.discard('__name__')
1244 drop_keys.discard('__name__')
1251 for k in drop_keys:
1245 for k in drop_keys:
1252 del ns[k]
1246 del ns[k]
1253
1247
1254 self.user_ns_hidden.clear()
1248 self.user_ns_hidden.clear()
1255
1249
1256 # Restore the user namespaces to minimal usability
1250 # Restore the user namespaces to minimal usability
1257 self.init_user_ns()
1251 self.init_user_ns()
1258
1252
1259 # Restore the default and user aliases
1253 # Restore the default and user aliases
1260 self.alias_manager.clear_aliases()
1254 self.alias_manager.clear_aliases()
1261 self.alias_manager.init_aliases()
1255 self.alias_manager.init_aliases()
1262
1256
1263 # Flush the private list of module references kept for script
1257 # Flush the private list of module references kept for script
1264 # execution protection
1258 # execution protection
1265 self.clear_main_mod_cache()
1259 self.clear_main_mod_cache()
1266
1260
1267 def del_var(self, varname, by_name=False):
1261 def del_var(self, varname, by_name=False):
1268 """Delete a variable from the various namespaces, so that, as
1262 """Delete a variable from the various namespaces, so that, as
1269 far as possible, we're not keeping any hidden references to it.
1263 far as possible, we're not keeping any hidden references to it.
1270
1264
1271 Parameters
1265 Parameters
1272 ----------
1266 ----------
1273 varname : str
1267 varname : str
1274 The name of the variable to delete.
1268 The name of the variable to delete.
1275 by_name : bool
1269 by_name : bool
1276 If True, delete variables with the given name in each
1270 If True, delete variables with the given name in each
1277 namespace. If False (default), find the variable in the user
1271 namespace. If False (default), find the variable in the user
1278 namespace, and delete references to it.
1272 namespace, and delete references to it.
1279 """
1273 """
1280 if varname in ('__builtin__', '__builtins__'):
1274 if varname in ('__builtin__', '__builtins__'):
1281 raise ValueError("Refusing to delete %s" % varname)
1275 raise ValueError("Refusing to delete %s" % varname)
1282
1276
1283 ns_refs = self.all_ns_refs
1277 ns_refs = self.all_ns_refs
1284
1278
1285 if by_name: # Delete by name
1279 if by_name: # Delete by name
1286 for ns in ns_refs:
1280 for ns in ns_refs:
1287 try:
1281 try:
1288 del ns[varname]
1282 del ns[varname]
1289 except KeyError:
1283 except KeyError:
1290 pass
1284 pass
1291 else: # Delete by object
1285 else: # Delete by object
1292 try:
1286 try:
1293 obj = self.user_ns[varname]
1287 obj = self.user_ns[varname]
1294 except KeyError:
1288 except KeyError:
1295 raise NameError("name '%s' is not defined" % varname)
1289 raise NameError("name '%s' is not defined" % varname)
1296 # Also check in output history
1290 # Also check in output history
1297 ns_refs.append(self.history_manager.output_hist)
1291 ns_refs.append(self.history_manager.output_hist)
1298 for ns in ns_refs:
1292 for ns in ns_refs:
1299 to_delete = [n for n, o in iteritems(ns) if o is obj]
1293 to_delete = [n for n, o in iteritems(ns) if o is obj]
1300 for name in to_delete:
1294 for name in to_delete:
1301 del ns[name]
1295 del ns[name]
1302
1296
1303 # displayhook keeps extra references, but not in a dictionary
1297 # displayhook keeps extra references, but not in a dictionary
1304 for name in ('_', '__', '___'):
1298 for name in ('_', '__', '___'):
1305 if getattr(self.displayhook, name) is obj:
1299 if getattr(self.displayhook, name) is obj:
1306 setattr(self.displayhook, name, None)
1300 setattr(self.displayhook, name, None)
1307
1301
1308 def reset_selective(self, regex=None):
1302 def reset_selective(self, regex=None):
1309 """Clear selective variables from internal namespaces based on a
1303 """Clear selective variables from internal namespaces based on a
1310 specified regular expression.
1304 specified regular expression.
1311
1305
1312 Parameters
1306 Parameters
1313 ----------
1307 ----------
1314 regex : string or compiled pattern, optional
1308 regex : string or compiled pattern, optional
1315 A regular expression pattern that will be used in searching
1309 A regular expression pattern that will be used in searching
1316 variable names in the users namespaces.
1310 variable names in the users namespaces.
1317 """
1311 """
1318 if regex is not None:
1312 if regex is not None:
1319 try:
1313 try:
1320 m = re.compile(regex)
1314 m = re.compile(regex)
1321 except TypeError:
1315 except TypeError:
1322 raise TypeError('regex must be a string or compiled pattern')
1316 raise TypeError('regex must be a string or compiled pattern')
1323 # Search for keys in each namespace that match the given regex
1317 # Search for keys in each namespace that match the given regex
1324 # If a match is found, delete the key/value pair.
1318 # If a match is found, delete the key/value pair.
1325 for ns in self.all_ns_refs:
1319 for ns in self.all_ns_refs:
1326 for var in ns:
1320 for var in ns:
1327 if m.search(var):
1321 if m.search(var):
1328 del ns[var]
1322 del ns[var]
1329
1323
1330 def push(self, variables, interactive=True):
1324 def push(self, variables, interactive=True):
1331 """Inject a group of variables into the IPython user namespace.
1325 """Inject a group of variables into the IPython user namespace.
1332
1326
1333 Parameters
1327 Parameters
1334 ----------
1328 ----------
1335 variables : dict, str or list/tuple of str
1329 variables : dict, str or list/tuple of str
1336 The variables to inject into the user's namespace. If a dict, a
1330 The variables to inject into the user's namespace. If a dict, a
1337 simple update is done. If a str, the string is assumed to have
1331 simple update is done. If a str, the string is assumed to have
1338 variable names separated by spaces. A list/tuple of str can also
1332 variable names separated by spaces. A list/tuple of str can also
1339 be used to give the variable names. If just the variable names are
1333 be used to give the variable names. If just the variable names are
1340 give (list/tuple/str) then the variable values looked up in the
1334 give (list/tuple/str) then the variable values looked up in the
1341 callers frame.
1335 callers frame.
1342 interactive : bool
1336 interactive : bool
1343 If True (default), the variables will be listed with the ``who``
1337 If True (default), the variables will be listed with the ``who``
1344 magic.
1338 magic.
1345 """
1339 """
1346 vdict = None
1340 vdict = None
1347
1341
1348 # We need a dict of name/value pairs to do namespace updates.
1342 # We need a dict of name/value pairs to do namespace updates.
1349 if isinstance(variables, dict):
1343 if isinstance(variables, dict):
1350 vdict = variables
1344 vdict = variables
1351 elif isinstance(variables, string_types+(list, tuple)):
1345 elif isinstance(variables, string_types+(list, tuple)):
1352 if isinstance(variables, string_types):
1346 if isinstance(variables, string_types):
1353 vlist = variables.split()
1347 vlist = variables.split()
1354 else:
1348 else:
1355 vlist = variables
1349 vlist = variables
1356 vdict = {}
1350 vdict = {}
1357 cf = sys._getframe(1)
1351 cf = sys._getframe(1)
1358 for name in vlist:
1352 for name in vlist:
1359 try:
1353 try:
1360 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1354 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1361 except:
1355 except:
1362 print('Could not get variable %s from %s' %
1356 print('Could not get variable %s from %s' %
1363 (name,cf.f_code.co_name))
1357 (name,cf.f_code.co_name))
1364 else:
1358 else:
1365 raise ValueError('variables must be a dict/str/list/tuple')
1359 raise ValueError('variables must be a dict/str/list/tuple')
1366
1360
1367 # Propagate variables to user namespace
1361 # Propagate variables to user namespace
1368 self.user_ns.update(vdict)
1362 self.user_ns.update(vdict)
1369
1363
1370 # And configure interactive visibility
1364 # And configure interactive visibility
1371 user_ns_hidden = self.user_ns_hidden
1365 user_ns_hidden = self.user_ns_hidden
1372 if interactive:
1366 if interactive:
1373 for name in vdict:
1367 for name in vdict:
1374 user_ns_hidden.pop(name, None)
1368 user_ns_hidden.pop(name, None)
1375 else:
1369 else:
1376 user_ns_hidden.update(vdict)
1370 user_ns_hidden.update(vdict)
1377
1371
1378 def drop_by_id(self, variables):
1372 def drop_by_id(self, variables):
1379 """Remove a dict of variables from the user namespace, if they are the
1373 """Remove a dict of variables from the user namespace, if they are the
1380 same as the values in the dictionary.
1374 same as the values in the dictionary.
1381
1375
1382 This is intended for use by extensions: variables that they've added can
1376 This is intended for use by extensions: variables that they've added can
1383 be taken back out if they are unloaded, without removing any that the
1377 be taken back out if they are unloaded, without removing any that the
1384 user has overwritten.
1378 user has overwritten.
1385
1379
1386 Parameters
1380 Parameters
1387 ----------
1381 ----------
1388 variables : dict
1382 variables : dict
1389 A dictionary mapping object names (as strings) to the objects.
1383 A dictionary mapping object names (as strings) to the objects.
1390 """
1384 """
1391 for name, obj in iteritems(variables):
1385 for name, obj in iteritems(variables):
1392 if name in self.user_ns and self.user_ns[name] is obj:
1386 if name in self.user_ns and self.user_ns[name] is obj:
1393 del self.user_ns[name]
1387 del self.user_ns[name]
1394 self.user_ns_hidden.pop(name, None)
1388 self.user_ns_hidden.pop(name, None)
1395
1389
1396 #-------------------------------------------------------------------------
1390 #-------------------------------------------------------------------------
1397 # Things related to object introspection
1391 # Things related to object introspection
1398 #-------------------------------------------------------------------------
1392 #-------------------------------------------------------------------------
1399
1393
1400 def _ofind(self, oname, namespaces=None):
1394 def _ofind(self, oname, namespaces=None):
1401 """Find an object in the available namespaces.
1395 """Find an object in the available namespaces.
1402
1396
1403 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1397 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1404
1398
1405 Has special code to detect magic functions.
1399 Has special code to detect magic functions.
1406 """
1400 """
1407 oname = oname.strip()
1401 oname = oname.strip()
1408 #print '1- oname: <%r>' % oname # dbg
1402 #print '1- oname: <%r>' % oname # dbg
1409 if not oname.startswith(ESC_MAGIC) and \
1403 if not oname.startswith(ESC_MAGIC) and \
1410 not oname.startswith(ESC_MAGIC2) and \
1404 not oname.startswith(ESC_MAGIC2) and \
1411 not py3compat.isidentifier(oname, dotted=True):
1405 not py3compat.isidentifier(oname, dotted=True):
1412 return dict(found=False)
1406 return dict(found=False)
1413
1407
1414 if namespaces is None:
1408 if namespaces is None:
1415 # Namespaces to search in:
1409 # Namespaces to search in:
1416 # Put them in a list. The order is important so that we
1410 # Put them in a list. The order is important so that we
1417 # find things in the same order that Python finds them.
1411 # find things in the same order that Python finds them.
1418 namespaces = [ ('Interactive', self.user_ns),
1412 namespaces = [ ('Interactive', self.user_ns),
1419 ('Interactive (global)', self.user_global_ns),
1413 ('Interactive (global)', self.user_global_ns),
1420 ('Python builtin', builtin_mod.__dict__),
1414 ('Python builtin', builtin_mod.__dict__),
1421 ]
1415 ]
1422
1416
1423 # initialize results to 'null'
1417 # initialize results to 'null'
1424 found = False; obj = None; ospace = None;
1418 found = False; obj = None; ospace = None;
1425 ismagic = False; isalias = False; parent = None
1419 ismagic = False; isalias = False; parent = None
1426
1420
1427 # We need to special-case 'print', which as of python2.6 registers as a
1421 # We need to special-case 'print', which as of python2.6 registers as a
1428 # function but should only be treated as one if print_function was
1422 # function but should only be treated as one if print_function was
1429 # loaded with a future import. In this case, just bail.
1423 # loaded with a future import. In this case, just bail.
1430 if (oname == 'print' and not py3compat.PY3 and not \
1424 if (oname == 'print' and not py3compat.PY3 and not \
1431 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1425 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1432 return {'found':found, 'obj':obj, 'namespace':ospace,
1426 return {'found':found, 'obj':obj, 'namespace':ospace,
1433 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1427 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1434
1428
1435 # Look for the given name by splitting it in parts. If the head is
1429 # Look for the given name by splitting it in parts. If the head is
1436 # found, then we look for all the remaining parts as members, and only
1430 # found, then we look for all the remaining parts as members, and only
1437 # declare success if we can find them all.
1431 # declare success if we can find them all.
1438 oname_parts = oname.split('.')
1432 oname_parts = oname.split('.')
1439 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1433 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1440 for nsname,ns in namespaces:
1434 for nsname,ns in namespaces:
1441 try:
1435 try:
1442 obj = ns[oname_head]
1436 obj = ns[oname_head]
1443 except KeyError:
1437 except KeyError:
1444 continue
1438 continue
1445 else:
1439 else:
1446 #print 'oname_rest:', oname_rest # dbg
1440 #print 'oname_rest:', oname_rest # dbg
1447 for idx, part in enumerate(oname_rest):
1441 for idx, part in enumerate(oname_rest):
1448 try:
1442 try:
1449 parent = obj
1443 parent = obj
1450 # The last part is looked up in a special way to avoid
1444 # The last part is looked up in a special way to avoid
1451 # descriptor invocation as it may raise or have side
1445 # descriptor invocation as it may raise or have side
1452 # effects.
1446 # effects.
1453 if idx == len(oname_rest) - 1:
1447 if idx == len(oname_rest) - 1:
1454 obj = self._getattr_property(obj, part)
1448 obj = self._getattr_property(obj, part)
1455 else:
1449 else:
1456 obj = getattr(obj, part)
1450 obj = getattr(obj, part)
1457 except:
1451 except:
1458 # Blanket except b/c some badly implemented objects
1452 # Blanket except b/c some badly implemented objects
1459 # allow __getattr__ to raise exceptions other than
1453 # allow __getattr__ to raise exceptions other than
1460 # AttributeError, which then crashes IPython.
1454 # AttributeError, which then crashes IPython.
1461 break
1455 break
1462 else:
1456 else:
1463 # If we finish the for loop (no break), we got all members
1457 # If we finish the for loop (no break), we got all members
1464 found = True
1458 found = True
1465 ospace = nsname
1459 ospace = nsname
1466 break # namespace loop
1460 break # namespace loop
1467
1461
1468 # Try to see if it's magic
1462 # Try to see if it's magic
1469 if not found:
1463 if not found:
1470 obj = None
1464 obj = None
1471 if oname.startswith(ESC_MAGIC2):
1465 if oname.startswith(ESC_MAGIC2):
1472 oname = oname.lstrip(ESC_MAGIC2)
1466 oname = oname.lstrip(ESC_MAGIC2)
1473 obj = self.find_cell_magic(oname)
1467 obj = self.find_cell_magic(oname)
1474 elif oname.startswith(ESC_MAGIC):
1468 elif oname.startswith(ESC_MAGIC):
1475 oname = oname.lstrip(ESC_MAGIC)
1469 oname = oname.lstrip(ESC_MAGIC)
1476 obj = self.find_line_magic(oname)
1470 obj = self.find_line_magic(oname)
1477 else:
1471 else:
1478 # search without prefix, so run? will find %run?
1472 # search without prefix, so run? will find %run?
1479 obj = self.find_line_magic(oname)
1473 obj = self.find_line_magic(oname)
1480 if obj is None:
1474 if obj is None:
1481 obj = self.find_cell_magic(oname)
1475 obj = self.find_cell_magic(oname)
1482 if obj is not None:
1476 if obj is not None:
1483 found = True
1477 found = True
1484 ospace = 'IPython internal'
1478 ospace = 'IPython internal'
1485 ismagic = True
1479 ismagic = True
1486 isalias = isinstance(obj, Alias)
1480 isalias = isinstance(obj, Alias)
1487
1481
1488 # Last try: special-case some literals like '', [], {}, etc:
1482 # Last try: special-case some literals like '', [], {}, etc:
1489 if not found and oname_head in ["''",'""','[]','{}','()']:
1483 if not found and oname_head in ["''",'""','[]','{}','()']:
1490 obj = eval(oname_head)
1484 obj = eval(oname_head)
1491 found = True
1485 found = True
1492 ospace = 'Interactive'
1486 ospace = 'Interactive'
1493
1487
1494 return {'found':found, 'obj':obj, 'namespace':ospace,
1488 return {'found':found, 'obj':obj, 'namespace':ospace,
1495 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1489 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1496
1490
1497 @staticmethod
1491 @staticmethod
1498 def _getattr_property(obj, attrname):
1492 def _getattr_property(obj, attrname):
1499 """Property-aware getattr to use in object finding.
1493 """Property-aware getattr to use in object finding.
1500
1494
1501 If attrname represents a property, return it unevaluated (in case it has
1495 If attrname represents a property, return it unevaluated (in case it has
1502 side effects or raises an error.
1496 side effects or raises an error.
1503
1497
1504 """
1498 """
1505 if not isinstance(obj, type):
1499 if not isinstance(obj, type):
1506 try:
1500 try:
1507 # `getattr(type(obj), attrname)` is not guaranteed to return
1501 # `getattr(type(obj), attrname)` is not guaranteed to return
1508 # `obj`, but does so for property:
1502 # `obj`, but does so for property:
1509 #
1503 #
1510 # property.__get__(self, None, cls) -> self
1504 # property.__get__(self, None, cls) -> self
1511 #
1505 #
1512 # The universal alternative is to traverse the mro manually
1506 # The universal alternative is to traverse the mro manually
1513 # searching for attrname in class dicts.
1507 # searching for attrname in class dicts.
1514 attr = getattr(type(obj), attrname)
1508 attr = getattr(type(obj), attrname)
1515 except AttributeError:
1509 except AttributeError:
1516 pass
1510 pass
1517 else:
1511 else:
1518 # This relies on the fact that data descriptors (with both
1512 # This relies on the fact that data descriptors (with both
1519 # __get__ & __set__ magic methods) take precedence over
1513 # __get__ & __set__ magic methods) take precedence over
1520 # instance-level attributes:
1514 # instance-level attributes:
1521 #
1515 #
1522 # class A(object):
1516 # class A(object):
1523 # @property
1517 # @property
1524 # def foobar(self): return 123
1518 # def foobar(self): return 123
1525 # a = A()
1519 # a = A()
1526 # a.__dict__['foobar'] = 345
1520 # a.__dict__['foobar'] = 345
1527 # a.foobar # == 123
1521 # a.foobar # == 123
1528 #
1522 #
1529 # So, a property may be returned right away.
1523 # So, a property may be returned right away.
1530 if isinstance(attr, property):
1524 if isinstance(attr, property):
1531 return attr
1525 return attr
1532
1526
1533 # Nothing helped, fall back.
1527 # Nothing helped, fall back.
1534 return getattr(obj, attrname)
1528 return getattr(obj, attrname)
1535
1529
1536 def _object_find(self, oname, namespaces=None):
1530 def _object_find(self, oname, namespaces=None):
1537 """Find an object and return a struct with info about it."""
1531 """Find an object and return a struct with info about it."""
1538 return Struct(self._ofind(oname, namespaces))
1532 return Struct(self._ofind(oname, namespaces))
1539
1533
1540 def _inspect(self, meth, oname, namespaces=None, **kw):
1534 def _inspect(self, meth, oname, namespaces=None, **kw):
1541 """Generic interface to the inspector system.
1535 """Generic interface to the inspector system.
1542
1536
1543 This function is meant to be called by pdef, pdoc & friends."""
1537 This function is meant to be called by pdef, pdoc & friends."""
1544 info = self._object_find(oname, namespaces)
1538 info = self._object_find(oname, namespaces)
1545 if info.found:
1539 if info.found:
1546 pmethod = getattr(self.inspector, meth)
1540 pmethod = getattr(self.inspector, meth)
1547 formatter = format_screen if info.ismagic else None
1541 formatter = format_screen if info.ismagic else None
1548 if meth == 'pdoc':
1542 if meth == 'pdoc':
1549 pmethod(info.obj, oname, formatter)
1543 pmethod(info.obj, oname, formatter)
1550 elif meth == 'pinfo':
1544 elif meth == 'pinfo':
1551 pmethod(info.obj, oname, formatter, info, **kw)
1545 pmethod(info.obj, oname, formatter, info, **kw)
1552 else:
1546 else:
1553 pmethod(info.obj, oname)
1547 pmethod(info.obj, oname)
1554 else:
1548 else:
1555 print('Object `%s` not found.' % oname)
1549 print('Object `%s` not found.' % oname)
1556 return 'not found' # so callers can take other action
1550 return 'not found' # so callers can take other action
1557
1551
1558 def object_inspect(self, oname, detail_level=0):
1552 def object_inspect(self, oname, detail_level=0):
1559 """Get object info about oname"""
1553 """Get object info about oname"""
1560 with self.builtin_trap:
1554 with self.builtin_trap:
1561 info = self._object_find(oname)
1555 info = self._object_find(oname)
1562 if info.found:
1556 if info.found:
1563 return self.inspector.info(info.obj, oname, info=info,
1557 return self.inspector.info(info.obj, oname, info=info,
1564 detail_level=detail_level
1558 detail_level=detail_level
1565 )
1559 )
1566 else:
1560 else:
1567 return oinspect.object_info(name=oname, found=False)
1561 return oinspect.object_info(name=oname, found=False)
1568
1562
1569 def object_inspect_text(self, oname, detail_level=0):
1563 def object_inspect_text(self, oname, detail_level=0):
1570 """Get object info as formatted text"""
1564 """Get object info as formatted text"""
1571 with self.builtin_trap:
1565 with self.builtin_trap:
1572 info = self._object_find(oname)
1566 info = self._object_find(oname)
1573 if info.found:
1567 if info.found:
1574 return self.inspector._format_info(info.obj, oname, info=info,
1568 return self.inspector._format_info(info.obj, oname, info=info,
1575 detail_level=detail_level
1569 detail_level=detail_level
1576 )
1570 )
1577 else:
1571 else:
1578 raise KeyError(oname)
1572 raise KeyError(oname)
1579
1573
1580 #-------------------------------------------------------------------------
1574 #-------------------------------------------------------------------------
1581 # Things related to history management
1575 # Things related to history management
1582 #-------------------------------------------------------------------------
1576 #-------------------------------------------------------------------------
1583
1577
1584 def init_history(self):
1578 def init_history(self):
1585 """Sets up the command history, and starts regular autosaves."""
1579 """Sets up the command history, and starts regular autosaves."""
1586 self.history_manager = HistoryManager(shell=self, parent=self)
1580 self.history_manager = HistoryManager(shell=self, parent=self)
1587 self.configurables.append(self.history_manager)
1581 self.configurables.append(self.history_manager)
1588
1582
1589 #-------------------------------------------------------------------------
1583 #-------------------------------------------------------------------------
1590 # Things related to exception handling and tracebacks (not debugging)
1584 # Things related to exception handling and tracebacks (not debugging)
1591 #-------------------------------------------------------------------------
1585 #-------------------------------------------------------------------------
1592
1586
1593 def init_traceback_handlers(self, custom_exceptions):
1587 def init_traceback_handlers(self, custom_exceptions):
1594 # Syntax error handler.
1588 # Syntax error handler.
1595 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1589 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1596
1590
1597 # The interactive one is initialized with an offset, meaning we always
1591 # The interactive one is initialized with an offset, meaning we always
1598 # want to remove the topmost item in the traceback, which is our own
1592 # want to remove the topmost item in the traceback, which is our own
1599 # internal code. Valid modes: ['Plain','Context','Verbose']
1593 # internal code. Valid modes: ['Plain','Context','Verbose']
1600 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1594 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1601 color_scheme='NoColor',
1595 color_scheme='NoColor',
1602 tb_offset = 1,
1596 tb_offset = 1,
1603 check_cache=check_linecache_ipython)
1597 check_cache=check_linecache_ipython)
1604
1598
1605 # The instance will store a pointer to the system-wide exception hook,
1599 # The instance will store a pointer to the system-wide exception hook,
1606 # so that runtime code (such as magics) can access it. This is because
1600 # so that runtime code (such as magics) can access it. This is because
1607 # during the read-eval loop, it may get temporarily overwritten.
1601 # during the read-eval loop, it may get temporarily overwritten.
1608 self.sys_excepthook = sys.excepthook
1602 self.sys_excepthook = sys.excepthook
1609
1603
1610 # and add any custom exception handlers the user may have specified
1604 # and add any custom exception handlers the user may have specified
1611 self.set_custom_exc(*custom_exceptions)
1605 self.set_custom_exc(*custom_exceptions)
1612
1606
1613 # Set the exception mode
1607 # Set the exception mode
1614 self.InteractiveTB.set_mode(mode=self.xmode)
1608 self.InteractiveTB.set_mode(mode=self.xmode)
1615
1609
1616 def set_custom_exc(self, exc_tuple, handler):
1610 def set_custom_exc(self, exc_tuple, handler):
1617 """set_custom_exc(exc_tuple,handler)
1611 """set_custom_exc(exc_tuple,handler)
1618
1612
1619 Set a custom exception handler, which will be called if any of the
1613 Set a custom exception handler, which will be called if any of the
1620 exceptions in exc_tuple occur in the mainloop (specifically, in the
1614 exceptions in exc_tuple occur in the mainloop (specifically, in the
1621 run_code() method).
1615 run_code() method).
1622
1616
1623 Parameters
1617 Parameters
1624 ----------
1618 ----------
1625
1619
1626 exc_tuple : tuple of exception classes
1620 exc_tuple : tuple of exception classes
1627 A *tuple* of exception classes, for which to call the defined
1621 A *tuple* of exception classes, for which to call the defined
1628 handler. It is very important that you use a tuple, and NOT A
1622 handler. It is very important that you use a tuple, and NOT A
1629 LIST here, because of the way Python's except statement works. If
1623 LIST here, because of the way Python's except statement works. If
1630 you only want to trap a single exception, use a singleton tuple::
1624 you only want to trap a single exception, use a singleton tuple::
1631
1625
1632 exc_tuple == (MyCustomException,)
1626 exc_tuple == (MyCustomException,)
1633
1627
1634 handler : callable
1628 handler : callable
1635 handler must have the following signature::
1629 handler must have the following signature::
1636
1630
1637 def my_handler(self, etype, value, tb, tb_offset=None):
1631 def my_handler(self, etype, value, tb, tb_offset=None):
1638 ...
1632 ...
1639 return structured_traceback
1633 return structured_traceback
1640
1634
1641 Your handler must return a structured traceback (a list of strings),
1635 Your handler must return a structured traceback (a list of strings),
1642 or None.
1636 or None.
1643
1637
1644 This will be made into an instance method (via types.MethodType)
1638 This will be made into an instance method (via types.MethodType)
1645 of IPython itself, and it will be called if any of the exceptions
1639 of IPython itself, and it will be called if any of the exceptions
1646 listed in the exc_tuple are caught. If the handler is None, an
1640 listed in the exc_tuple are caught. If the handler is None, an
1647 internal basic one is used, which just prints basic info.
1641 internal basic one is used, which just prints basic info.
1648
1642
1649 To protect IPython from crashes, if your handler ever raises an
1643 To protect IPython from crashes, if your handler ever raises an
1650 exception or returns an invalid result, it will be immediately
1644 exception or returns an invalid result, it will be immediately
1651 disabled.
1645 disabled.
1652
1646
1653 WARNING: by putting in your own exception handler into IPython's main
1647 WARNING: by putting in your own exception handler into IPython's main
1654 execution loop, you run a very good chance of nasty crashes. This
1648 execution loop, you run a very good chance of nasty crashes. This
1655 facility should only be used if you really know what you are doing."""
1649 facility should only be used if you really know what you are doing."""
1656
1650
1657 assert type(exc_tuple)==type(()) , \
1651 assert type(exc_tuple)==type(()) , \
1658 "The custom exceptions must be given AS A TUPLE."
1652 "The custom exceptions must be given AS A TUPLE."
1659
1653
1660 def dummy_handler(self,etype,value,tb,tb_offset=None):
1654 def dummy_handler(self,etype,value,tb,tb_offset=None):
1661 print('*** Simple custom exception handler ***')
1655 print('*** Simple custom exception handler ***')
1662 print('Exception type :',etype)
1656 print('Exception type :',etype)
1663 print('Exception value:',value)
1657 print('Exception value:',value)
1664 print('Traceback :',tb)
1658 print('Traceback :',tb)
1665 #print 'Source code :','\n'.join(self.buffer)
1659 #print 'Source code :','\n'.join(self.buffer)
1666
1660
1667 def validate_stb(stb):
1661 def validate_stb(stb):
1668 """validate structured traceback return type
1662 """validate structured traceback return type
1669
1663
1670 return type of CustomTB *should* be a list of strings, but allow
1664 return type of CustomTB *should* be a list of strings, but allow
1671 single strings or None, which are harmless.
1665 single strings or None, which are harmless.
1672
1666
1673 This function will *always* return a list of strings,
1667 This function will *always* return a list of strings,
1674 and will raise a TypeError if stb is inappropriate.
1668 and will raise a TypeError if stb is inappropriate.
1675 """
1669 """
1676 msg = "CustomTB must return list of strings, not %r" % stb
1670 msg = "CustomTB must return list of strings, not %r" % stb
1677 if stb is None:
1671 if stb is None:
1678 return []
1672 return []
1679 elif isinstance(stb, string_types):
1673 elif isinstance(stb, string_types):
1680 return [stb]
1674 return [stb]
1681 elif not isinstance(stb, list):
1675 elif not isinstance(stb, list):
1682 raise TypeError(msg)
1676 raise TypeError(msg)
1683 # it's a list
1677 # it's a list
1684 for line in stb:
1678 for line in stb:
1685 # check every element
1679 # check every element
1686 if not isinstance(line, string_types):
1680 if not isinstance(line, string_types):
1687 raise TypeError(msg)
1681 raise TypeError(msg)
1688 return stb
1682 return stb
1689
1683
1690 if handler is None:
1684 if handler is None:
1691 wrapped = dummy_handler
1685 wrapped = dummy_handler
1692 else:
1686 else:
1693 def wrapped(self,etype,value,tb,tb_offset=None):
1687 def wrapped(self,etype,value,tb,tb_offset=None):
1694 """wrap CustomTB handler, to protect IPython from user code
1688 """wrap CustomTB handler, to protect IPython from user code
1695
1689
1696 This makes it harder (but not impossible) for custom exception
1690 This makes it harder (but not impossible) for custom exception
1697 handlers to crash IPython.
1691 handlers to crash IPython.
1698 """
1692 """
1699 try:
1693 try:
1700 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1694 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1701 return validate_stb(stb)
1695 return validate_stb(stb)
1702 except:
1696 except:
1703 # clear custom handler immediately
1697 # clear custom handler immediately
1704 self.set_custom_exc((), None)
1698 self.set_custom_exc((), None)
1705 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1699 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1706 # show the exception in handler first
1700 # show the exception in handler first
1707 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1701 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1708 print(self.InteractiveTB.stb2text(stb))
1702 print(self.InteractiveTB.stb2text(stb))
1709 print("The original exception:")
1703 print("The original exception:")
1710 stb = self.InteractiveTB.structured_traceback(
1704 stb = self.InteractiveTB.structured_traceback(
1711 (etype,value,tb), tb_offset=tb_offset
1705 (etype,value,tb), tb_offset=tb_offset
1712 )
1706 )
1713 return stb
1707 return stb
1714
1708
1715 self.CustomTB = types.MethodType(wrapped,self)
1709 self.CustomTB = types.MethodType(wrapped,self)
1716 self.custom_exceptions = exc_tuple
1710 self.custom_exceptions = exc_tuple
1717
1711
1718 def excepthook(self, etype, value, tb):
1712 def excepthook(self, etype, value, tb):
1719 """One more defense for GUI apps that call sys.excepthook.
1713 """One more defense for GUI apps that call sys.excepthook.
1720
1714
1721 GUI frameworks like wxPython trap exceptions and call
1715 GUI frameworks like wxPython trap exceptions and call
1722 sys.excepthook themselves. I guess this is a feature that
1716 sys.excepthook themselves. I guess this is a feature that
1723 enables them to keep running after exceptions that would
1717 enables them to keep running after exceptions that would
1724 otherwise kill their mainloop. This is a bother for IPython
1718 otherwise kill their mainloop. This is a bother for IPython
1725 which excepts to catch all of the program exceptions with a try:
1719 which excepts to catch all of the program exceptions with a try:
1726 except: statement.
1720 except: statement.
1727
1721
1728 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1722 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1729 any app directly invokes sys.excepthook, it will look to the user like
1723 any app directly invokes sys.excepthook, it will look to the user like
1730 IPython crashed. In order to work around this, we can disable the
1724 IPython crashed. In order to work around this, we can disable the
1731 CrashHandler and replace it with this excepthook instead, which prints a
1725 CrashHandler and replace it with this excepthook instead, which prints a
1732 regular traceback using our InteractiveTB. In this fashion, apps which
1726 regular traceback using our InteractiveTB. In this fashion, apps which
1733 call sys.excepthook will generate a regular-looking exception from
1727 call sys.excepthook will generate a regular-looking exception from
1734 IPython, and the CrashHandler will only be triggered by real IPython
1728 IPython, and the CrashHandler will only be triggered by real IPython
1735 crashes.
1729 crashes.
1736
1730
1737 This hook should be used sparingly, only in places which are not likely
1731 This hook should be used sparingly, only in places which are not likely
1738 to be true IPython errors.
1732 to be true IPython errors.
1739 """
1733 """
1740 self.showtraceback((etype, value, tb), tb_offset=0)
1734 self.showtraceback((etype, value, tb), tb_offset=0)
1741
1735
1742 def _get_exc_info(self, exc_tuple=None):
1736 def _get_exc_info(self, exc_tuple=None):
1743 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1737 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1744
1738
1745 Ensures sys.last_type,value,traceback hold the exc_info we found,
1739 Ensures sys.last_type,value,traceback hold the exc_info we found,
1746 from whichever source.
1740 from whichever source.
1747
1741
1748 raises ValueError if none of these contain any information
1742 raises ValueError if none of these contain any information
1749 """
1743 """
1750 if exc_tuple is None:
1744 if exc_tuple is None:
1751 etype, value, tb = sys.exc_info()
1745 etype, value, tb = sys.exc_info()
1752 else:
1746 else:
1753 etype, value, tb = exc_tuple
1747 etype, value, tb = exc_tuple
1754
1748
1755 if etype is None:
1749 if etype is None:
1756 if hasattr(sys, 'last_type'):
1750 if hasattr(sys, 'last_type'):
1757 etype, value, tb = sys.last_type, sys.last_value, \
1751 etype, value, tb = sys.last_type, sys.last_value, \
1758 sys.last_traceback
1752 sys.last_traceback
1759
1753
1760 if etype is None:
1754 if etype is None:
1761 raise ValueError("No exception to find")
1755 raise ValueError("No exception to find")
1762
1756
1763 # Now store the exception info in sys.last_type etc.
1757 # Now store the exception info in sys.last_type etc.
1764 # WARNING: these variables are somewhat deprecated and not
1758 # WARNING: these variables are somewhat deprecated and not
1765 # necessarily safe to use in a threaded environment, but tools
1759 # necessarily safe to use in a threaded environment, but tools
1766 # like pdb depend on their existence, so let's set them. If we
1760 # like pdb depend on their existence, so let's set them. If we
1767 # find problems in the field, we'll need to revisit their use.
1761 # find problems in the field, we'll need to revisit their use.
1768 sys.last_type = etype
1762 sys.last_type = etype
1769 sys.last_value = value
1763 sys.last_value = value
1770 sys.last_traceback = tb
1764 sys.last_traceback = tb
1771
1765
1772 return etype, value, tb
1766 return etype, value, tb
1773
1767
1774 def show_usage_error(self, exc):
1768 def show_usage_error(self, exc):
1775 """Show a short message for UsageErrors
1769 """Show a short message for UsageErrors
1776
1770
1777 These are special exceptions that shouldn't show a traceback.
1771 These are special exceptions that shouldn't show a traceback.
1778 """
1772 """
1779 print("UsageError: %s" % exc, file=sys.stderr)
1773 print("UsageError: %s" % exc, file=sys.stderr)
1780
1774
1781 def get_exception_only(self, exc_tuple=None):
1775 def get_exception_only(self, exc_tuple=None):
1782 """
1776 """
1783 Return as a string (ending with a newline) the exception that
1777 Return as a string (ending with a newline) the exception that
1784 just occurred, without any traceback.
1778 just occurred, without any traceback.
1785 """
1779 """
1786 etype, value, tb = self._get_exc_info(exc_tuple)
1780 etype, value, tb = self._get_exc_info(exc_tuple)
1787 msg = traceback.format_exception_only(etype, value)
1781 msg = traceback.format_exception_only(etype, value)
1788 return ''.join(msg)
1782 return ''.join(msg)
1789
1783
1790 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1784 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1791 exception_only=False):
1785 exception_only=False):
1792 """Display the exception that just occurred.
1786 """Display the exception that just occurred.
1793
1787
1794 If nothing is known about the exception, this is the method which
1788 If nothing is known about the exception, this is the method which
1795 should be used throughout the code for presenting user tracebacks,
1789 should be used throughout the code for presenting user tracebacks,
1796 rather than directly invoking the InteractiveTB object.
1790 rather than directly invoking the InteractiveTB object.
1797
1791
1798 A specific showsyntaxerror() also exists, but this method can take
1792 A specific showsyntaxerror() also exists, but this method can take
1799 care of calling it if needed, so unless you are explicitly catching a
1793 care of calling it if needed, so unless you are explicitly catching a
1800 SyntaxError exception, don't try to analyze the stack manually and
1794 SyntaxError exception, don't try to analyze the stack manually and
1801 simply call this method."""
1795 simply call this method."""
1802
1796
1803 try:
1797 try:
1804 try:
1798 try:
1805 etype, value, tb = self._get_exc_info(exc_tuple)
1799 etype, value, tb = self._get_exc_info(exc_tuple)
1806 except ValueError:
1800 except ValueError:
1807 print('No traceback available to show.', file=sys.stderr)
1801 print('No traceback available to show.', file=sys.stderr)
1808 return
1802 return
1809
1803
1810 if issubclass(etype, SyntaxError):
1804 if issubclass(etype, SyntaxError):
1811 # Though this won't be called by syntax errors in the input
1805 # Though this won't be called by syntax errors in the input
1812 # line, there may be SyntaxError cases with imported code.
1806 # line, there may be SyntaxError cases with imported code.
1813 self.showsyntaxerror(filename)
1807 self.showsyntaxerror(filename)
1814 elif etype is UsageError:
1808 elif etype is UsageError:
1815 self.show_usage_error(value)
1809 self.show_usage_error(value)
1816 else:
1810 else:
1817 if exception_only:
1811 if exception_only:
1818 stb = ['An exception has occurred, use %tb to see '
1812 stb = ['An exception has occurred, use %tb to see '
1819 'the full traceback.\n']
1813 'the full traceback.\n']
1820 stb.extend(self.InteractiveTB.get_exception_only(etype,
1814 stb.extend(self.InteractiveTB.get_exception_only(etype,
1821 value))
1815 value))
1822 else:
1816 else:
1823 try:
1817 try:
1824 # Exception classes can customise their traceback - we
1818 # Exception classes can customise their traceback - we
1825 # use this in IPython.parallel for exceptions occurring
1819 # use this in IPython.parallel for exceptions occurring
1826 # in the engines. This should return a list of strings.
1820 # in the engines. This should return a list of strings.
1827 stb = value._render_traceback_()
1821 stb = value._render_traceback_()
1828 except Exception:
1822 except Exception:
1829 stb = self.InteractiveTB.structured_traceback(etype,
1823 stb = self.InteractiveTB.structured_traceback(etype,
1830 value, tb, tb_offset=tb_offset)
1824 value, tb, tb_offset=tb_offset)
1831
1825
1832 self._showtraceback(etype, value, stb)
1826 self._showtraceback(etype, value, stb)
1833 if self.call_pdb:
1827 if self.call_pdb:
1834 # drop into debugger
1828 # drop into debugger
1835 self.debugger(force=True)
1829 self.debugger(force=True)
1836 return
1830 return
1837
1831
1838 # Actually show the traceback
1832 # Actually show the traceback
1839 self._showtraceback(etype, value, stb)
1833 self._showtraceback(etype, value, stb)
1840
1834
1841 except KeyboardInterrupt:
1835 except KeyboardInterrupt:
1842 print('\n' + self.get_exception_only(), file=sys.stderr)
1836 print('\n' + self.get_exception_only(), file=sys.stderr)
1843
1837
1844 def _showtraceback(self, etype, evalue, stb):
1838 def _showtraceback(self, etype, evalue, stb):
1845 """Actually show a traceback.
1839 """Actually show a traceback.
1846
1840
1847 Subclasses may override this method to put the traceback on a different
1841 Subclasses may override this method to put the traceback on a different
1848 place, like a side channel.
1842 place, like a side channel.
1849 """
1843 """
1850 print(self.InteractiveTB.stb2text(stb))
1844 print(self.InteractiveTB.stb2text(stb))
1851
1845
1852 def showsyntaxerror(self, filename=None):
1846 def showsyntaxerror(self, filename=None):
1853 """Display the syntax error that just occurred.
1847 """Display the syntax error that just occurred.
1854
1848
1855 This doesn't display a stack trace because there isn't one.
1849 This doesn't display a stack trace because there isn't one.
1856
1850
1857 If a filename is given, it is stuffed in the exception instead
1851 If a filename is given, it is stuffed in the exception instead
1858 of what was there before (because Python's parser always uses
1852 of what was there before (because Python's parser always uses
1859 "<string>" when reading from a string).
1853 "<string>" when reading from a string).
1860 """
1854 """
1861 etype, value, last_traceback = self._get_exc_info()
1855 etype, value, last_traceback = self._get_exc_info()
1862
1856
1863 if filename and issubclass(etype, SyntaxError):
1857 if filename and issubclass(etype, SyntaxError):
1864 try:
1858 try:
1865 value.filename = filename
1859 value.filename = filename
1866 except:
1860 except:
1867 # Not the format we expect; leave it alone
1861 # Not the format we expect; leave it alone
1868 pass
1862 pass
1869
1863
1870 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1864 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1871 self._showtraceback(etype, value, stb)
1865 self._showtraceback(etype, value, stb)
1872
1866
1873 # This is overridden in TerminalInteractiveShell to show a message about
1867 # This is overridden in TerminalInteractiveShell to show a message about
1874 # the %paste magic.
1868 # the %paste magic.
1875 def showindentationerror(self):
1869 def showindentationerror(self):
1876 """Called by run_cell when there's an IndentationError in code entered
1870 """Called by run_cell when there's an IndentationError in code entered
1877 at the prompt.
1871 at the prompt.
1878
1872
1879 This is overridden in TerminalInteractiveShell to show a message about
1873 This is overridden in TerminalInteractiveShell to show a message about
1880 the %paste magic."""
1874 the %paste magic."""
1881 self.showsyntaxerror()
1875 self.showsyntaxerror()
1882
1876
1883 #-------------------------------------------------------------------------
1877 #-------------------------------------------------------------------------
1884 # Things related to readline
1878 # Things related to readline
1885 #-------------------------------------------------------------------------
1879 #-------------------------------------------------------------------------
1886
1880
1887 def init_readline(self):
1881 def init_readline(self):
1888 """Moved to terminal subclass, here only to simplify the init logic."""
1882 """Moved to terminal subclass, here only to simplify the init logic."""
1889 self.readline = None
1883 self.readline = None
1890 # Set a number of methods that depend on readline to be no-op
1884 # Set a number of methods that depend on readline to be no-op
1891 self.readline_no_record = NoOpContext()
1885 self.readline_no_record = NoOpContext()
1892 self.set_readline_completer = no_op
1886 self.set_readline_completer = no_op
1893 self.set_custom_completer = no_op
1887 self.set_custom_completer = no_op
1894
1888
1895 @skip_doctest
1889 @skip_doctest
1896 def set_next_input(self, s, replace=False):
1890 def set_next_input(self, s, replace=False):
1897 """ Sets the 'default' input string for the next command line.
1891 """ Sets the 'default' input string for the next command line.
1898
1892
1899 Example::
1893 Example::
1900
1894
1901 In [1]: _ip.set_next_input("Hello Word")
1895 In [1]: _ip.set_next_input("Hello Word")
1902 In [2]: Hello Word_ # cursor is here
1896 In [2]: Hello Word_ # cursor is here
1903 """
1897 """
1904 self.rl_next_input = py3compat.cast_bytes_py2(s)
1898 self.rl_next_input = py3compat.cast_bytes_py2(s)
1905
1899
1906 def _indent_current_str(self):
1900 def _indent_current_str(self):
1907 """return the current level of indentation as a string"""
1901 """return the current level of indentation as a string"""
1908 return self.input_splitter.indent_spaces * ' '
1902 return self.input_splitter.indent_spaces * ' '
1909
1903
1910 #-------------------------------------------------------------------------
1904 #-------------------------------------------------------------------------
1911 # Things related to text completion
1905 # Things related to text completion
1912 #-------------------------------------------------------------------------
1906 #-------------------------------------------------------------------------
1913
1907
1914 def init_completer(self):
1908 def init_completer(self):
1915 """Initialize the completion machinery.
1909 """Initialize the completion machinery.
1916
1910
1917 This creates completion machinery that can be used by client code,
1911 This creates completion machinery that can be used by client code,
1918 either interactively in-process (typically triggered by the readline
1912 either interactively in-process (typically triggered by the readline
1919 library), programmatically (such as in test suites) or out-of-process
1913 library), programmatically (such as in test suites) or out-of-process
1920 (typically over the network by remote frontends).
1914 (typically over the network by remote frontends).
1921 """
1915 """
1922 from IPython.core.completer import IPCompleter
1916 from IPython.core.completer import IPCompleter
1923 from IPython.core.completerlib import (module_completer,
1917 from IPython.core.completerlib import (module_completer,
1924 magic_run_completer, cd_completer, reset_completer)
1918 magic_run_completer, cd_completer, reset_completer)
1925
1919
1926 self.Completer = IPCompleter(shell=self,
1920 self.Completer = IPCompleter(shell=self,
1927 namespace=self.user_ns,
1921 namespace=self.user_ns,
1928 global_namespace=self.user_global_ns,
1922 global_namespace=self.user_global_ns,
1929 use_readline=self.has_readline,
1923 use_readline=self.has_readline,
1930 parent=self,
1924 parent=self,
1931 )
1925 )
1932 self.configurables.append(self.Completer)
1926 self.configurables.append(self.Completer)
1933
1927
1934 # Add custom completers to the basic ones built into IPCompleter
1928 # Add custom completers to the basic ones built into IPCompleter
1935 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1929 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1936 self.strdispatchers['complete_command'] = sdisp
1930 self.strdispatchers['complete_command'] = sdisp
1937 self.Completer.custom_completers = sdisp
1931 self.Completer.custom_completers = sdisp
1938
1932
1939 self.set_hook('complete_command', module_completer, str_key = 'import')
1933 self.set_hook('complete_command', module_completer, str_key = 'import')
1940 self.set_hook('complete_command', module_completer, str_key = 'from')
1934 self.set_hook('complete_command', module_completer, str_key = 'from')
1941 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1935 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1942 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1936 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1943 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1937 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1944 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1938 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1945
1939
1946
1940
1947 @skip_doctest_py2
1941 @skip_doctest_py2
1948 def complete(self, text, line=None, cursor_pos=None):
1942 def complete(self, text, line=None, cursor_pos=None):
1949 """Return the completed text and a list of completions.
1943 """Return the completed text and a list of completions.
1950
1944
1951 Parameters
1945 Parameters
1952 ----------
1946 ----------
1953
1947
1954 text : string
1948 text : string
1955 A string of text to be completed on. It can be given as empty and
1949 A string of text to be completed on. It can be given as empty and
1956 instead a line/position pair are given. In this case, the
1950 instead a line/position pair are given. In this case, the
1957 completer itself will split the line like readline does.
1951 completer itself will split the line like readline does.
1958
1952
1959 line : string, optional
1953 line : string, optional
1960 The complete line that text is part of.
1954 The complete line that text is part of.
1961
1955
1962 cursor_pos : int, optional
1956 cursor_pos : int, optional
1963 The position of the cursor on the input line.
1957 The position of the cursor on the input line.
1964
1958
1965 Returns
1959 Returns
1966 -------
1960 -------
1967 text : string
1961 text : string
1968 The actual text that was completed.
1962 The actual text that was completed.
1969
1963
1970 matches : list
1964 matches : list
1971 A sorted list with all possible completions.
1965 A sorted list with all possible completions.
1972
1966
1973 The optional arguments allow the completion to take more context into
1967 The optional arguments allow the completion to take more context into
1974 account, and are part of the low-level completion API.
1968 account, and are part of the low-level completion API.
1975
1969
1976 This is a wrapper around the completion mechanism, similar to what
1970 This is a wrapper around the completion mechanism, similar to what
1977 readline does at the command line when the TAB key is hit. By
1971 readline does at the command line when the TAB key is hit. By
1978 exposing it as a method, it can be used by other non-readline
1972 exposing it as a method, it can be used by other non-readline
1979 environments (such as GUIs) for text completion.
1973 environments (such as GUIs) for text completion.
1980
1974
1981 Simple usage example:
1975 Simple usage example:
1982
1976
1983 In [1]: x = 'hello'
1977 In [1]: x = 'hello'
1984
1978
1985 In [2]: _ip.complete('x.l')
1979 In [2]: _ip.complete('x.l')
1986 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1980 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1987 """
1981 """
1988
1982
1989 # Inject names into __builtin__ so we can complete on the added names.
1983 # Inject names into __builtin__ so we can complete on the added names.
1990 with self.builtin_trap:
1984 with self.builtin_trap:
1991 return self.Completer.complete(text, line, cursor_pos)
1985 return self.Completer.complete(text, line, cursor_pos)
1992
1986
1993 def set_custom_completer(self, completer, pos=0):
1987 def set_custom_completer(self, completer, pos=0):
1994 """Adds a new custom completer function.
1988 """Adds a new custom completer function.
1995
1989
1996 The position argument (defaults to 0) is the index in the completers
1990 The position argument (defaults to 0) is the index in the completers
1997 list where you want the completer to be inserted."""
1991 list where you want the completer to be inserted."""
1998
1992
1999 newcomp = types.MethodType(completer,self.Completer)
1993 newcomp = types.MethodType(completer,self.Completer)
2000 self.Completer.matchers.insert(pos,newcomp)
1994 self.Completer.matchers.insert(pos,newcomp)
2001
1995
2002 def set_completer_frame(self, frame=None):
1996 def set_completer_frame(self, frame=None):
2003 """Set the frame of the completer."""
1997 """Set the frame of the completer."""
2004 if frame:
1998 if frame:
2005 self.Completer.namespace = frame.f_locals
1999 self.Completer.namespace = frame.f_locals
2006 self.Completer.global_namespace = frame.f_globals
2000 self.Completer.global_namespace = frame.f_globals
2007 else:
2001 else:
2008 self.Completer.namespace = self.user_ns
2002 self.Completer.namespace = self.user_ns
2009 self.Completer.global_namespace = self.user_global_ns
2003 self.Completer.global_namespace = self.user_global_ns
2010
2004
2011 #-------------------------------------------------------------------------
2005 #-------------------------------------------------------------------------
2012 # Things related to magics
2006 # Things related to magics
2013 #-------------------------------------------------------------------------
2007 #-------------------------------------------------------------------------
2014
2008
2015 def init_magics(self):
2009 def init_magics(self):
2016 from IPython.core import magics as m
2010 from IPython.core import magics as m
2017 self.magics_manager = magic.MagicsManager(shell=self,
2011 self.magics_manager = magic.MagicsManager(shell=self,
2018 parent=self,
2012 parent=self,
2019 user_magics=m.UserMagics(self))
2013 user_magics=m.UserMagics(self))
2020 self.configurables.append(self.magics_manager)
2014 self.configurables.append(self.magics_manager)
2021
2015
2022 # Expose as public API from the magics manager
2016 # Expose as public API from the magics manager
2023 self.register_magics = self.magics_manager.register
2017 self.register_magics = self.magics_manager.register
2024 self.define_magic = self.magics_manager.define_magic
2018 self.define_magic = self.magics_manager.define_magic
2025
2019
2026 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2020 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2027 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2021 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2028 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2022 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2029 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2023 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2030 )
2024 )
2031
2025
2032 # Register Magic Aliases
2026 # Register Magic Aliases
2033 mman = self.magics_manager
2027 mman = self.magics_manager
2034 # FIXME: magic aliases should be defined by the Magics classes
2028 # FIXME: magic aliases should be defined by the Magics classes
2035 # or in MagicsManager, not here
2029 # or in MagicsManager, not here
2036 mman.register_alias('ed', 'edit')
2030 mman.register_alias('ed', 'edit')
2037 mman.register_alias('hist', 'history')
2031 mman.register_alias('hist', 'history')
2038 mman.register_alias('rep', 'recall')
2032 mman.register_alias('rep', 'recall')
2039 mman.register_alias('SVG', 'svg', 'cell')
2033 mman.register_alias('SVG', 'svg', 'cell')
2040 mman.register_alias('HTML', 'html', 'cell')
2034 mman.register_alias('HTML', 'html', 'cell')
2041 mman.register_alias('file', 'writefile', 'cell')
2035 mman.register_alias('file', 'writefile', 'cell')
2042
2036
2043 # FIXME: Move the color initialization to the DisplayHook, which
2037 # FIXME: Move the color initialization to the DisplayHook, which
2044 # should be split into a prompt manager and displayhook. We probably
2038 # should be split into a prompt manager and displayhook. We probably
2045 # even need a centralize colors management object.
2039 # even need a centralize colors management object.
2046 self.magic('colors %s' % self.colors)
2040 self.magic('colors %s' % self.colors)
2047
2041
2048 # Defined here so that it's included in the documentation
2042 # Defined here so that it's included in the documentation
2049 @functools.wraps(magic.MagicsManager.register_function)
2043 @functools.wraps(magic.MagicsManager.register_function)
2050 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2044 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2051 self.magics_manager.register_function(func,
2045 self.magics_manager.register_function(func,
2052 magic_kind=magic_kind, magic_name=magic_name)
2046 magic_kind=magic_kind, magic_name=magic_name)
2053
2047
2054 def run_line_magic(self, magic_name, line):
2048 def run_line_magic(self, magic_name, line):
2055 """Execute the given line magic.
2049 """Execute the given line magic.
2056
2050
2057 Parameters
2051 Parameters
2058 ----------
2052 ----------
2059 magic_name : str
2053 magic_name : str
2060 Name of the desired magic function, without '%' prefix.
2054 Name of the desired magic function, without '%' prefix.
2061
2055
2062 line : str
2056 line : str
2063 The rest of the input line as a single string.
2057 The rest of the input line as a single string.
2064 """
2058 """
2065 fn = self.find_line_magic(magic_name)
2059 fn = self.find_line_magic(magic_name)
2066 if fn is None:
2060 if fn is None:
2067 cm = self.find_cell_magic(magic_name)
2061 cm = self.find_cell_magic(magic_name)
2068 etpl = "Line magic function `%%%s` not found%s."
2062 etpl = "Line magic function `%%%s` not found%s."
2069 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2063 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2070 'did you mean that instead?)' % magic_name )
2064 'did you mean that instead?)' % magic_name )
2071 error(etpl % (magic_name, extra))
2065 error(etpl % (magic_name, extra))
2072 else:
2066 else:
2073 # Note: this is the distance in the stack to the user's frame.
2067 # Note: this is the distance in the stack to the user's frame.
2074 # This will need to be updated if the internal calling logic gets
2068 # This will need to be updated if the internal calling logic gets
2075 # refactored, or else we'll be expanding the wrong variables.
2069 # refactored, or else we'll be expanding the wrong variables.
2076 stack_depth = 2
2070 stack_depth = 2
2077 magic_arg_s = self.var_expand(line, stack_depth)
2071 magic_arg_s = self.var_expand(line, stack_depth)
2078 # Put magic args in a list so we can call with f(*a) syntax
2072 # Put magic args in a list so we can call with f(*a) syntax
2079 args = [magic_arg_s]
2073 args = [magic_arg_s]
2080 kwargs = {}
2074 kwargs = {}
2081 # Grab local namespace if we need it:
2075 # Grab local namespace if we need it:
2082 if getattr(fn, "needs_local_scope", False):
2076 if getattr(fn, "needs_local_scope", False):
2083 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2077 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2084 with self.builtin_trap:
2078 with self.builtin_trap:
2085 result = fn(*args,**kwargs)
2079 result = fn(*args,**kwargs)
2086 return result
2080 return result
2087
2081
2088 def run_cell_magic(self, magic_name, line, cell):
2082 def run_cell_magic(self, magic_name, line, cell):
2089 """Execute the given cell magic.
2083 """Execute the given cell magic.
2090
2084
2091 Parameters
2085 Parameters
2092 ----------
2086 ----------
2093 magic_name : str
2087 magic_name : str
2094 Name of the desired magic function, without '%' prefix.
2088 Name of the desired magic function, without '%' prefix.
2095
2089
2096 line : str
2090 line : str
2097 The rest of the first input line as a single string.
2091 The rest of the first input line as a single string.
2098
2092
2099 cell : str
2093 cell : str
2100 The body of the cell as a (possibly multiline) string.
2094 The body of the cell as a (possibly multiline) string.
2101 """
2095 """
2102 fn = self.find_cell_magic(magic_name)
2096 fn = self.find_cell_magic(magic_name)
2103 if fn is None:
2097 if fn is None:
2104 lm = self.find_line_magic(magic_name)
2098 lm = self.find_line_magic(magic_name)
2105 etpl = "Cell magic `%%{0}` not found{1}."
2099 etpl = "Cell magic `%%{0}` not found{1}."
2106 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2100 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2107 'did you mean that instead?)'.format(magic_name))
2101 'did you mean that instead?)'.format(magic_name))
2108 error(etpl.format(magic_name, extra))
2102 error(etpl.format(magic_name, extra))
2109 elif cell == '':
2103 elif cell == '':
2110 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2104 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2111 if self.find_line_magic(magic_name) is not None:
2105 if self.find_line_magic(magic_name) is not None:
2112 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2106 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2113 raise UsageError(message)
2107 raise UsageError(message)
2114 else:
2108 else:
2115 # Note: this is the distance in the stack to the user's frame.
2109 # Note: this is the distance in the stack to the user's frame.
2116 # This will need to be updated if the internal calling logic gets
2110 # This will need to be updated if the internal calling logic gets
2117 # refactored, or else we'll be expanding the wrong variables.
2111 # refactored, or else we'll be expanding the wrong variables.
2118 stack_depth = 2
2112 stack_depth = 2
2119 magic_arg_s = self.var_expand(line, stack_depth)
2113 magic_arg_s = self.var_expand(line, stack_depth)
2120 with self.builtin_trap:
2114 with self.builtin_trap:
2121 result = fn(magic_arg_s, cell)
2115 result = fn(magic_arg_s, cell)
2122 return result
2116 return result
2123
2117
2124 def find_line_magic(self, magic_name):
2118 def find_line_magic(self, magic_name):
2125 """Find and return a line magic by name.
2119 """Find and return a line magic by name.
2126
2120
2127 Returns None if the magic isn't found."""
2121 Returns None if the magic isn't found."""
2128 return self.magics_manager.magics['line'].get(magic_name)
2122 return self.magics_manager.magics['line'].get(magic_name)
2129
2123
2130 def find_cell_magic(self, magic_name):
2124 def find_cell_magic(self, magic_name):
2131 """Find and return a cell magic by name.
2125 """Find and return a cell magic by name.
2132
2126
2133 Returns None if the magic isn't found."""
2127 Returns None if the magic isn't found."""
2134 return self.magics_manager.magics['cell'].get(magic_name)
2128 return self.magics_manager.magics['cell'].get(magic_name)
2135
2129
2136 def find_magic(self, magic_name, magic_kind='line'):
2130 def find_magic(self, magic_name, magic_kind='line'):
2137 """Find and return a magic of the given type by name.
2131 """Find and return a magic of the given type by name.
2138
2132
2139 Returns None if the magic isn't found."""
2133 Returns None if the magic isn't found."""
2140 return self.magics_manager.magics[magic_kind].get(magic_name)
2134 return self.magics_manager.magics[magic_kind].get(magic_name)
2141
2135
2142 def magic(self, arg_s):
2136 def magic(self, arg_s):
2143 """DEPRECATED. Use run_line_magic() instead.
2137 """DEPRECATED. Use run_line_magic() instead.
2144
2138
2145 Call a magic function by name.
2139 Call a magic function by name.
2146
2140
2147 Input: a string containing the name of the magic function to call and
2141 Input: a string containing the name of the magic function to call and
2148 any additional arguments to be passed to the magic.
2142 any additional arguments to be passed to the magic.
2149
2143
2150 magic('name -opt foo bar') is equivalent to typing at the ipython
2144 magic('name -opt foo bar') is equivalent to typing at the ipython
2151 prompt:
2145 prompt:
2152
2146
2153 In[1]: %name -opt foo bar
2147 In[1]: %name -opt foo bar
2154
2148
2155 To call a magic without arguments, simply use magic('name').
2149 To call a magic without arguments, simply use magic('name').
2156
2150
2157 This provides a proper Python function to call IPython's magics in any
2151 This provides a proper Python function to call IPython's magics in any
2158 valid Python code you can type at the interpreter, including loops and
2152 valid Python code you can type at the interpreter, including loops and
2159 compound statements.
2153 compound statements.
2160 """
2154 """
2161 # TODO: should we issue a loud deprecation warning here?
2155 # TODO: should we issue a loud deprecation warning here?
2162 magic_name, _, magic_arg_s = arg_s.partition(' ')
2156 magic_name, _, magic_arg_s = arg_s.partition(' ')
2163 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2157 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2164 return self.run_line_magic(magic_name, magic_arg_s)
2158 return self.run_line_magic(magic_name, magic_arg_s)
2165
2159
2166 #-------------------------------------------------------------------------
2160 #-------------------------------------------------------------------------
2167 # Things related to macros
2161 # Things related to macros
2168 #-------------------------------------------------------------------------
2162 #-------------------------------------------------------------------------
2169
2163
2170 def define_macro(self, name, themacro):
2164 def define_macro(self, name, themacro):
2171 """Define a new macro
2165 """Define a new macro
2172
2166
2173 Parameters
2167 Parameters
2174 ----------
2168 ----------
2175 name : str
2169 name : str
2176 The name of the macro.
2170 The name of the macro.
2177 themacro : str or Macro
2171 themacro : str or Macro
2178 The action to do upon invoking the macro. If a string, a new
2172 The action to do upon invoking the macro. If a string, a new
2179 Macro object is created by passing the string to it.
2173 Macro object is created by passing the string to it.
2180 """
2174 """
2181
2175
2182 from IPython.core import macro
2176 from IPython.core import macro
2183
2177
2184 if isinstance(themacro, string_types):
2178 if isinstance(themacro, string_types):
2185 themacro = macro.Macro(themacro)
2179 themacro = macro.Macro(themacro)
2186 if not isinstance(themacro, macro.Macro):
2180 if not isinstance(themacro, macro.Macro):
2187 raise ValueError('A macro must be a string or a Macro instance.')
2181 raise ValueError('A macro must be a string or a Macro instance.')
2188 self.user_ns[name] = themacro
2182 self.user_ns[name] = themacro
2189
2183
2190 #-------------------------------------------------------------------------
2184 #-------------------------------------------------------------------------
2191 # Things related to the running of system commands
2185 # Things related to the running of system commands
2192 #-------------------------------------------------------------------------
2186 #-------------------------------------------------------------------------
2193
2187
2194 def system_piped(self, cmd):
2188 def system_piped(self, cmd):
2195 """Call the given cmd in a subprocess, piping stdout/err
2189 """Call the given cmd in a subprocess, piping stdout/err
2196
2190
2197 Parameters
2191 Parameters
2198 ----------
2192 ----------
2199 cmd : str
2193 cmd : str
2200 Command to execute (can not end in '&', as background processes are
2194 Command to execute (can not end in '&', as background processes are
2201 not supported. Should not be a command that expects input
2195 not supported. Should not be a command that expects input
2202 other than simple text.
2196 other than simple text.
2203 """
2197 """
2204 if cmd.rstrip().endswith('&'):
2198 if cmd.rstrip().endswith('&'):
2205 # this is *far* from a rigorous test
2199 # this is *far* from a rigorous test
2206 # We do not support backgrounding processes because we either use
2200 # We do not support backgrounding processes because we either use
2207 # pexpect or pipes to read from. Users can always just call
2201 # pexpect or pipes to read from. Users can always just call
2208 # os.system() or use ip.system=ip.system_raw
2202 # os.system() or use ip.system=ip.system_raw
2209 # if they really want a background process.
2203 # if they really want a background process.
2210 raise OSError("Background processes not supported.")
2204 raise OSError("Background processes not supported.")
2211
2205
2212 # we explicitly do NOT return the subprocess status code, because
2206 # we explicitly do NOT return the subprocess status code, because
2213 # a non-None value would trigger :func:`sys.displayhook` calls.
2207 # a non-None value would trigger :func:`sys.displayhook` calls.
2214 # Instead, we store the exit_code in user_ns.
2208 # Instead, we store the exit_code in user_ns.
2215 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2209 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2216
2210
2217 def system_raw(self, cmd):
2211 def system_raw(self, cmd):
2218 """Call the given cmd in a subprocess using os.system on Windows or
2212 """Call the given cmd in a subprocess using os.system on Windows or
2219 subprocess.call using the system shell on other platforms.
2213 subprocess.call using the system shell on other platforms.
2220
2214
2221 Parameters
2215 Parameters
2222 ----------
2216 ----------
2223 cmd : str
2217 cmd : str
2224 Command to execute.
2218 Command to execute.
2225 """
2219 """
2226 cmd = self.var_expand(cmd, depth=1)
2220 cmd = self.var_expand(cmd, depth=1)
2227 # protect os.system from UNC paths on Windows, which it can't handle:
2221 # protect os.system from UNC paths on Windows, which it can't handle:
2228 if sys.platform == 'win32':
2222 if sys.platform == 'win32':
2229 from IPython.utils._process_win32 import AvoidUNCPath
2223 from IPython.utils._process_win32 import AvoidUNCPath
2230 with AvoidUNCPath() as path:
2224 with AvoidUNCPath() as path:
2231 if path is not None:
2225 if path is not None:
2232 cmd = '"pushd %s &&"%s' % (path, cmd)
2226 cmd = '"pushd %s &&"%s' % (path, cmd)
2233 cmd = py3compat.unicode_to_str(cmd)
2227 cmd = py3compat.unicode_to_str(cmd)
2234 try:
2228 try:
2235 ec = os.system(cmd)
2229 ec = os.system(cmd)
2236 except KeyboardInterrupt:
2230 except KeyboardInterrupt:
2237 print('\n' + self.get_exception_only(), file=sys.stderr)
2231 print('\n' + self.get_exception_only(), file=sys.stderr)
2238 ec = -2
2232 ec = -2
2239 else:
2233 else:
2240 cmd = py3compat.unicode_to_str(cmd)
2234 cmd = py3compat.unicode_to_str(cmd)
2241 # For posix the result of the subprocess.call() below is an exit
2235 # For posix the result of the subprocess.call() below is an exit
2242 # code, which by convention is zero for success, positive for
2236 # code, which by convention is zero for success, positive for
2243 # program failure. Exit codes above 128 are reserved for signals,
2237 # program failure. Exit codes above 128 are reserved for signals,
2244 # and the formula for converting a signal to an exit code is usually
2238 # and the formula for converting a signal to an exit code is usually
2245 # signal_number+128. To more easily differentiate between exit
2239 # signal_number+128. To more easily differentiate between exit
2246 # codes and signals, ipython uses negative numbers. For instance
2240 # codes and signals, ipython uses negative numbers. For instance
2247 # since control-c is signal 2 but exit code 130, ipython's
2241 # since control-c is signal 2 but exit code 130, ipython's
2248 # _exit_code variable will read -2. Note that some shells like
2242 # _exit_code variable will read -2. Note that some shells like
2249 # csh and fish don't follow sh/bash conventions for exit codes.
2243 # csh and fish don't follow sh/bash conventions for exit codes.
2250 executable = os.environ.get('SHELL', None)
2244 executable = os.environ.get('SHELL', None)
2251 try:
2245 try:
2252 # Use env shell instead of default /bin/sh
2246 # Use env shell instead of default /bin/sh
2253 ec = subprocess.call(cmd, shell=True, executable=executable)
2247 ec = subprocess.call(cmd, shell=True, executable=executable)
2254 except KeyboardInterrupt:
2248 except KeyboardInterrupt:
2255 # intercept control-C; a long traceback is not useful here
2249 # intercept control-C; a long traceback is not useful here
2256 print('\n' + self.get_exception_only(), file=sys.stderr)
2250 print('\n' + self.get_exception_only(), file=sys.stderr)
2257 ec = 130
2251 ec = 130
2258 if ec > 128:
2252 if ec > 128:
2259 ec = -(ec - 128)
2253 ec = -(ec - 128)
2260
2254
2261 # We explicitly do NOT return the subprocess status code, because
2255 # We explicitly do NOT return the subprocess status code, because
2262 # a non-None value would trigger :func:`sys.displayhook` calls.
2256 # a non-None value would trigger :func:`sys.displayhook` calls.
2263 # Instead, we store the exit_code in user_ns. Note the semantics
2257 # Instead, we store the exit_code in user_ns. Note the semantics
2264 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2258 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2265 # but raising SystemExit(_exit_code) will give status 254!
2259 # but raising SystemExit(_exit_code) will give status 254!
2266 self.user_ns['_exit_code'] = ec
2260 self.user_ns['_exit_code'] = ec
2267
2261
2268 # use piped system by default, because it is better behaved
2262 # use piped system by default, because it is better behaved
2269 system = system_piped
2263 system = system_piped
2270
2264
2271 def getoutput(self, cmd, split=True, depth=0):
2265 def getoutput(self, cmd, split=True, depth=0):
2272 """Get output (possibly including stderr) from a subprocess.
2266 """Get output (possibly including stderr) from a subprocess.
2273
2267
2274 Parameters
2268 Parameters
2275 ----------
2269 ----------
2276 cmd : str
2270 cmd : str
2277 Command to execute (can not end in '&', as background processes are
2271 Command to execute (can not end in '&', as background processes are
2278 not supported.
2272 not supported.
2279 split : bool, optional
2273 split : bool, optional
2280 If True, split the output into an IPython SList. Otherwise, an
2274 If True, split the output into an IPython SList. Otherwise, an
2281 IPython LSString is returned. These are objects similar to normal
2275 IPython LSString is returned. These are objects similar to normal
2282 lists and strings, with a few convenience attributes for easier
2276 lists and strings, with a few convenience attributes for easier
2283 manipulation of line-based output. You can use '?' on them for
2277 manipulation of line-based output. You can use '?' on them for
2284 details.
2278 details.
2285 depth : int, optional
2279 depth : int, optional
2286 How many frames above the caller are the local variables which should
2280 How many frames above the caller are the local variables which should
2287 be expanded in the command string? The default (0) assumes that the
2281 be expanded in the command string? The default (0) assumes that the
2288 expansion variables are in the stack frame calling this function.
2282 expansion variables are in the stack frame calling this function.
2289 """
2283 """
2290 if cmd.rstrip().endswith('&'):
2284 if cmd.rstrip().endswith('&'):
2291 # this is *far* from a rigorous test
2285 # this is *far* from a rigorous test
2292 raise OSError("Background processes not supported.")
2286 raise OSError("Background processes not supported.")
2293 out = getoutput(self.var_expand(cmd, depth=depth+1))
2287 out = getoutput(self.var_expand(cmd, depth=depth+1))
2294 if split:
2288 if split:
2295 out = SList(out.splitlines())
2289 out = SList(out.splitlines())
2296 else:
2290 else:
2297 out = LSString(out)
2291 out = LSString(out)
2298 return out
2292 return out
2299
2293
2300 #-------------------------------------------------------------------------
2294 #-------------------------------------------------------------------------
2301 # Things related to aliases
2295 # Things related to aliases
2302 #-------------------------------------------------------------------------
2296 #-------------------------------------------------------------------------
2303
2297
2304 def init_alias(self):
2298 def init_alias(self):
2305 self.alias_manager = AliasManager(shell=self, parent=self)
2299 self.alias_manager = AliasManager(shell=self, parent=self)
2306 self.configurables.append(self.alias_manager)
2300 self.configurables.append(self.alias_manager)
2307
2301
2308 #-------------------------------------------------------------------------
2302 #-------------------------------------------------------------------------
2309 # Things related to extensions
2303 # Things related to extensions
2310 #-------------------------------------------------------------------------
2304 #-------------------------------------------------------------------------
2311
2305
2312 def init_extension_manager(self):
2306 def init_extension_manager(self):
2313 self.extension_manager = ExtensionManager(shell=self, parent=self)
2307 self.extension_manager = ExtensionManager(shell=self, parent=self)
2314 self.configurables.append(self.extension_manager)
2308 self.configurables.append(self.extension_manager)
2315
2309
2316 #-------------------------------------------------------------------------
2310 #-------------------------------------------------------------------------
2317 # Things related to payloads
2311 # Things related to payloads
2318 #-------------------------------------------------------------------------
2312 #-------------------------------------------------------------------------
2319
2313
2320 def init_payload(self):
2314 def init_payload(self):
2321 self.payload_manager = PayloadManager(parent=self)
2315 self.payload_manager = PayloadManager(parent=self)
2322 self.configurables.append(self.payload_manager)
2316 self.configurables.append(self.payload_manager)
2323
2317
2324 #-------------------------------------------------------------------------
2318 #-------------------------------------------------------------------------
2325 # Things related to the prefilter
2319 # Things related to the prefilter
2326 #-------------------------------------------------------------------------
2320 #-------------------------------------------------------------------------
2327
2321
2328 def init_prefilter(self):
2322 def init_prefilter(self):
2329 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2323 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2330 self.configurables.append(self.prefilter_manager)
2324 self.configurables.append(self.prefilter_manager)
2331 # Ultimately this will be refactored in the new interpreter code, but
2325 # Ultimately this will be refactored in the new interpreter code, but
2332 # for now, we should expose the main prefilter method (there's legacy
2326 # for now, we should expose the main prefilter method (there's legacy
2333 # code out there that may rely on this).
2327 # code out there that may rely on this).
2334 self.prefilter = self.prefilter_manager.prefilter_lines
2328 self.prefilter = self.prefilter_manager.prefilter_lines
2335
2329
2336 def auto_rewrite_input(self, cmd):
2330 def auto_rewrite_input(self, cmd):
2337 """Print to the screen the rewritten form of the user's command.
2331 """Print to the screen the rewritten form of the user's command.
2338
2332
2339 This shows visual feedback by rewriting input lines that cause
2333 This shows visual feedback by rewriting input lines that cause
2340 automatic calling to kick in, like::
2334 automatic calling to kick in, like::
2341
2335
2342 /f x
2336 /f x
2343
2337
2344 into::
2338 into::
2345
2339
2346 ------> f(x)
2340 ------> f(x)
2347
2341
2348 after the user's input prompt. This helps the user understand that the
2342 after the user's input prompt. This helps the user understand that the
2349 input line was transformed automatically by IPython.
2343 input line was transformed automatically by IPython.
2350 """
2344 """
2351 if not self.show_rewritten_input:
2345 if not self.show_rewritten_input:
2352 return
2346 return
2353
2347
2354 rw = self.prompt_manager.render('rewrite') + cmd
2348 rw = self.prompt_manager.render('rewrite') + cmd
2355
2349
2356 try:
2350 try:
2357 # plain ascii works better w/ pyreadline, on some machines, so
2351 # plain ascii works better w/ pyreadline, on some machines, so
2358 # we use it and only print uncolored rewrite if we have unicode
2352 # we use it and only print uncolored rewrite if we have unicode
2359 rw = str(rw)
2353 rw = str(rw)
2360 print(rw)
2354 print(rw)
2361 except UnicodeEncodeError:
2355 except UnicodeEncodeError:
2362 print("------> " + cmd)
2356 print("------> " + cmd)
2363
2357
2364 #-------------------------------------------------------------------------
2358 #-------------------------------------------------------------------------
2365 # Things related to extracting values/expressions from kernel and user_ns
2359 # Things related to extracting values/expressions from kernel and user_ns
2366 #-------------------------------------------------------------------------
2360 #-------------------------------------------------------------------------
2367
2361
2368 def _user_obj_error(self):
2362 def _user_obj_error(self):
2369 """return simple exception dict
2363 """return simple exception dict
2370
2364
2371 for use in user_expressions
2365 for use in user_expressions
2372 """
2366 """
2373
2367
2374 etype, evalue, tb = self._get_exc_info()
2368 etype, evalue, tb = self._get_exc_info()
2375 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2369 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2376
2370
2377 exc_info = {
2371 exc_info = {
2378 u'status' : 'error',
2372 u'status' : 'error',
2379 u'traceback' : stb,
2373 u'traceback' : stb,
2380 u'ename' : unicode_type(etype.__name__),
2374 u'ename' : unicode_type(etype.__name__),
2381 u'evalue' : py3compat.safe_unicode(evalue),
2375 u'evalue' : py3compat.safe_unicode(evalue),
2382 }
2376 }
2383
2377
2384 return exc_info
2378 return exc_info
2385
2379
2386 def _format_user_obj(self, obj):
2380 def _format_user_obj(self, obj):
2387 """format a user object to display dict
2381 """format a user object to display dict
2388
2382
2389 for use in user_expressions
2383 for use in user_expressions
2390 """
2384 """
2391
2385
2392 data, md = self.display_formatter.format(obj)
2386 data, md = self.display_formatter.format(obj)
2393 value = {
2387 value = {
2394 'status' : 'ok',
2388 'status' : 'ok',
2395 'data' : data,
2389 'data' : data,
2396 'metadata' : md,
2390 'metadata' : md,
2397 }
2391 }
2398 return value
2392 return value
2399
2393
2400 def user_expressions(self, expressions):
2394 def user_expressions(self, expressions):
2401 """Evaluate a dict of expressions in the user's namespace.
2395 """Evaluate a dict of expressions in the user's namespace.
2402
2396
2403 Parameters
2397 Parameters
2404 ----------
2398 ----------
2405 expressions : dict
2399 expressions : dict
2406 A dict with string keys and string values. The expression values
2400 A dict with string keys and string values. The expression values
2407 should be valid Python expressions, each of which will be evaluated
2401 should be valid Python expressions, each of which will be evaluated
2408 in the user namespace.
2402 in the user namespace.
2409
2403
2410 Returns
2404 Returns
2411 -------
2405 -------
2412 A dict, keyed like the input expressions dict, with the rich mime-typed
2406 A dict, keyed like the input expressions dict, with the rich mime-typed
2413 display_data of each value.
2407 display_data of each value.
2414 """
2408 """
2415 out = {}
2409 out = {}
2416 user_ns = self.user_ns
2410 user_ns = self.user_ns
2417 global_ns = self.user_global_ns
2411 global_ns = self.user_global_ns
2418
2412
2419 for key, expr in iteritems(expressions):
2413 for key, expr in iteritems(expressions):
2420 try:
2414 try:
2421 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2415 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2422 except:
2416 except:
2423 value = self._user_obj_error()
2417 value = self._user_obj_error()
2424 out[key] = value
2418 out[key] = value
2425 return out
2419 return out
2426
2420
2427 #-------------------------------------------------------------------------
2421 #-------------------------------------------------------------------------
2428 # Things related to the running of code
2422 # Things related to the running of code
2429 #-------------------------------------------------------------------------
2423 #-------------------------------------------------------------------------
2430
2424
2431 def ex(self, cmd):
2425 def ex(self, cmd):
2432 """Execute a normal python statement in user namespace."""
2426 """Execute a normal python statement in user namespace."""
2433 with self.builtin_trap:
2427 with self.builtin_trap:
2434 exec(cmd, self.user_global_ns, self.user_ns)
2428 exec(cmd, self.user_global_ns, self.user_ns)
2435
2429
2436 def ev(self, expr):
2430 def ev(self, expr):
2437 """Evaluate python expression expr in user namespace.
2431 """Evaluate python expression expr in user namespace.
2438
2432
2439 Returns the result of evaluation
2433 Returns the result of evaluation
2440 """
2434 """
2441 with self.builtin_trap:
2435 with self.builtin_trap:
2442 return eval(expr, self.user_global_ns, self.user_ns)
2436 return eval(expr, self.user_global_ns, self.user_ns)
2443
2437
2444 def safe_execfile(self, fname, *where, **kw):
2438 def safe_execfile(self, fname, *where, **kw):
2445 """A safe version of the builtin execfile().
2439 """A safe version of the builtin execfile().
2446
2440
2447 This version will never throw an exception, but instead print
2441 This version will never throw an exception, but instead print
2448 helpful error messages to the screen. This only works on pure
2442 helpful error messages to the screen. This only works on pure
2449 Python files with the .py extension.
2443 Python files with the .py extension.
2450
2444
2451 Parameters
2445 Parameters
2452 ----------
2446 ----------
2453 fname : string
2447 fname : string
2454 The name of the file to be executed.
2448 The name of the file to be executed.
2455 where : tuple
2449 where : tuple
2456 One or two namespaces, passed to execfile() as (globals,locals).
2450 One or two namespaces, passed to execfile() as (globals,locals).
2457 If only one is given, it is passed as both.
2451 If only one is given, it is passed as both.
2458 exit_ignore : bool (False)
2452 exit_ignore : bool (False)
2459 If True, then silence SystemExit for non-zero status (it is always
2453 If True, then silence SystemExit for non-zero status (it is always
2460 silenced for zero status, as it is so common).
2454 silenced for zero status, as it is so common).
2461 raise_exceptions : bool (False)
2455 raise_exceptions : bool (False)
2462 If True raise exceptions everywhere. Meant for testing.
2456 If True raise exceptions everywhere. Meant for testing.
2463 shell_futures : bool (False)
2457 shell_futures : bool (False)
2464 If True, the code will share future statements with the interactive
2458 If True, the code will share future statements with the interactive
2465 shell. It will both be affected by previous __future__ imports, and
2459 shell. It will both be affected by previous __future__ imports, and
2466 any __future__ imports in the code will affect the shell. If False,
2460 any __future__ imports in the code will affect the shell. If False,
2467 __future__ imports are not shared in either direction.
2461 __future__ imports are not shared in either direction.
2468
2462
2469 """
2463 """
2470 kw.setdefault('exit_ignore', False)
2464 kw.setdefault('exit_ignore', False)
2471 kw.setdefault('raise_exceptions', False)
2465 kw.setdefault('raise_exceptions', False)
2472 kw.setdefault('shell_futures', False)
2466 kw.setdefault('shell_futures', False)
2473
2467
2474 fname = os.path.abspath(os.path.expanduser(fname))
2468 fname = os.path.abspath(os.path.expanduser(fname))
2475
2469
2476 # Make sure we can open the file
2470 # Make sure we can open the file
2477 try:
2471 try:
2478 with open(fname):
2472 with open(fname):
2479 pass
2473 pass
2480 except:
2474 except:
2481 warn('Could not open file <%s> for safe execution.' % fname)
2475 warn('Could not open file <%s> for safe execution.' % fname)
2482 return
2476 return
2483
2477
2484 # Find things also in current directory. This is needed to mimic the
2478 # Find things also in current directory. This is needed to mimic the
2485 # behavior of running a script from the system command line, where
2479 # behavior of running a script from the system command line, where
2486 # Python inserts the script's directory into sys.path
2480 # Python inserts the script's directory into sys.path
2487 dname = os.path.dirname(fname)
2481 dname = os.path.dirname(fname)
2488
2482
2489 with prepended_to_syspath(dname):
2483 with prepended_to_syspath(dname):
2490 try:
2484 try:
2491 glob, loc = (where + (None, ))[:2]
2485 glob, loc = (where + (None, ))[:2]
2492 py3compat.execfile(
2486 py3compat.execfile(
2493 fname, glob, loc,
2487 fname, glob, loc,
2494 self.compile if kw['shell_futures'] else None)
2488 self.compile if kw['shell_futures'] else None)
2495 except SystemExit as status:
2489 except SystemExit as status:
2496 # If the call was made with 0 or None exit status (sys.exit(0)
2490 # If the call was made with 0 or None exit status (sys.exit(0)
2497 # or sys.exit() ), don't bother showing a traceback, as both of
2491 # or sys.exit() ), don't bother showing a traceback, as both of
2498 # these are considered normal by the OS:
2492 # these are considered normal by the OS:
2499 # > python -c'import sys;sys.exit(0)'; echo $?
2493 # > python -c'import sys;sys.exit(0)'; echo $?
2500 # 0
2494 # 0
2501 # > python -c'import sys;sys.exit()'; echo $?
2495 # > python -c'import sys;sys.exit()'; echo $?
2502 # 0
2496 # 0
2503 # For other exit status, we show the exception unless
2497 # For other exit status, we show the exception unless
2504 # explicitly silenced, but only in short form.
2498 # explicitly silenced, but only in short form.
2505 if status.code:
2499 if status.code:
2506 if kw['raise_exceptions']:
2500 if kw['raise_exceptions']:
2507 raise
2501 raise
2508 if not kw['exit_ignore']:
2502 if not kw['exit_ignore']:
2509 self.showtraceback(exception_only=True)
2503 self.showtraceback(exception_only=True)
2510 except:
2504 except:
2511 if kw['raise_exceptions']:
2505 if kw['raise_exceptions']:
2512 raise
2506 raise
2513 # tb offset is 2 because we wrap execfile
2507 # tb offset is 2 because we wrap execfile
2514 self.showtraceback(tb_offset=2)
2508 self.showtraceback(tb_offset=2)
2515
2509
2516 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2510 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2517 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2511 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2518
2512
2519 Parameters
2513 Parameters
2520 ----------
2514 ----------
2521 fname : str
2515 fname : str
2522 The name of the file to execute. The filename must have a
2516 The name of the file to execute. The filename must have a
2523 .ipy or .ipynb extension.
2517 .ipy or .ipynb extension.
2524 shell_futures : bool (False)
2518 shell_futures : bool (False)
2525 If True, the code will share future statements with the interactive
2519 If True, the code will share future statements with the interactive
2526 shell. It will both be affected by previous __future__ imports, and
2520 shell. It will both be affected by previous __future__ imports, and
2527 any __future__ imports in the code will affect the shell. If False,
2521 any __future__ imports in the code will affect the shell. If False,
2528 __future__ imports are not shared in either direction.
2522 __future__ imports are not shared in either direction.
2529 raise_exceptions : bool (False)
2523 raise_exceptions : bool (False)
2530 If True raise exceptions everywhere. Meant for testing.
2524 If True raise exceptions everywhere. Meant for testing.
2531 """
2525 """
2532 fname = os.path.abspath(os.path.expanduser(fname))
2526 fname = os.path.abspath(os.path.expanduser(fname))
2533
2527
2534 # Make sure we can open the file
2528 # Make sure we can open the file
2535 try:
2529 try:
2536 with open(fname):
2530 with open(fname):
2537 pass
2531 pass
2538 except:
2532 except:
2539 warn('Could not open file <%s> for safe execution.' % fname)
2533 warn('Could not open file <%s> for safe execution.' % fname)
2540 return
2534 return
2541
2535
2542 # Find things also in current directory. This is needed to mimic the
2536 # Find things also in current directory. This is needed to mimic the
2543 # behavior of running a script from the system command line, where
2537 # behavior of running a script from the system command line, where
2544 # Python inserts the script's directory into sys.path
2538 # Python inserts the script's directory into sys.path
2545 dname = os.path.dirname(fname)
2539 dname = os.path.dirname(fname)
2546
2540
2547 def get_cells():
2541 def get_cells():
2548 """generator for sequence of code blocks to run"""
2542 """generator for sequence of code blocks to run"""
2549 if fname.endswith('.ipynb'):
2543 if fname.endswith('.ipynb'):
2550 from nbformat import read
2544 from nbformat import read
2551 with io_open(fname) as f:
2545 with io_open(fname) as f:
2552 nb = read(f, as_version=4)
2546 nb = read(f, as_version=4)
2553 if not nb.cells:
2547 if not nb.cells:
2554 return
2548 return
2555 for cell in nb.cells:
2549 for cell in nb.cells:
2556 if cell.cell_type == 'code':
2550 if cell.cell_type == 'code':
2557 yield cell.source
2551 yield cell.source
2558 else:
2552 else:
2559 with open(fname) as f:
2553 with open(fname) as f:
2560 yield f.read()
2554 yield f.read()
2561
2555
2562 with prepended_to_syspath(dname):
2556 with prepended_to_syspath(dname):
2563 try:
2557 try:
2564 for cell in get_cells():
2558 for cell in get_cells():
2565 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2559 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2566 if raise_exceptions:
2560 if raise_exceptions:
2567 result.raise_error()
2561 result.raise_error()
2568 elif not result.success:
2562 elif not result.success:
2569 break
2563 break
2570 except:
2564 except:
2571 if raise_exceptions:
2565 if raise_exceptions:
2572 raise
2566 raise
2573 self.showtraceback()
2567 self.showtraceback()
2574 warn('Unknown failure executing file: <%s>' % fname)
2568 warn('Unknown failure executing file: <%s>' % fname)
2575
2569
2576 def safe_run_module(self, mod_name, where):
2570 def safe_run_module(self, mod_name, where):
2577 """A safe version of runpy.run_module().
2571 """A safe version of runpy.run_module().
2578
2572
2579 This version will never throw an exception, but instead print
2573 This version will never throw an exception, but instead print
2580 helpful error messages to the screen.
2574 helpful error messages to the screen.
2581
2575
2582 `SystemExit` exceptions with status code 0 or None are ignored.
2576 `SystemExit` exceptions with status code 0 or None are ignored.
2583
2577
2584 Parameters
2578 Parameters
2585 ----------
2579 ----------
2586 mod_name : string
2580 mod_name : string
2587 The name of the module to be executed.
2581 The name of the module to be executed.
2588 where : dict
2582 where : dict
2589 The globals namespace.
2583 The globals namespace.
2590 """
2584 """
2591 try:
2585 try:
2592 try:
2586 try:
2593 where.update(
2587 where.update(
2594 runpy.run_module(str(mod_name), run_name="__main__",
2588 runpy.run_module(str(mod_name), run_name="__main__",
2595 alter_sys=True)
2589 alter_sys=True)
2596 )
2590 )
2597 except SystemExit as status:
2591 except SystemExit as status:
2598 if status.code:
2592 if status.code:
2599 raise
2593 raise
2600 except:
2594 except:
2601 self.showtraceback()
2595 self.showtraceback()
2602 warn('Unknown failure executing module: <%s>' % mod_name)
2596 warn('Unknown failure executing module: <%s>' % mod_name)
2603
2597
2604 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2598 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2605 """Run a complete IPython cell.
2599 """Run a complete IPython cell.
2606
2600
2607 Parameters
2601 Parameters
2608 ----------
2602 ----------
2609 raw_cell : str
2603 raw_cell : str
2610 The code (including IPython code such as %magic functions) to run.
2604 The code (including IPython code such as %magic functions) to run.
2611 store_history : bool
2605 store_history : bool
2612 If True, the raw and translated cell will be stored in IPython's
2606 If True, the raw and translated cell will be stored in IPython's
2613 history. For user code calling back into IPython's machinery, this
2607 history. For user code calling back into IPython's machinery, this
2614 should be set to False.
2608 should be set to False.
2615 silent : bool
2609 silent : bool
2616 If True, avoid side-effects, such as implicit displayhooks and
2610 If True, avoid side-effects, such as implicit displayhooks and
2617 and logging. silent=True forces store_history=False.
2611 and logging. silent=True forces store_history=False.
2618 shell_futures : bool
2612 shell_futures : bool
2619 If True, the code will share future statements with the interactive
2613 If True, the code will share future statements with the interactive
2620 shell. It will both be affected by previous __future__ imports, and
2614 shell. It will both be affected by previous __future__ imports, and
2621 any __future__ imports in the code will affect the shell. If False,
2615 any __future__ imports in the code will affect the shell. If False,
2622 __future__ imports are not shared in either direction.
2616 __future__ imports are not shared in either direction.
2623
2617
2624 Returns
2618 Returns
2625 -------
2619 -------
2626 result : :class:`ExecutionResult`
2620 result : :class:`ExecutionResult`
2627 """
2621 """
2628 result = ExecutionResult()
2622 result = ExecutionResult()
2629
2623
2630 if (not raw_cell) or raw_cell.isspace():
2624 if (not raw_cell) or raw_cell.isspace():
2631 return result
2625 return result
2632
2626
2633 if silent:
2627 if silent:
2634 store_history = False
2628 store_history = False
2635
2629
2636 if store_history:
2630 if store_history:
2637 result.execution_count = self.execution_count
2631 result.execution_count = self.execution_count
2638
2632
2639 def error_before_exec(value):
2633 def error_before_exec(value):
2640 result.error_before_exec = value
2634 result.error_before_exec = value
2641 return result
2635 return result
2642
2636
2643 self.events.trigger('pre_execute')
2637 self.events.trigger('pre_execute')
2644 if not silent:
2638 if not silent:
2645 self.events.trigger('pre_run_cell')
2639 self.events.trigger('pre_run_cell')
2646
2640
2647 # If any of our input transformation (input_transformer_manager or
2641 # If any of our input transformation (input_transformer_manager or
2648 # prefilter_manager) raises an exception, we store it in this variable
2642 # prefilter_manager) raises an exception, we store it in this variable
2649 # so that we can display the error after logging the input and storing
2643 # so that we can display the error after logging the input and storing
2650 # it in the history.
2644 # it in the history.
2651 preprocessing_exc_tuple = None
2645 preprocessing_exc_tuple = None
2652 try:
2646 try:
2653 # Static input transformations
2647 # Static input transformations
2654 cell = self.input_transformer_manager.transform_cell(raw_cell)
2648 cell = self.input_transformer_manager.transform_cell(raw_cell)
2655 except SyntaxError:
2649 except SyntaxError:
2656 preprocessing_exc_tuple = sys.exc_info()
2650 preprocessing_exc_tuple = sys.exc_info()
2657 cell = raw_cell # cell has to exist so it can be stored/logged
2651 cell = raw_cell # cell has to exist so it can be stored/logged
2658 else:
2652 else:
2659 if len(cell.splitlines()) == 1:
2653 if len(cell.splitlines()) == 1:
2660 # Dynamic transformations - only applied for single line commands
2654 # Dynamic transformations - only applied for single line commands
2661 with self.builtin_trap:
2655 with self.builtin_trap:
2662 try:
2656 try:
2663 # use prefilter_lines to handle trailing newlines
2657 # use prefilter_lines to handle trailing newlines
2664 # restore trailing newline for ast.parse
2658 # restore trailing newline for ast.parse
2665 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2659 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2666 except Exception:
2660 except Exception:
2667 # don't allow prefilter errors to crash IPython
2661 # don't allow prefilter errors to crash IPython
2668 preprocessing_exc_tuple = sys.exc_info()
2662 preprocessing_exc_tuple = sys.exc_info()
2669
2663
2670 # Store raw and processed history
2664 # Store raw and processed history
2671 if store_history:
2665 if store_history:
2672 self.history_manager.store_inputs(self.execution_count,
2666 self.history_manager.store_inputs(self.execution_count,
2673 cell, raw_cell)
2667 cell, raw_cell)
2674 if not silent:
2668 if not silent:
2675 self.logger.log(cell, raw_cell)
2669 self.logger.log(cell, raw_cell)
2676
2670
2677 # Display the exception if input processing failed.
2671 # Display the exception if input processing failed.
2678 if preprocessing_exc_tuple is not None:
2672 if preprocessing_exc_tuple is not None:
2679 self.showtraceback(preprocessing_exc_tuple)
2673 self.showtraceback(preprocessing_exc_tuple)
2680 if store_history:
2674 if store_history:
2681 self.execution_count += 1
2675 self.execution_count += 1
2682 return error_before_exec(preprocessing_exc_tuple[2])
2676 return error_before_exec(preprocessing_exc_tuple[2])
2683
2677
2684 # Our own compiler remembers the __future__ environment. If we want to
2678 # Our own compiler remembers the __future__ environment. If we want to
2685 # run code with a separate __future__ environment, use the default
2679 # run code with a separate __future__ environment, use the default
2686 # compiler
2680 # compiler
2687 compiler = self.compile if shell_futures else CachingCompiler()
2681 compiler = self.compile if shell_futures else CachingCompiler()
2688
2682
2689 with self.builtin_trap:
2683 with self.builtin_trap:
2690 cell_name = self.compile.cache(cell, self.execution_count)
2684 cell_name = self.compile.cache(cell, self.execution_count)
2691
2685
2692 with self.display_trap:
2686 with self.display_trap:
2693 # Compile to bytecode
2687 # Compile to bytecode
2694 try:
2688 try:
2695 code_ast = compiler.ast_parse(cell, filename=cell_name)
2689 code_ast = compiler.ast_parse(cell, filename=cell_name)
2696 except IndentationError as e:
2690 except IndentationError as e:
2697 self.showindentationerror()
2691 self.showindentationerror()
2698 if store_history:
2692 if store_history:
2699 self.execution_count += 1
2693 self.execution_count += 1
2700 return error_before_exec(e)
2694 return error_before_exec(e)
2701 except (OverflowError, SyntaxError, ValueError, TypeError,
2695 except (OverflowError, SyntaxError, ValueError, TypeError,
2702 MemoryError) as e:
2696 MemoryError) as e:
2703 self.showsyntaxerror()
2697 self.showsyntaxerror()
2704 if store_history:
2698 if store_history:
2705 self.execution_count += 1
2699 self.execution_count += 1
2706 return error_before_exec(e)
2700 return error_before_exec(e)
2707
2701
2708 # Apply AST transformations
2702 # Apply AST transformations
2709 try:
2703 try:
2710 code_ast = self.transform_ast(code_ast)
2704 code_ast = self.transform_ast(code_ast)
2711 except InputRejected as e:
2705 except InputRejected as e:
2712 self.showtraceback()
2706 self.showtraceback()
2713 if store_history:
2707 if store_history:
2714 self.execution_count += 1
2708 self.execution_count += 1
2715 return error_before_exec(e)
2709 return error_before_exec(e)
2716
2710
2717 # Give the displayhook a reference to our ExecutionResult so it
2711 # Give the displayhook a reference to our ExecutionResult so it
2718 # can fill in the output value.
2712 # can fill in the output value.
2719 self.displayhook.exec_result = result
2713 self.displayhook.exec_result = result
2720
2714
2721 # Execute the user code
2715 # Execute the user code
2722 interactivity = "none" if silent else self.ast_node_interactivity
2716 interactivity = "none" if silent else self.ast_node_interactivity
2723 self.run_ast_nodes(code_ast.body, cell_name,
2717 self.run_ast_nodes(code_ast.body, cell_name,
2724 interactivity=interactivity, compiler=compiler, result=result)
2718 interactivity=interactivity, compiler=compiler, result=result)
2725
2719
2726 # Reset this so later displayed values do not modify the
2720 # Reset this so later displayed values do not modify the
2727 # ExecutionResult
2721 # ExecutionResult
2728 self.displayhook.exec_result = None
2722 self.displayhook.exec_result = None
2729
2723
2730 self.events.trigger('post_execute')
2724 self.events.trigger('post_execute')
2731 if not silent:
2725 if not silent:
2732 self.events.trigger('post_run_cell')
2726 self.events.trigger('post_run_cell')
2733
2727
2734 if store_history:
2728 if store_history:
2735 # Write output to the database. Does nothing unless
2729 # Write output to the database. Does nothing unless
2736 # history output logging is enabled.
2730 # history output logging is enabled.
2737 self.history_manager.store_output(self.execution_count)
2731 self.history_manager.store_output(self.execution_count)
2738 # Each cell is a *single* input, regardless of how many lines it has
2732 # Each cell is a *single* input, regardless of how many lines it has
2739 self.execution_count += 1
2733 self.execution_count += 1
2740
2734
2741 return result
2735 return result
2742
2736
2743 def transform_ast(self, node):
2737 def transform_ast(self, node):
2744 """Apply the AST transformations from self.ast_transformers
2738 """Apply the AST transformations from self.ast_transformers
2745
2739
2746 Parameters
2740 Parameters
2747 ----------
2741 ----------
2748 node : ast.Node
2742 node : ast.Node
2749 The root node to be transformed. Typically called with the ast.Module
2743 The root node to be transformed. Typically called with the ast.Module
2750 produced by parsing user input.
2744 produced by parsing user input.
2751
2745
2752 Returns
2746 Returns
2753 -------
2747 -------
2754 An ast.Node corresponding to the node it was called with. Note that it
2748 An ast.Node corresponding to the node it was called with. Note that it
2755 may also modify the passed object, so don't rely on references to the
2749 may also modify the passed object, so don't rely on references to the
2756 original AST.
2750 original AST.
2757 """
2751 """
2758 for transformer in self.ast_transformers:
2752 for transformer in self.ast_transformers:
2759 try:
2753 try:
2760 node = transformer.visit(node)
2754 node = transformer.visit(node)
2761 except InputRejected:
2755 except InputRejected:
2762 # User-supplied AST transformers can reject an input by raising
2756 # User-supplied AST transformers can reject an input by raising
2763 # an InputRejected. Short-circuit in this case so that we
2757 # an InputRejected. Short-circuit in this case so that we
2764 # don't unregister the transform.
2758 # don't unregister the transform.
2765 raise
2759 raise
2766 except Exception:
2760 except Exception:
2767 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2761 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2768 self.ast_transformers.remove(transformer)
2762 self.ast_transformers.remove(transformer)
2769
2763
2770 if self.ast_transformers:
2764 if self.ast_transformers:
2771 ast.fix_missing_locations(node)
2765 ast.fix_missing_locations(node)
2772 return node
2766 return node
2773
2767
2774
2768
2775 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2769 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2776 compiler=compile, result=None):
2770 compiler=compile, result=None):
2777 """Run a sequence of AST nodes. The execution mode depends on the
2771 """Run a sequence of AST nodes. The execution mode depends on the
2778 interactivity parameter.
2772 interactivity parameter.
2779
2773
2780 Parameters
2774 Parameters
2781 ----------
2775 ----------
2782 nodelist : list
2776 nodelist : list
2783 A sequence of AST nodes to run.
2777 A sequence of AST nodes to run.
2784 cell_name : str
2778 cell_name : str
2785 Will be passed to the compiler as the filename of the cell. Typically
2779 Will be passed to the compiler as the filename of the cell. Typically
2786 the value returned by ip.compile.cache(cell).
2780 the value returned by ip.compile.cache(cell).
2787 interactivity : str
2781 interactivity : str
2788 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2782 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2789 run interactively (displaying output from expressions). 'last_expr'
2783 run interactively (displaying output from expressions). 'last_expr'
2790 will run the last node interactively only if it is an expression (i.e.
2784 will run the last node interactively only if it is an expression (i.e.
2791 expressions in loops or other blocks are not displayed. Other values
2785 expressions in loops or other blocks are not displayed. Other values
2792 for this parameter will raise a ValueError.
2786 for this parameter will raise a ValueError.
2793 compiler : callable
2787 compiler : callable
2794 A function with the same interface as the built-in compile(), to turn
2788 A function with the same interface as the built-in compile(), to turn
2795 the AST nodes into code objects. Default is the built-in compile().
2789 the AST nodes into code objects. Default is the built-in compile().
2796 result : ExecutionResult, optional
2790 result : ExecutionResult, optional
2797 An object to store exceptions that occur during execution.
2791 An object to store exceptions that occur during execution.
2798
2792
2799 Returns
2793 Returns
2800 -------
2794 -------
2801 True if an exception occurred while running code, False if it finished
2795 True if an exception occurred while running code, False if it finished
2802 running.
2796 running.
2803 """
2797 """
2804 if not nodelist:
2798 if not nodelist:
2805 return
2799 return
2806
2800
2807 if interactivity == 'last_expr':
2801 if interactivity == 'last_expr':
2808 if isinstance(nodelist[-1], ast.Expr):
2802 if isinstance(nodelist[-1], ast.Expr):
2809 interactivity = "last"
2803 interactivity = "last"
2810 else:
2804 else:
2811 interactivity = "none"
2805 interactivity = "none"
2812
2806
2813 if interactivity == 'none':
2807 if interactivity == 'none':
2814 to_run_exec, to_run_interactive = nodelist, []
2808 to_run_exec, to_run_interactive = nodelist, []
2815 elif interactivity == 'last':
2809 elif interactivity == 'last':
2816 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2810 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2817 elif interactivity == 'all':
2811 elif interactivity == 'all':
2818 to_run_exec, to_run_interactive = [], nodelist
2812 to_run_exec, to_run_interactive = [], nodelist
2819 else:
2813 else:
2820 raise ValueError("Interactivity was %r" % interactivity)
2814 raise ValueError("Interactivity was %r" % interactivity)
2821
2815
2822 try:
2816 try:
2823 for i, node in enumerate(to_run_exec):
2817 for i, node in enumerate(to_run_exec):
2824 mod = ast.Module([node])
2818 mod = ast.Module([node])
2825 code = compiler(mod, cell_name, "exec")
2819 code = compiler(mod, cell_name, "exec")
2826 if self.run_code(code, result):
2820 if self.run_code(code, result):
2827 return True
2821 return True
2828
2822
2829 for i, node in enumerate(to_run_interactive):
2823 for i, node in enumerate(to_run_interactive):
2830 mod = ast.Interactive([node])
2824 mod = ast.Interactive([node])
2831 code = compiler(mod, cell_name, "single")
2825 code = compiler(mod, cell_name, "single")
2832 if self.run_code(code, result):
2826 if self.run_code(code, result):
2833 return True
2827 return True
2834
2828
2835 # Flush softspace
2829 # Flush softspace
2836 if softspace(sys.stdout, 0):
2830 if softspace(sys.stdout, 0):
2837 print()
2831 print()
2838
2832
2839 except:
2833 except:
2840 # It's possible to have exceptions raised here, typically by
2834 # It's possible to have exceptions raised here, typically by
2841 # compilation of odd code (such as a naked 'return' outside a
2835 # compilation of odd code (such as a naked 'return' outside a
2842 # function) that did parse but isn't valid. Typically the exception
2836 # function) that did parse but isn't valid. Typically the exception
2843 # is a SyntaxError, but it's safest just to catch anything and show
2837 # is a SyntaxError, but it's safest just to catch anything and show
2844 # the user a traceback.
2838 # the user a traceback.
2845
2839
2846 # We do only one try/except outside the loop to minimize the impact
2840 # We do only one try/except outside the loop to minimize the impact
2847 # on runtime, and also because if any node in the node list is
2841 # on runtime, and also because if any node in the node list is
2848 # broken, we should stop execution completely.
2842 # broken, we should stop execution completely.
2849 if result:
2843 if result:
2850 result.error_before_exec = sys.exc_info()[1]
2844 result.error_before_exec = sys.exc_info()[1]
2851 self.showtraceback()
2845 self.showtraceback()
2852 return True
2846 return True
2853
2847
2854 return False
2848 return False
2855
2849
2856 def run_code(self, code_obj, result=None):
2850 def run_code(self, code_obj, result=None):
2857 """Execute a code object.
2851 """Execute a code object.
2858
2852
2859 When an exception occurs, self.showtraceback() is called to display a
2853 When an exception occurs, self.showtraceback() is called to display a
2860 traceback.
2854 traceback.
2861
2855
2862 Parameters
2856 Parameters
2863 ----------
2857 ----------
2864 code_obj : code object
2858 code_obj : code object
2865 A compiled code object, to be executed
2859 A compiled code object, to be executed
2866 result : ExecutionResult, optional
2860 result : ExecutionResult, optional
2867 An object to store exceptions that occur during execution.
2861 An object to store exceptions that occur during execution.
2868
2862
2869 Returns
2863 Returns
2870 -------
2864 -------
2871 False : successful execution.
2865 False : successful execution.
2872 True : an error occurred.
2866 True : an error occurred.
2873 """
2867 """
2874 # Set our own excepthook in case the user code tries to call it
2868 # Set our own excepthook in case the user code tries to call it
2875 # directly, so that the IPython crash handler doesn't get triggered
2869 # directly, so that the IPython crash handler doesn't get triggered
2876 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2870 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2877
2871
2878 # we save the original sys.excepthook in the instance, in case config
2872 # we save the original sys.excepthook in the instance, in case config
2879 # code (such as magics) needs access to it.
2873 # code (such as magics) needs access to it.
2880 self.sys_excepthook = old_excepthook
2874 self.sys_excepthook = old_excepthook
2881 outflag = 1 # happens in more places, so it's easier as default
2875 outflag = 1 # happens in more places, so it's easier as default
2882 try:
2876 try:
2883 try:
2877 try:
2884 self.hooks.pre_run_code_hook()
2878 self.hooks.pre_run_code_hook()
2885 #rprint('Running code', repr(code_obj)) # dbg
2879 #rprint('Running code', repr(code_obj)) # dbg
2886 exec(code_obj, self.user_global_ns, self.user_ns)
2880 exec(code_obj, self.user_global_ns, self.user_ns)
2887 finally:
2881 finally:
2888 # Reset our crash handler in place
2882 # Reset our crash handler in place
2889 sys.excepthook = old_excepthook
2883 sys.excepthook = old_excepthook
2890 except SystemExit as e:
2884 except SystemExit as e:
2891 if result is not None:
2885 if result is not None:
2892 result.error_in_exec = e
2886 result.error_in_exec = e
2893 self.showtraceback(exception_only=True)
2887 self.showtraceback(exception_only=True)
2894 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2888 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2895 except self.custom_exceptions:
2889 except self.custom_exceptions:
2896 etype, value, tb = sys.exc_info()
2890 etype, value, tb = sys.exc_info()
2897 if result is not None:
2891 if result is not None:
2898 result.error_in_exec = value
2892 result.error_in_exec = value
2899 self.CustomTB(etype, value, tb)
2893 self.CustomTB(etype, value, tb)
2900 except:
2894 except:
2901 if result is not None:
2895 if result is not None:
2902 result.error_in_exec = sys.exc_info()[1]
2896 result.error_in_exec = sys.exc_info()[1]
2903 self.showtraceback()
2897 self.showtraceback()
2904 else:
2898 else:
2905 outflag = 0
2899 outflag = 0
2906 return outflag
2900 return outflag
2907
2901
2908 # For backwards compatibility
2902 # For backwards compatibility
2909 runcode = run_code
2903 runcode = run_code
2910
2904
2911 #-------------------------------------------------------------------------
2905 #-------------------------------------------------------------------------
2912 # Things related to GUI support and pylab
2906 # Things related to GUI support and pylab
2913 #-------------------------------------------------------------------------
2907 #-------------------------------------------------------------------------
2914
2908
2915 def enable_gui(self, gui=None):
2909 def enable_gui(self, gui=None):
2916 raise NotImplementedError('Implement enable_gui in a subclass')
2910 raise NotImplementedError('Implement enable_gui in a subclass')
2917
2911
2918 def enable_matplotlib(self, gui=None):
2912 def enable_matplotlib(self, gui=None):
2919 """Enable interactive matplotlib and inline figure support.
2913 """Enable interactive matplotlib and inline figure support.
2920
2914
2921 This takes the following steps:
2915 This takes the following steps:
2922
2916
2923 1. select the appropriate eventloop and matplotlib backend
2917 1. select the appropriate eventloop and matplotlib backend
2924 2. set up matplotlib for interactive use with that backend
2918 2. set up matplotlib for interactive use with that backend
2925 3. configure formatters for inline figure display
2919 3. configure formatters for inline figure display
2926 4. enable the selected gui eventloop
2920 4. enable the selected gui eventloop
2927
2921
2928 Parameters
2922 Parameters
2929 ----------
2923 ----------
2930 gui : optional, string
2924 gui : optional, string
2931 If given, dictates the choice of matplotlib GUI backend to use
2925 If given, dictates the choice of matplotlib GUI backend to use
2932 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2926 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2933 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2927 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2934 matplotlib (as dictated by the matplotlib build-time options plus the
2928 matplotlib (as dictated by the matplotlib build-time options plus the
2935 user's matplotlibrc configuration file). Note that not all backends
2929 user's matplotlibrc configuration file). Note that not all backends
2936 make sense in all contexts, for example a terminal ipython can't
2930 make sense in all contexts, for example a terminal ipython can't
2937 display figures inline.
2931 display figures inline.
2938 """
2932 """
2939 from IPython.core import pylabtools as pt
2933 from IPython.core import pylabtools as pt
2940 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2934 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2941
2935
2942 if gui != 'inline':
2936 if gui != 'inline':
2943 # If we have our first gui selection, store it
2937 # If we have our first gui selection, store it
2944 if self.pylab_gui_select is None:
2938 if self.pylab_gui_select is None:
2945 self.pylab_gui_select = gui
2939 self.pylab_gui_select = gui
2946 # Otherwise if they are different
2940 # Otherwise if they are different
2947 elif gui != self.pylab_gui_select:
2941 elif gui != self.pylab_gui_select:
2948 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2942 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2949 ' Using %s instead.' % (gui, self.pylab_gui_select))
2943 ' Using %s instead.' % (gui, self.pylab_gui_select))
2950 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2944 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2951
2945
2952 pt.activate_matplotlib(backend)
2946 pt.activate_matplotlib(backend)
2953 pt.configure_inline_support(self, backend)
2947 pt.configure_inline_support(self, backend)
2954
2948
2955 # Now we must activate the gui pylab wants to use, and fix %run to take
2949 # Now we must activate the gui pylab wants to use, and fix %run to take
2956 # plot updates into account
2950 # plot updates into account
2957 self.enable_gui(gui)
2951 self.enable_gui(gui)
2958 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2952 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2959 pt.mpl_runner(self.safe_execfile)
2953 pt.mpl_runner(self.safe_execfile)
2960
2954
2961 return gui, backend
2955 return gui, backend
2962
2956
2963 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2957 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2964 """Activate pylab support at runtime.
2958 """Activate pylab support at runtime.
2965
2959
2966 This turns on support for matplotlib, preloads into the interactive
2960 This turns on support for matplotlib, preloads into the interactive
2967 namespace all of numpy and pylab, and configures IPython to correctly
2961 namespace all of numpy and pylab, and configures IPython to correctly
2968 interact with the GUI event loop. The GUI backend to be used can be
2962 interact with the GUI event loop. The GUI backend to be used can be
2969 optionally selected with the optional ``gui`` argument.
2963 optionally selected with the optional ``gui`` argument.
2970
2964
2971 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2965 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2972
2966
2973 Parameters
2967 Parameters
2974 ----------
2968 ----------
2975 gui : optional, string
2969 gui : optional, string
2976 If given, dictates the choice of matplotlib GUI backend to use
2970 If given, dictates the choice of matplotlib GUI backend to use
2977 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2971 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2978 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2972 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2979 matplotlib (as dictated by the matplotlib build-time options plus the
2973 matplotlib (as dictated by the matplotlib build-time options plus the
2980 user's matplotlibrc configuration file). Note that not all backends
2974 user's matplotlibrc configuration file). Note that not all backends
2981 make sense in all contexts, for example a terminal ipython can't
2975 make sense in all contexts, for example a terminal ipython can't
2982 display figures inline.
2976 display figures inline.
2983 import_all : optional, bool, default: True
2977 import_all : optional, bool, default: True
2984 Whether to do `from numpy import *` and `from pylab import *`
2978 Whether to do `from numpy import *` and `from pylab import *`
2985 in addition to module imports.
2979 in addition to module imports.
2986 welcome_message : deprecated
2980 welcome_message : deprecated
2987 This argument is ignored, no welcome message will be displayed.
2981 This argument is ignored, no welcome message will be displayed.
2988 """
2982 """
2989 from IPython.core.pylabtools import import_pylab
2983 from IPython.core.pylabtools import import_pylab
2990
2984
2991 gui, backend = self.enable_matplotlib(gui)
2985 gui, backend = self.enable_matplotlib(gui)
2992
2986
2993 # We want to prevent the loading of pylab to pollute the user's
2987 # We want to prevent the loading of pylab to pollute the user's
2994 # namespace as shown by the %who* magics, so we execute the activation
2988 # namespace as shown by the %who* magics, so we execute the activation
2995 # code in an empty namespace, and we update *both* user_ns and
2989 # code in an empty namespace, and we update *both* user_ns and
2996 # user_ns_hidden with this information.
2990 # user_ns_hidden with this information.
2997 ns = {}
2991 ns = {}
2998 import_pylab(ns, import_all)
2992 import_pylab(ns, import_all)
2999 # warn about clobbered names
2993 # warn about clobbered names
3000 ignored = {"__builtins__"}
2994 ignored = {"__builtins__"}
3001 both = set(ns).intersection(self.user_ns).difference(ignored)
2995 both = set(ns).intersection(self.user_ns).difference(ignored)
3002 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2996 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3003 self.user_ns.update(ns)
2997 self.user_ns.update(ns)
3004 self.user_ns_hidden.update(ns)
2998 self.user_ns_hidden.update(ns)
3005 return gui, backend, clobbered
2999 return gui, backend, clobbered
3006
3000
3007 #-------------------------------------------------------------------------
3001 #-------------------------------------------------------------------------
3008 # Utilities
3002 # Utilities
3009 #-------------------------------------------------------------------------
3003 #-------------------------------------------------------------------------
3010
3004
3011 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3005 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3012 """Expand python variables in a string.
3006 """Expand python variables in a string.
3013
3007
3014 The depth argument indicates how many frames above the caller should
3008 The depth argument indicates how many frames above the caller should
3015 be walked to look for the local namespace where to expand variables.
3009 be walked to look for the local namespace where to expand variables.
3016
3010
3017 The global namespace for expansion is always the user's interactive
3011 The global namespace for expansion is always the user's interactive
3018 namespace.
3012 namespace.
3019 """
3013 """
3020 ns = self.user_ns.copy()
3014 ns = self.user_ns.copy()
3021 try:
3015 try:
3022 frame = sys._getframe(depth+1)
3016 frame = sys._getframe(depth+1)
3023 except ValueError:
3017 except ValueError:
3024 # This is thrown if there aren't that many frames on the stack,
3018 # This is thrown if there aren't that many frames on the stack,
3025 # e.g. if a script called run_line_magic() directly.
3019 # e.g. if a script called run_line_magic() directly.
3026 pass
3020 pass
3027 else:
3021 else:
3028 ns.update(frame.f_locals)
3022 ns.update(frame.f_locals)
3029
3023
3030 try:
3024 try:
3031 # We have to use .vformat() here, because 'self' is a valid and common
3025 # We have to use .vformat() here, because 'self' is a valid and common
3032 # name, and expanding **ns for .format() would make it collide with
3026 # name, and expanding **ns for .format() would make it collide with
3033 # the 'self' argument of the method.
3027 # the 'self' argument of the method.
3034 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3028 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3035 except Exception:
3029 except Exception:
3036 # if formatter couldn't format, just let it go untransformed
3030 # if formatter couldn't format, just let it go untransformed
3037 pass
3031 pass
3038 return cmd
3032 return cmd
3039
3033
3040 def mktempfile(self, data=None, prefix='ipython_edit_'):
3034 def mktempfile(self, data=None, prefix='ipython_edit_'):
3041 """Make a new tempfile and return its filename.
3035 """Make a new tempfile and return its filename.
3042
3036
3043 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3037 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3044 but it registers the created filename internally so ipython cleans it up
3038 but it registers the created filename internally so ipython cleans it up
3045 at exit time.
3039 at exit time.
3046
3040
3047 Optional inputs:
3041 Optional inputs:
3048
3042
3049 - data(None): if data is given, it gets written out to the temp file
3043 - data(None): if data is given, it gets written out to the temp file
3050 immediately, and the file is closed again."""
3044 immediately, and the file is closed again."""
3051
3045
3052 dirname = tempfile.mkdtemp(prefix=prefix)
3046 dirname = tempfile.mkdtemp(prefix=prefix)
3053 self.tempdirs.append(dirname)
3047 self.tempdirs.append(dirname)
3054
3048
3055 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3049 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3056 os.close(handle) # On Windows, there can only be one open handle on a file
3050 os.close(handle) # On Windows, there can only be one open handle on a file
3057 self.tempfiles.append(filename)
3051 self.tempfiles.append(filename)
3058
3052
3059 if data:
3053 if data:
3060 tmp_file = open(filename,'w')
3054 tmp_file = open(filename,'w')
3061 tmp_file.write(data)
3055 tmp_file.write(data)
3062 tmp_file.close()
3056 tmp_file.close()
3063 return filename
3057 return filename
3064
3058
3065 @undoc
3059 @undoc
3066 def write(self,data):
3060 def write(self,data):
3067 """DEPRECATED: Write a string to the default output"""
3061 """DEPRECATED: Write a string to the default output"""
3068 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3062 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3069 DeprecationWarning, stacklevel=2)
3063 DeprecationWarning, stacklevel=2)
3070 sys.stdout.write(data)
3064 sys.stdout.write(data)
3071
3065
3072 @undoc
3066 @undoc
3073 def write_err(self,data):
3067 def write_err(self,data):
3074 """DEPRECATED: Write a string to the default error output"""
3068 """DEPRECATED: Write a string to the default error output"""
3075 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3069 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3076 DeprecationWarning, stacklevel=2)
3070 DeprecationWarning, stacklevel=2)
3077 sys.stderr.write(data)
3071 sys.stderr.write(data)
3078
3072
3079 def ask_yes_no(self, prompt, default=None, interrupt=None):
3073 def ask_yes_no(self, prompt, default=None, interrupt=None):
3080 if self.quiet:
3074 if self.quiet:
3081 return True
3075 return True
3082 return ask_yes_no(prompt,default,interrupt)
3076 return ask_yes_no(prompt,default,interrupt)
3083
3077
3084 def show_usage(self):
3078 def show_usage(self):
3085 """Show a usage message"""
3079 """Show a usage message"""
3086 page.page(IPython.core.usage.interactive_usage)
3080 page.page(IPython.core.usage.interactive_usage)
3087
3081
3088 def extract_input_lines(self, range_str, raw=False):
3082 def extract_input_lines(self, range_str, raw=False):
3089 """Return as a string a set of input history slices.
3083 """Return as a string a set of input history slices.
3090
3084
3091 Parameters
3085 Parameters
3092 ----------
3086 ----------
3093 range_str : string
3087 range_str : string
3094 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3088 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3095 since this function is for use by magic functions which get their
3089 since this function is for use by magic functions which get their
3096 arguments as strings. The number before the / is the session
3090 arguments as strings. The number before the / is the session
3097 number: ~n goes n back from the current session.
3091 number: ~n goes n back from the current session.
3098
3092
3099 raw : bool, optional
3093 raw : bool, optional
3100 By default, the processed input is used. If this is true, the raw
3094 By default, the processed input is used. If this is true, the raw
3101 input history is used instead.
3095 input history is used instead.
3102
3096
3103 Notes
3097 Notes
3104 -----
3098 -----
3105
3099
3106 Slices can be described with two notations:
3100 Slices can be described with two notations:
3107
3101
3108 * ``N:M`` -> standard python form, means including items N...(M-1).
3102 * ``N:M`` -> standard python form, means including items N...(M-1).
3109 * ``N-M`` -> include items N..M (closed endpoint).
3103 * ``N-M`` -> include items N..M (closed endpoint).
3110 """
3104 """
3111 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3105 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3112 return "\n".join(x for _, _, x in lines)
3106 return "\n".join(x for _, _, x in lines)
3113
3107
3114 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3108 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3115 """Get a code string from history, file, url, or a string or macro.
3109 """Get a code string from history, file, url, or a string or macro.
3116
3110
3117 This is mainly used by magic functions.
3111 This is mainly used by magic functions.
3118
3112
3119 Parameters
3113 Parameters
3120 ----------
3114 ----------
3121
3115
3122 target : str
3116 target : str
3123
3117
3124 A string specifying code to retrieve. This will be tried respectively
3118 A string specifying code to retrieve. This will be tried respectively
3125 as: ranges of input history (see %history for syntax), url,
3119 as: ranges of input history (see %history for syntax), url,
3126 corresponding .py file, filename, or an expression evaluating to a
3120 corresponding .py file, filename, or an expression evaluating to a
3127 string or Macro in the user namespace.
3121 string or Macro in the user namespace.
3128
3122
3129 raw : bool
3123 raw : bool
3130 If true (default), retrieve raw history. Has no effect on the other
3124 If true (default), retrieve raw history. Has no effect on the other
3131 retrieval mechanisms.
3125 retrieval mechanisms.
3132
3126
3133 py_only : bool (default False)
3127 py_only : bool (default False)
3134 Only try to fetch python code, do not try alternative methods to decode file
3128 Only try to fetch python code, do not try alternative methods to decode file
3135 if unicode fails.
3129 if unicode fails.
3136
3130
3137 Returns
3131 Returns
3138 -------
3132 -------
3139 A string of code.
3133 A string of code.
3140
3134
3141 ValueError is raised if nothing is found, and TypeError if it evaluates
3135 ValueError is raised if nothing is found, and TypeError if it evaluates
3142 to an object of another type. In each case, .args[0] is a printable
3136 to an object of another type. In each case, .args[0] is a printable
3143 message.
3137 message.
3144 """
3138 """
3145 code = self.extract_input_lines(target, raw=raw) # Grab history
3139 code = self.extract_input_lines(target, raw=raw) # Grab history
3146 if code:
3140 if code:
3147 return code
3141 return code
3148 utarget = unquote_filename(target)
3142 utarget = unquote_filename(target)
3149 try:
3143 try:
3150 if utarget.startswith(('http://', 'https://')):
3144 if utarget.startswith(('http://', 'https://')):
3151 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3145 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3152 except UnicodeDecodeError:
3146 except UnicodeDecodeError:
3153 if not py_only :
3147 if not py_only :
3154 # Deferred import
3148 # Deferred import
3155 try:
3149 try:
3156 from urllib.request import urlopen # Py3
3150 from urllib.request import urlopen # Py3
3157 except ImportError:
3151 except ImportError:
3158 from urllib import urlopen
3152 from urllib import urlopen
3159 response = urlopen(target)
3153 response = urlopen(target)
3160 return response.read().decode('latin1')
3154 return response.read().decode('latin1')
3161 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3155 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3162
3156
3163 potential_target = [target]
3157 potential_target = [target]
3164 try :
3158 try :
3165 potential_target.insert(0,get_py_filename(target))
3159 potential_target.insert(0,get_py_filename(target))
3166 except IOError:
3160 except IOError:
3167 pass
3161 pass
3168
3162
3169 for tgt in potential_target :
3163 for tgt in potential_target :
3170 if os.path.isfile(tgt): # Read file
3164 if os.path.isfile(tgt): # Read file
3171 try :
3165 try :
3172 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3166 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3173 except UnicodeDecodeError :
3167 except UnicodeDecodeError :
3174 if not py_only :
3168 if not py_only :
3175 with io_open(tgt,'r', encoding='latin1') as f :
3169 with io_open(tgt,'r', encoding='latin1') as f :
3176 return f.read()
3170 return f.read()
3177 raise ValueError(("'%s' seem to be unreadable.") % target)
3171 raise ValueError(("'%s' seem to be unreadable.") % target)
3178 elif os.path.isdir(os.path.expanduser(tgt)):
3172 elif os.path.isdir(os.path.expanduser(tgt)):
3179 raise ValueError("'%s' is a directory, not a regular file." % target)
3173 raise ValueError("'%s' is a directory, not a regular file." % target)
3180
3174
3181 if search_ns:
3175 if search_ns:
3182 # Inspect namespace to load object source
3176 # Inspect namespace to load object source
3183 object_info = self.object_inspect(target, detail_level=1)
3177 object_info = self.object_inspect(target, detail_level=1)
3184 if object_info['found'] and object_info['source']:
3178 if object_info['found'] and object_info['source']:
3185 return object_info['source']
3179 return object_info['source']
3186
3180
3187 try: # User namespace
3181 try: # User namespace
3188 codeobj = eval(target, self.user_ns)
3182 codeobj = eval(target, self.user_ns)
3189 except Exception:
3183 except Exception:
3190 raise ValueError(("'%s' was not found in history, as a file, url, "
3184 raise ValueError(("'%s' was not found in history, as a file, url, "
3191 "nor in the user namespace.") % target)
3185 "nor in the user namespace.") % target)
3192
3186
3193 if isinstance(codeobj, string_types):
3187 if isinstance(codeobj, string_types):
3194 return codeobj
3188 return codeobj
3195 elif isinstance(codeobj, Macro):
3189 elif isinstance(codeobj, Macro):
3196 return codeobj.value
3190 return codeobj.value
3197
3191
3198 raise TypeError("%s is neither a string nor a macro." % target,
3192 raise TypeError("%s is neither a string nor a macro." % target,
3199 codeobj)
3193 codeobj)
3200
3194
3201 #-------------------------------------------------------------------------
3195 #-------------------------------------------------------------------------
3202 # Things related to IPython exiting
3196 # Things related to IPython exiting
3203 #-------------------------------------------------------------------------
3197 #-------------------------------------------------------------------------
3204 def atexit_operations(self):
3198 def atexit_operations(self):
3205 """This will be executed at the time of exit.
3199 """This will be executed at the time of exit.
3206
3200
3207 Cleanup operations and saving of persistent data that is done
3201 Cleanup operations and saving of persistent data that is done
3208 unconditionally by IPython should be performed here.
3202 unconditionally by IPython should be performed here.
3209
3203
3210 For things that may depend on startup flags or platform specifics (such
3204 For things that may depend on startup flags or platform specifics (such
3211 as having readline or not), register a separate atexit function in the
3205 as having readline or not), register a separate atexit function in the
3212 code that has the appropriate information, rather than trying to
3206 code that has the appropriate information, rather than trying to
3213 clutter
3207 clutter
3214 """
3208 """
3215 # Close the history session (this stores the end time and line count)
3209 # Close the history session (this stores the end time and line count)
3216 # this must be *before* the tempfile cleanup, in case of temporary
3210 # this must be *before* the tempfile cleanup, in case of temporary
3217 # history db
3211 # history db
3218 self.history_manager.end_session()
3212 self.history_manager.end_session()
3219
3213
3220 # Cleanup all tempfiles and folders left around
3214 # Cleanup all tempfiles and folders left around
3221 for tfile in self.tempfiles:
3215 for tfile in self.tempfiles:
3222 try:
3216 try:
3223 os.unlink(tfile)
3217 os.unlink(tfile)
3224 except OSError:
3218 except OSError:
3225 pass
3219 pass
3226
3220
3227 for tdir in self.tempdirs:
3221 for tdir in self.tempdirs:
3228 try:
3222 try:
3229 os.rmdir(tdir)
3223 os.rmdir(tdir)
3230 except OSError:
3224 except OSError:
3231 pass
3225 pass
3232
3226
3233 # Clear all user namespaces to release all references cleanly.
3227 # Clear all user namespaces to release all references cleanly.
3234 self.reset(new_session=False)
3228 self.reset(new_session=False)
3235
3229
3236 # Run user hooks
3230 # Run user hooks
3237 self.hooks.shutdown_hook()
3231 self.hooks.shutdown_hook()
3238
3232
3239 def cleanup(self):
3233 def cleanup(self):
3240 self.restore_sys_module_state()
3234 self.restore_sys_module_state()
3241
3235
3242
3236
3243 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3237 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3244 """An abstract base class for InteractiveShell."""
3238 """An abstract base class for InteractiveShell."""
3245
3239
3246 InteractiveShellABC.register(InteractiveShell)
3240 InteractiveShellABC.register(InteractiveShell)
@@ -1,437 +1,429 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 A mixin for :class:`~IPython.core.application.Application` classes that
3 A mixin for :class:`~IPython.core.application.Application` classes that
4 launch InteractiveShell instances, load extensions, etc.
4 launch InteractiveShell instances, load extensions, etc.
5 """
5 """
6
6
7 # Copyright (c) IPython Development Team.
7 # Copyright (c) IPython Development Team.
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9
9
10 from __future__ import absolute_import
10 from __future__ import absolute_import
11 from __future__ import print_function
11 from __future__ import print_function
12
12
13 import glob
13 import glob
14 import os
14 import os
15 import sys
15 import sys
16
16
17 from traitlets.config.application import boolean_flag
17 from traitlets.config.application import boolean_flag
18 from traitlets.config.configurable import Configurable
18 from traitlets.config.configurable import Configurable
19 from traitlets.config.loader import Config
19 from traitlets.config.loader import Config
20 from IPython.core import pylabtools
20 from IPython.core import pylabtools
21 from IPython.utils import py3compat
21 from IPython.utils import py3compat
22 from IPython.utils.contexts import preserve_keys
22 from IPython.utils.contexts import preserve_keys
23 from IPython.utils.path import filefind
23 from IPython.utils.path import filefind
24 from traitlets import (
24 from traitlets import (
25 Unicode, Instance, List, Bool, CaselessStrEnum, default, observe,
25 Unicode, Instance, List, Bool, CaselessStrEnum, observe,
26 )
26 )
27 from IPython.lib.inputhook import guis
27 from IPython.lib.inputhook import guis
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Aliases and Flags
30 # Aliases and Flags
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 gui_keys = tuple(sorted([ key for key in guis if key is not None ]))
33 gui_keys = tuple(sorted([ key for key in guis if key is not None ]))
34
34
35 backend_keys = sorted(pylabtools.backends.keys())
35 backend_keys = sorted(pylabtools.backends.keys())
36 backend_keys.insert(0, 'auto')
36 backend_keys.insert(0, 'auto')
37
37
38 shell_flags = {}
38 shell_flags = {}
39
39
40 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
40 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
41 addflag('autoindent', 'InteractiveShell.autoindent',
41 addflag('autoindent', 'InteractiveShell.autoindent',
42 'Turn on autoindenting.', 'Turn off autoindenting.'
42 'Turn on autoindenting.', 'Turn off autoindenting.'
43 )
43 )
44 addflag('automagic', 'InteractiveShell.automagic',
44 addflag('automagic', 'InteractiveShell.automagic',
45 """Turn on the auto calling of magic commands. Type %%magic at the
45 """Turn on the auto calling of magic commands. Type %%magic at the
46 IPython prompt for more information.""",
46 IPython prompt for more information.""",
47 'Turn off the auto calling of magic commands.'
47 'Turn off the auto calling of magic commands.'
48 )
48 )
49 addflag('pdb', 'InteractiveShell.pdb',
49 addflag('pdb', 'InteractiveShell.pdb',
50 "Enable auto calling the pdb debugger after every exception.",
50 "Enable auto calling the pdb debugger after every exception.",
51 "Disable auto calling the pdb debugger after every exception."
51 "Disable auto calling the pdb debugger after every exception."
52 )
52 )
53 # pydb flag doesn't do any config, as core.debugger switches on import,
54 # which is before parsing. This just allows the flag to be passed.
55 shell_flags.update(dict(
56 pydb = ({},
57 """Use the third party 'pydb' package as debugger, instead of pdb.
58 Requires that pydb is installed."""
59 )
60 ))
61 addflag('pprint', 'PlainTextFormatter.pprint',
53 addflag('pprint', 'PlainTextFormatter.pprint',
62 "Enable auto pretty printing of results.",
54 "Enable auto pretty printing of results.",
63 "Disable auto pretty printing of results."
55 "Disable auto pretty printing of results."
64 )
56 )
65 addflag('color-info', 'InteractiveShell.color_info',
57 addflag('color-info', 'InteractiveShell.color_info',
66 """IPython can display information about objects via a set of functions,
58 """IPython can display information about objects via a set of functions,
67 and optionally can use colors for this, syntax highlighting
59 and optionally can use colors for this, syntax highlighting
68 source code and various other elements. This is on by default, but can cause
60 source code and various other elements. This is on by default, but can cause
69 problems with some pagers. If you see such problems, you can disable the
61 problems with some pagers. If you see such problems, you can disable the
70 colours.""",
62 colours.""",
71 "Disable using colors for info related things."
63 "Disable using colors for info related things."
72 )
64 )
73 addflag('deep-reload', 'InteractiveShell.deep_reload',
65 addflag('deep-reload', 'InteractiveShell.deep_reload',
74 """ **Deprecated** and will be removed in IPython 5.0.
66 """ **Deprecated** and will be removed in IPython 5.0.
75
67
76 Enable deep (recursive) reloading by default. IPython can use the
68 Enable deep (recursive) reloading by default. IPython can use the
77 deep_reload module which reloads changes in modules recursively (it
69 deep_reload module which reloads changes in modules recursively (it
78 replaces the reload() function, so you don't need to change anything to
70 replaces the reload() function, so you don't need to change anything to
79 use it). deep_reload() forces a full reload of modules whose code may
71 use it). deep_reload() forces a full reload of modules whose code may
80 have changed, which the default reload() function does not. When
72 have changed, which the default reload() function does not. When
81 deep_reload is off, IPython will use the normal reload(), but
73 deep_reload is off, IPython will use the normal reload(), but
82 deep_reload will still be available as dreload(). This feature is off
74 deep_reload will still be available as dreload(). This feature is off
83 by default [which means that you have both normal reload() and
75 by default [which means that you have both normal reload() and
84 dreload()].""",
76 dreload()].""",
85 "Disable deep (recursive) reloading by default."
77 "Disable deep (recursive) reloading by default."
86 )
78 )
87 nosep_config = Config()
79 nosep_config = Config()
88 nosep_config.InteractiveShell.separate_in = ''
80 nosep_config.InteractiveShell.separate_in = ''
89 nosep_config.InteractiveShell.separate_out = ''
81 nosep_config.InteractiveShell.separate_out = ''
90 nosep_config.InteractiveShell.separate_out2 = ''
82 nosep_config.InteractiveShell.separate_out2 = ''
91
83
92 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
84 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
93 shell_flags['pylab'] = (
85 shell_flags['pylab'] = (
94 {'InteractiveShellApp' : {'pylab' : 'auto'}},
86 {'InteractiveShellApp' : {'pylab' : 'auto'}},
95 """Pre-load matplotlib and numpy for interactive use with
87 """Pre-load matplotlib and numpy for interactive use with
96 the default matplotlib backend."""
88 the default matplotlib backend."""
97 )
89 )
98 shell_flags['matplotlib'] = (
90 shell_flags['matplotlib'] = (
99 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
91 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
100 """Configure matplotlib for interactive use with
92 """Configure matplotlib for interactive use with
101 the default matplotlib backend."""
93 the default matplotlib backend."""
102 )
94 )
103
95
104 # it's possible we don't want short aliases for *all* of these:
96 # it's possible we don't want short aliases for *all* of these:
105 shell_aliases = dict(
97 shell_aliases = dict(
106 autocall='InteractiveShell.autocall',
98 autocall='InteractiveShell.autocall',
107 colors='InteractiveShell.colors',
99 colors='InteractiveShell.colors',
108 logfile='InteractiveShell.logfile',
100 logfile='InteractiveShell.logfile',
109 logappend='InteractiveShell.logappend',
101 logappend='InteractiveShell.logappend',
110 c='InteractiveShellApp.code_to_run',
102 c='InteractiveShellApp.code_to_run',
111 m='InteractiveShellApp.module_to_run',
103 m='InteractiveShellApp.module_to_run',
112 ext='InteractiveShellApp.extra_extension',
104 ext='InteractiveShellApp.extra_extension',
113 gui='InteractiveShellApp.gui',
105 gui='InteractiveShellApp.gui',
114 pylab='InteractiveShellApp.pylab',
106 pylab='InteractiveShellApp.pylab',
115 matplotlib='InteractiveShellApp.matplotlib',
107 matplotlib='InteractiveShellApp.matplotlib',
116 )
108 )
117 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
109 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
118
110
119 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
120 # Main classes and functions
112 # Main classes and functions
121 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
122
114
123 class InteractiveShellApp(Configurable):
115 class InteractiveShellApp(Configurable):
124 """A Mixin for applications that start InteractiveShell instances.
116 """A Mixin for applications that start InteractiveShell instances.
125
117
126 Provides configurables for loading extensions and executing files
118 Provides configurables for loading extensions and executing files
127 as part of configuring a Shell environment.
119 as part of configuring a Shell environment.
128
120
129 The following methods should be called by the :meth:`initialize` method
121 The following methods should be called by the :meth:`initialize` method
130 of the subclass:
122 of the subclass:
131
123
132 - :meth:`init_path`
124 - :meth:`init_path`
133 - :meth:`init_shell` (to be implemented by the subclass)
125 - :meth:`init_shell` (to be implemented by the subclass)
134 - :meth:`init_gui_pylab`
126 - :meth:`init_gui_pylab`
135 - :meth:`init_extensions`
127 - :meth:`init_extensions`
136 - :meth:`init_code`
128 - :meth:`init_code`
137 """
129 """
138 extensions = List(Unicode(),
130 extensions = List(Unicode(),
139 help="A list of dotted module names of IPython extensions to load."
131 help="A list of dotted module names of IPython extensions to load."
140 ).tag(config=True)
132 ).tag(config=True)
141 extra_extension = Unicode('',
133 extra_extension = Unicode('',
142 help="dotted module name of an IPython extension to load."
134 help="dotted module name of an IPython extension to load."
143 ).tag(config=True)
135 ).tag(config=True)
144
136
145 reraise_ipython_extension_failures = Bool(False,
137 reraise_ipython_extension_failures = Bool(False,
146 help="Reraise exceptions encountered loading IPython extensions?",
138 help="Reraise exceptions encountered loading IPython extensions?",
147 ).tag(config=True)
139 ).tag(config=True)
148
140
149 # Extensions that are always loaded (not configurable)
141 # Extensions that are always loaded (not configurable)
150 default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
142 default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
151
143
152 hide_initial_ns = Bool(True,
144 hide_initial_ns = Bool(True,
153 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
145 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
154 be hidden from tools like %who?"""
146 be hidden from tools like %who?"""
155 ).tag(config=True)
147 ).tag(config=True)
156
148
157 exec_files = List(Unicode(),
149 exec_files = List(Unicode(),
158 help="""List of files to run at IPython startup."""
150 help="""List of files to run at IPython startup."""
159 ).tag(config=True)
151 ).tag(config=True)
160 exec_PYTHONSTARTUP = Bool(True,
152 exec_PYTHONSTARTUP = Bool(True,
161 help="""Run the file referenced by the PYTHONSTARTUP environment
153 help="""Run the file referenced by the PYTHONSTARTUP environment
162 variable at IPython startup."""
154 variable at IPython startup."""
163 ).tag(config=True)
155 ).tag(config=True)
164 file_to_run = Unicode('',
156 file_to_run = Unicode('',
165 help="""A file to be run""").tag(config=True)
157 help="""A file to be run""").tag(config=True)
166
158
167 exec_lines = List(Unicode(),
159 exec_lines = List(Unicode(),
168 help="""lines of code to run at IPython startup."""
160 help="""lines of code to run at IPython startup."""
169 ).tag(config=True)
161 ).tag(config=True)
170 code_to_run = Unicode('',
162 code_to_run = Unicode('',
171 help="Execute the given command string."
163 help="Execute the given command string."
172 ).tag(config=True)
164 ).tag(config=True)
173 module_to_run = Unicode('',
165 module_to_run = Unicode('',
174 help="Run the module as a script."
166 help="Run the module as a script."
175 ).tag(config=True)
167 ).tag(config=True)
176 gui = CaselessStrEnum(gui_keys, allow_none=True,
168 gui = CaselessStrEnum(gui_keys, allow_none=True,
177 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
169 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
178 ).tag(config=True)
170 ).tag(config=True)
179 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
171 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
180 help="""Configure matplotlib for interactive use with
172 help="""Configure matplotlib for interactive use with
181 the default matplotlib backend."""
173 the default matplotlib backend."""
182 ).tag(config=True)
174 ).tag(config=True)
183 pylab = CaselessStrEnum(backend_keys, allow_none=True,
175 pylab = CaselessStrEnum(backend_keys, allow_none=True,
184 help="""Pre-load matplotlib and numpy for interactive use,
176 help="""Pre-load matplotlib and numpy for interactive use,
185 selecting a particular matplotlib backend and loop integration.
177 selecting a particular matplotlib backend and loop integration.
186 """
178 """
187 ).tag(config=True)
179 ).tag(config=True)
188 pylab_import_all = Bool(True,
180 pylab_import_all = Bool(True,
189 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
181 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
190 and an ``import *`` is done from numpy and pylab, when using pylab mode.
182 and an ``import *`` is done from numpy and pylab, when using pylab mode.
191
183
192 When False, pylab mode should not import any names into the user namespace.
184 When False, pylab mode should not import any names into the user namespace.
193 """
185 """
194 ).tag(config=True)
186 ).tag(config=True)
195 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
187 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
196 allow_none=True)
188 allow_none=True)
197 # whether interact-loop should start
189 # whether interact-loop should start
198 interact = Bool(True)
190 interact = Bool(True)
199
191
200 user_ns = Instance(dict, args=None, allow_none=True)
192 user_ns = Instance(dict, args=None, allow_none=True)
201 @observe('user_ns')
193 @observe('user_ns')
202 def _user_ns_changed(self, change):
194 def _user_ns_changed(self, change):
203 if self.shell is not None:
195 if self.shell is not None:
204 self.shell.user_ns = change['new']
196 self.shell.user_ns = change['new']
205 self.shell.init_user_ns()
197 self.shell.init_user_ns()
206
198
207 def init_path(self):
199 def init_path(self):
208 """Add current working directory, '', to sys.path"""
200 """Add current working directory, '', to sys.path"""
209 if sys.path[0] != '':
201 if sys.path[0] != '':
210 sys.path.insert(0, '')
202 sys.path.insert(0, '')
211
203
212 def init_shell(self):
204 def init_shell(self):
213 raise NotImplementedError("Override in subclasses")
205 raise NotImplementedError("Override in subclasses")
214
206
215 def init_gui_pylab(self):
207 def init_gui_pylab(self):
216 """Enable GUI event loop integration, taking pylab into account."""
208 """Enable GUI event loop integration, taking pylab into account."""
217 enable = False
209 enable = False
218 shell = self.shell
210 shell = self.shell
219 if self.pylab:
211 if self.pylab:
220 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
212 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
221 key = self.pylab
213 key = self.pylab
222 elif self.matplotlib:
214 elif self.matplotlib:
223 enable = shell.enable_matplotlib
215 enable = shell.enable_matplotlib
224 key = self.matplotlib
216 key = self.matplotlib
225 elif self.gui:
217 elif self.gui:
226 enable = shell.enable_gui
218 enable = shell.enable_gui
227 key = self.gui
219 key = self.gui
228
220
229 if not enable:
221 if not enable:
230 return
222 return
231
223
232 try:
224 try:
233 r = enable(key)
225 r = enable(key)
234 except ImportError:
226 except ImportError:
235 self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
227 self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
236 self.shell.showtraceback()
228 self.shell.showtraceback()
237 return
229 return
238 except Exception:
230 except Exception:
239 self.log.warning("GUI event loop or pylab initialization failed")
231 self.log.warning("GUI event loop or pylab initialization failed")
240 self.shell.showtraceback()
232 self.shell.showtraceback()
241 return
233 return
242
234
243 if isinstance(r, tuple):
235 if isinstance(r, tuple):
244 gui, backend = r[:2]
236 gui, backend = r[:2]
245 self.log.info("Enabling GUI event loop integration, "
237 self.log.info("Enabling GUI event loop integration, "
246 "eventloop=%s, matplotlib=%s", gui, backend)
238 "eventloop=%s, matplotlib=%s", gui, backend)
247 if key == "auto":
239 if key == "auto":
248 print("Using matplotlib backend: %s" % backend)
240 print("Using matplotlib backend: %s" % backend)
249 else:
241 else:
250 gui = r
242 gui = r
251 self.log.info("Enabling GUI event loop integration, "
243 self.log.info("Enabling GUI event loop integration, "
252 "eventloop=%s", gui)
244 "eventloop=%s", gui)
253
245
254 def init_extensions(self):
246 def init_extensions(self):
255 """Load all IPython extensions in IPythonApp.extensions.
247 """Load all IPython extensions in IPythonApp.extensions.
256
248
257 This uses the :meth:`ExtensionManager.load_extensions` to load all
249 This uses the :meth:`ExtensionManager.load_extensions` to load all
258 the extensions listed in ``self.extensions``.
250 the extensions listed in ``self.extensions``.
259 """
251 """
260 try:
252 try:
261 self.log.debug("Loading IPython extensions...")
253 self.log.debug("Loading IPython extensions...")
262 extensions = self.default_extensions + self.extensions
254 extensions = self.default_extensions + self.extensions
263 if self.extra_extension:
255 if self.extra_extension:
264 extensions.append(self.extra_extension)
256 extensions.append(self.extra_extension)
265 for ext in extensions:
257 for ext in extensions:
266 try:
258 try:
267 self.log.info("Loading IPython extension: %s" % ext)
259 self.log.info("Loading IPython extension: %s" % ext)
268 self.shell.extension_manager.load_extension(ext)
260 self.shell.extension_manager.load_extension(ext)
269 except:
261 except:
270 if self.reraise_ipython_extension_failures:
262 if self.reraise_ipython_extension_failures:
271 raise
263 raise
272 msg = ("Error in loading extension: {ext}\n"
264 msg = ("Error in loading extension: {ext}\n"
273 "Check your config files in {location}".format(
265 "Check your config files in {location}".format(
274 ext=ext,
266 ext=ext,
275 location=self.profile_dir.location
267 location=self.profile_dir.location
276 ))
268 ))
277 self.log.warning(msg, exc_info=True)
269 self.log.warning(msg, exc_info=True)
278 except:
270 except:
279 if self.reraise_ipython_extension_failures:
271 if self.reraise_ipython_extension_failures:
280 raise
272 raise
281 self.log.warning("Unknown error in loading extensions:", exc_info=True)
273 self.log.warning("Unknown error in loading extensions:", exc_info=True)
282
274
283 def init_code(self):
275 def init_code(self):
284 """run the pre-flight code, specified via exec_lines"""
276 """run the pre-flight code, specified via exec_lines"""
285 self._run_startup_files()
277 self._run_startup_files()
286 self._run_exec_lines()
278 self._run_exec_lines()
287 self._run_exec_files()
279 self._run_exec_files()
288
280
289 # Hide variables defined here from %who etc.
281 # Hide variables defined here from %who etc.
290 if self.hide_initial_ns:
282 if self.hide_initial_ns:
291 self.shell.user_ns_hidden.update(self.shell.user_ns)
283 self.shell.user_ns_hidden.update(self.shell.user_ns)
292
284
293 # command-line execution (ipython -i script.py, ipython -m module)
285 # command-line execution (ipython -i script.py, ipython -m module)
294 # should *not* be excluded from %whos
286 # should *not* be excluded from %whos
295 self._run_cmd_line_code()
287 self._run_cmd_line_code()
296 self._run_module()
288 self._run_module()
297
289
298 # flush output, so itwon't be attached to the first cell
290 # flush output, so itwon't be attached to the first cell
299 sys.stdout.flush()
291 sys.stdout.flush()
300 sys.stderr.flush()
292 sys.stderr.flush()
301
293
302 def _run_exec_lines(self):
294 def _run_exec_lines(self):
303 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
295 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
304 if not self.exec_lines:
296 if not self.exec_lines:
305 return
297 return
306 try:
298 try:
307 self.log.debug("Running code from IPythonApp.exec_lines...")
299 self.log.debug("Running code from IPythonApp.exec_lines...")
308 for line in self.exec_lines:
300 for line in self.exec_lines:
309 try:
301 try:
310 self.log.info("Running code in user namespace: %s" %
302 self.log.info("Running code in user namespace: %s" %
311 line)
303 line)
312 self.shell.run_cell(line, store_history=False)
304 self.shell.run_cell(line, store_history=False)
313 except:
305 except:
314 self.log.warning("Error in executing line in user "
306 self.log.warning("Error in executing line in user "
315 "namespace: %s" % line)
307 "namespace: %s" % line)
316 self.shell.showtraceback()
308 self.shell.showtraceback()
317 except:
309 except:
318 self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
310 self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
319 self.shell.showtraceback()
311 self.shell.showtraceback()
320
312
321 def _exec_file(self, fname, shell_futures=False):
313 def _exec_file(self, fname, shell_futures=False):
322 try:
314 try:
323 full_filename = filefind(fname, [u'.', self.ipython_dir])
315 full_filename = filefind(fname, [u'.', self.ipython_dir])
324 except IOError as e:
316 except IOError:
325 self.log.warning("File not found: %r"%fname)
317 self.log.warning("File not found: %r"%fname)
326 return
318 return
327 # Make sure that the running script gets a proper sys.argv as if it
319 # Make sure that the running script gets a proper sys.argv as if it
328 # were run from a system shell.
320 # were run from a system shell.
329 save_argv = sys.argv
321 save_argv = sys.argv
330 sys.argv = [full_filename] + self.extra_args[1:]
322 sys.argv = [full_filename] + self.extra_args[1:]
331 # protect sys.argv from potential unicode strings on Python 2:
323 # protect sys.argv from potential unicode strings on Python 2:
332 if not py3compat.PY3:
324 if not py3compat.PY3:
333 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
325 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
334 try:
326 try:
335 if os.path.isfile(full_filename):
327 if os.path.isfile(full_filename):
336 self.log.info("Running file in user namespace: %s" %
328 self.log.info("Running file in user namespace: %s" %
337 full_filename)
329 full_filename)
338 # Ensure that __file__ is always defined to match Python
330 # Ensure that __file__ is always defined to match Python
339 # behavior.
331 # behavior.
340 with preserve_keys(self.shell.user_ns, '__file__'):
332 with preserve_keys(self.shell.user_ns, '__file__'):
341 self.shell.user_ns['__file__'] = fname
333 self.shell.user_ns['__file__'] = fname
342 if full_filename.endswith('.ipy'):
334 if full_filename.endswith('.ipy'):
343 self.shell.safe_execfile_ipy(full_filename,
335 self.shell.safe_execfile_ipy(full_filename,
344 shell_futures=shell_futures)
336 shell_futures=shell_futures)
345 else:
337 else:
346 # default to python, even without extension
338 # default to python, even without extension
347 self.shell.safe_execfile(full_filename,
339 self.shell.safe_execfile(full_filename,
348 self.shell.user_ns,
340 self.shell.user_ns,
349 shell_futures=shell_futures,
341 shell_futures=shell_futures,
350 raise_exceptions=True)
342 raise_exceptions=True)
351 finally:
343 finally:
352 sys.argv = save_argv
344 sys.argv = save_argv
353
345
354 def _run_startup_files(self):
346 def _run_startup_files(self):
355 """Run files from profile startup directory"""
347 """Run files from profile startup directory"""
356 startup_dir = self.profile_dir.startup_dir
348 startup_dir = self.profile_dir.startup_dir
357 startup_files = []
349 startup_files = []
358
350
359 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
351 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
360 not (self.file_to_run or self.code_to_run or self.module_to_run):
352 not (self.file_to_run or self.code_to_run or self.module_to_run):
361 python_startup = os.environ['PYTHONSTARTUP']
353 python_startup = os.environ['PYTHONSTARTUP']
362 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
354 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
363 try:
355 try:
364 self._exec_file(python_startup)
356 self._exec_file(python_startup)
365 except:
357 except:
366 self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
358 self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
367 self.shell.showtraceback()
359 self.shell.showtraceback()
368 finally:
360 finally:
369 # Many PYTHONSTARTUP files set up the readline completions,
361 # Many PYTHONSTARTUP files set up the readline completions,
370 # but this is often at odds with IPython's own completions.
362 # but this is often at odds with IPython's own completions.
371 # Do not allow PYTHONSTARTUP to set up readline.
363 # Do not allow PYTHONSTARTUP to set up readline.
372 if self.shell.has_readline:
364 if self.shell.has_readline:
373 self.shell.set_readline_completer()
365 self.shell.set_readline_completer()
374
366
375 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
367 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
376 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
368 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
377 if not startup_files:
369 if not startup_files:
378 return
370 return
379
371
380 self.log.debug("Running startup files from %s...", startup_dir)
372 self.log.debug("Running startup files from %s...", startup_dir)
381 try:
373 try:
382 for fname in sorted(startup_files):
374 for fname in sorted(startup_files):
383 self._exec_file(fname)
375 self._exec_file(fname)
384 except:
376 except:
385 self.log.warning("Unknown error in handling startup files:")
377 self.log.warning("Unknown error in handling startup files:")
386 self.shell.showtraceback()
378 self.shell.showtraceback()
387
379
388 def _run_exec_files(self):
380 def _run_exec_files(self):
389 """Run files from IPythonApp.exec_files"""
381 """Run files from IPythonApp.exec_files"""
390 if not self.exec_files:
382 if not self.exec_files:
391 return
383 return
392
384
393 self.log.debug("Running files in IPythonApp.exec_files...")
385 self.log.debug("Running files in IPythonApp.exec_files...")
394 try:
386 try:
395 for fname in self.exec_files:
387 for fname in self.exec_files:
396 self._exec_file(fname)
388 self._exec_file(fname)
397 except:
389 except:
398 self.log.warning("Unknown error in handling IPythonApp.exec_files:")
390 self.log.warning("Unknown error in handling IPythonApp.exec_files:")
399 self.shell.showtraceback()
391 self.shell.showtraceback()
400
392
401 def _run_cmd_line_code(self):
393 def _run_cmd_line_code(self):
402 """Run code or file specified at the command-line"""
394 """Run code or file specified at the command-line"""
403 if self.code_to_run:
395 if self.code_to_run:
404 line = self.code_to_run
396 line = self.code_to_run
405 try:
397 try:
406 self.log.info("Running code given at command line (c=): %s" %
398 self.log.info("Running code given at command line (c=): %s" %
407 line)
399 line)
408 self.shell.run_cell(line, store_history=False)
400 self.shell.run_cell(line, store_history=False)
409 except:
401 except:
410 self.log.warning("Error in executing line in user namespace: %s" %
402 self.log.warning("Error in executing line in user namespace: %s" %
411 line)
403 line)
412 self.shell.showtraceback()
404 self.shell.showtraceback()
413 if not self.interact:
405 if not self.interact:
414 self.exit(1)
406 self.exit(1)
415
407
416 # Like Python itself, ignore the second if the first of these is present
408 # Like Python itself, ignore the second if the first of these is present
417 elif self.file_to_run:
409 elif self.file_to_run:
418 fname = self.file_to_run
410 fname = self.file_to_run
419 try:
411 try:
420 self._exec_file(fname, shell_futures=True)
412 self._exec_file(fname, shell_futures=True)
421 except:
413 except:
422 self.shell.showtraceback(tb_offset=4)
414 self.shell.showtraceback(tb_offset=4)
423 if not self.interact:
415 if not self.interact:
424 self.exit(1)
416 self.exit(1)
425
417
426 def _run_module(self):
418 def _run_module(self):
427 """Run module specified at the command-line."""
419 """Run module specified at the command-line."""
428 if self.module_to_run:
420 if self.module_to_run:
429 # Make sure that the module gets a proper sys.argv as if it were
421 # Make sure that the module gets a proper sys.argv as if it were
430 # run using `python -m`.
422 # run using `python -m`.
431 save_argv = sys.argv
423 save_argv = sys.argv
432 sys.argv = [sys.executable] + self.extra_args
424 sys.argv = [sys.executable] + self.extra_args
433 try:
425 try:
434 self.shell.safe_run_module(self.module_to_run,
426 self.shell.safe_run_module(self.module_to_run,
435 self.shell.user_ns)
427 self.shell.user_ns)
436 finally:
428 finally:
437 sys.argv = save_argv
429 sys.argv = save_argv
General Comments 0
You need to be logged in to leave comments. Login now