##// END OF EJS Templates
Merge pull request #9483 from Carreau/nopydb...
Thomas Kluyver -
r22362:cfad504c merge
parent child Browse files
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,1266 +1,1265 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 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81 # Globals
81 # Globals
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83
83
84 # Public API
84 # Public API
85 __all__ = ['Completer','IPCompleter']
85 __all__ = ['Completer','IPCompleter']
86
86
87 if sys.platform == 'win32':
87 if sys.platform == 'win32':
88 PROTECTABLES = ' '
88 PROTECTABLES = ' '
89 else:
89 else:
90 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
90 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
91
91
92
92
93 #-----------------------------------------------------------------------------
93 #-----------------------------------------------------------------------------
94 # Main functions and classes
94 # Main functions and classes
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96
96
97 def has_open_quotes(s):
97 def has_open_quotes(s):
98 """Return whether a string has open quotes.
98 """Return whether a string has open quotes.
99
99
100 This simply counts whether the number of quote characters of either type in
100 This simply counts whether the number of quote characters of either type in
101 the string is odd.
101 the string is odd.
102
102
103 Returns
103 Returns
104 -------
104 -------
105 If there is an open quote, the quote character is returned. Else, return
105 If there is an open quote, the quote character is returned. Else, return
106 False.
106 False.
107 """
107 """
108 # We check " first, then ', so complex cases with nested quotes will get
108 # We check " first, then ', so complex cases with nested quotes will get
109 # the " to take precedence.
109 # the " to take precedence.
110 if s.count('"') % 2:
110 if s.count('"') % 2:
111 return '"'
111 return '"'
112 elif s.count("'") % 2:
112 elif s.count("'") % 2:
113 return "'"
113 return "'"
114 else:
114 else:
115 return False
115 return False
116
116
117
117
118 def protect_filename(s):
118 def protect_filename(s):
119 """Escape a string to protect certain characters."""
119 """Escape a string to protect certain characters."""
120
120
121 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
121 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
122 for ch in s])
122 for ch in s])
123
123
124 def expand_user(path):
124 def expand_user(path):
125 """Expand '~'-style usernames in strings.
125 """Expand '~'-style usernames in strings.
126
126
127 This is similar to :func:`os.path.expanduser`, but it computes and returns
127 This is similar to :func:`os.path.expanduser`, but it computes and returns
128 extra information that will be useful if the input was being used in
128 extra information that will be useful if the input was being used in
129 computing completions, and you wish to return the completions with the
129 computing completions, and you wish to return the completions with the
130 original '~' instead of its expanded value.
130 original '~' instead of its expanded value.
131
131
132 Parameters
132 Parameters
133 ----------
133 ----------
134 path : str
134 path : str
135 String to be expanded. If no ~ is present, the output is the same as the
135 String to be expanded. If no ~ is present, the output is the same as the
136 input.
136 input.
137
137
138 Returns
138 Returns
139 -------
139 -------
140 newpath : str
140 newpath : str
141 Result of ~ expansion in the input path.
141 Result of ~ expansion in the input path.
142 tilde_expand : bool
142 tilde_expand : bool
143 Whether any expansion was performed or not.
143 Whether any expansion was performed or not.
144 tilde_val : str
144 tilde_val : str
145 The value that ~ was replaced with.
145 The value that ~ was replaced with.
146 """
146 """
147 # Default values
147 # Default values
148 tilde_expand = False
148 tilde_expand = False
149 tilde_val = ''
149 tilde_val = ''
150 newpath = path
150 newpath = path
151
151
152 if path.startswith('~'):
152 if path.startswith('~'):
153 tilde_expand = True
153 tilde_expand = True
154 rest = len(path)-1
154 rest = len(path)-1
155 newpath = os.path.expanduser(path)
155 newpath = os.path.expanduser(path)
156 if rest:
156 if rest:
157 tilde_val = newpath[:-rest]
157 tilde_val = newpath[:-rest]
158 else:
158 else:
159 tilde_val = newpath
159 tilde_val = newpath
160
160
161 return newpath, tilde_expand, tilde_val
161 return newpath, tilde_expand, tilde_val
162
162
163
163
164 def compress_user(path, tilde_expand, tilde_val):
164 def compress_user(path, tilde_expand, tilde_val):
165 """Does the opposite of expand_user, with its outputs.
165 """Does the opposite of expand_user, with its outputs.
166 """
166 """
167 if tilde_expand:
167 if tilde_expand:
168 return path.replace(tilde_val, '~')
168 return path.replace(tilde_val, '~')
169 else:
169 else:
170 return path
170 return path
171
171
172
172
173 def completions_sorting_key(word):
173 def completions_sorting_key(word):
174 """key for sorting completions
174 """key for sorting completions
175
175
176 This does several things:
176 This does several things:
177
177
178 - Lowercase all completions, so they are sorted alphabetically with
178 - Lowercase all completions, so they are sorted alphabetically with
179 upper and lower case words mingled
179 upper and lower case words mingled
180 - Demote any completions starting with underscores to the end
180 - Demote any completions starting with underscores to the end
181 - Insert any %magic and %%cellmagic completions in the alphabetical order
181 - Insert any %magic and %%cellmagic completions in the alphabetical order
182 by their name
182 by their name
183 """
183 """
184 # Case insensitive sort
184 # Case insensitive sort
185 word = word.lower()
185 word = word.lower()
186
186
187 prio1, prio2 = 0, 0
187 prio1, prio2 = 0, 0
188
188
189 if word.startswith('__'):
189 if word.startswith('__'):
190 prio1 = 2
190 prio1 = 2
191 elif word.startswith('_'):
191 elif word.startswith('_'):
192 prio1 = 1
192 prio1 = 1
193
193
194 if word.endswith('='):
194 if word.endswith('='):
195 prio1 = -1
195 prio1 = -1
196
196
197 if word.startswith('%%'):
197 if word.startswith('%%'):
198 # If there's another % in there, this is something else, so leave it alone
198 # If there's another % in there, this is something else, so leave it alone
199 if not "%" in word[2:]:
199 if not "%" in word[2:]:
200 word = word[2:]
200 word = word[2:]
201 prio2 = 2
201 prio2 = 2
202 elif word.startswith('%'):
202 elif word.startswith('%'):
203 if not "%" in word[1:]:
203 if not "%" in word[1:]:
204 word = word[1:]
204 word = word[1:]
205 prio2 = 1
205 prio2 = 1
206
206
207 return prio1, word, prio2
207 return prio1, word, prio2
208
208
209
209
210 @undoc
210 @undoc
211 class Bunch(object): pass
211 class Bunch(object): pass
212
212
213
213
214 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
214 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
215 GREEDY_DELIMS = ' =\r\n'
215 GREEDY_DELIMS = ' =\r\n'
216
216
217
217
218 class CompletionSplitter(object):
218 class CompletionSplitter(object):
219 """An object to split an input line in a manner similar to readline.
219 """An object to split an input line in a manner similar to readline.
220
220
221 By having our own implementation, we can expose readline-like completion in
221 By having our own implementation, we can expose readline-like completion in
222 a uniform manner to all frontends. This object only needs to be given the
222 a uniform manner to all frontends. This object only needs to be given the
223 line of text to be split and the cursor position on said line, and it
223 line of text to be split and the cursor position on said line, and it
224 returns the 'word' to be completed on at the cursor after splitting the
224 returns the 'word' to be completed on at the cursor after splitting the
225 entire line.
225 entire line.
226
226
227 What characters are used as splitting delimiters can be controlled by
227 What characters are used as splitting delimiters can be controlled by
228 setting the `delims` attribute (this is a property that internally
228 setting the `delims` attribute (this is a property that internally
229 automatically builds the necessary regular expression)"""
229 automatically builds the necessary regular expression)"""
230
230
231 # Private interface
231 # Private interface
232
232
233 # A string of delimiter characters. The default value makes sense for
233 # A string of delimiter characters. The default value makes sense for
234 # IPython's most typical usage patterns.
234 # IPython's most typical usage patterns.
235 _delims = DELIMS
235 _delims = DELIMS
236
236
237 # The expression (a normal string) to be compiled into a regular expression
237 # The expression (a normal string) to be compiled into a regular expression
238 # for actual splitting. We store it as an attribute mostly for ease of
238 # for actual splitting. We store it as an attribute mostly for ease of
239 # debugging, since this type of code can be so tricky to debug.
239 # debugging, since this type of code can be so tricky to debug.
240 _delim_expr = None
240 _delim_expr = None
241
241
242 # The regular expression that does the actual splitting
242 # The regular expression that does the actual splitting
243 _delim_re = None
243 _delim_re = None
244
244
245 def __init__(self, delims=None):
245 def __init__(self, delims=None):
246 delims = CompletionSplitter._delims if delims is None else delims
246 delims = CompletionSplitter._delims if delims is None else delims
247 self.delims = delims
247 self.delims = delims
248
248
249 @property
249 @property
250 def delims(self):
250 def delims(self):
251 """Return the string of delimiter characters."""
251 """Return the string of delimiter characters."""
252 return self._delims
252 return self._delims
253
253
254 @delims.setter
254 @delims.setter
255 def delims(self, delims):
255 def delims(self, delims):
256 """Set the delimiters for line splitting."""
256 """Set the delimiters for line splitting."""
257 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
257 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
258 self._delim_re = re.compile(expr)
258 self._delim_re = re.compile(expr)
259 self._delims = delims
259 self._delims = delims
260 self._delim_expr = expr
260 self._delim_expr = expr
261
261
262 def split_line(self, line, cursor_pos=None):
262 def split_line(self, line, cursor_pos=None):
263 """Split a line of text with a cursor at the given position.
263 """Split a line of text with a cursor at the given position.
264 """
264 """
265 l = line if cursor_pos is None else line[:cursor_pos]
265 l = line if cursor_pos is None else line[:cursor_pos]
266 return self._delim_re.split(l)[-1]
266 return self._delim_re.split(l)[-1]
267
267
268
268
269 class Completer(Configurable):
269 class Completer(Configurable):
270
270
271 greedy = Bool(False,
271 greedy = Bool(False,
272 help="""Activate greedy completion
272 help="""Activate greedy completion
273 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
273 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
274
274
275 This will enable completion on elements of lists, results of function calls, etc.,
275 This will enable completion on elements of lists, results of function calls, etc.,
276 but can be unsafe because the code is actually evaluated on TAB.
276 but can be unsafe because the code is actually evaluated on TAB.
277 """
277 """
278 ).tag(config=True)
278 ).tag(config=True)
279
279
280
280
281 def __init__(self, namespace=None, global_namespace=None, **kwargs):
281 def __init__(self, namespace=None, global_namespace=None, **kwargs):
282 """Create a new completer for the command line.
282 """Create a new completer for the command line.
283
283
284 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
284 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
285
285
286 If unspecified, the default namespace where completions are performed
286 If unspecified, the default namespace where completions are performed
287 is __main__ (technically, __main__.__dict__). Namespaces should be
287 is __main__ (technically, __main__.__dict__). Namespaces should be
288 given as dictionaries.
288 given as dictionaries.
289
289
290 An optional second namespace can be given. This allows the completer
290 An optional second namespace can be given. This allows the completer
291 to handle cases where both the local and global scopes need to be
291 to handle cases where both the local and global scopes need to be
292 distinguished.
292 distinguished.
293
293
294 Completer instances should be used as the completion mechanism of
294 Completer instances should be used as the completion mechanism of
295 readline via the set_completer() call:
295 readline via the set_completer() call:
296
296
297 readline.set_completer(Completer(my_namespace).complete)
297 readline.set_completer(Completer(my_namespace).complete)
298 """
298 """
299
299
300 # Don't bind to namespace quite yet, but flag whether the user wants a
300 # Don't bind to namespace quite yet, but flag whether the user wants a
301 # specific namespace or to use __main__.__dict__. This will allow us
301 # specific namespace or to use __main__.__dict__. This will allow us
302 # to bind to __main__.__dict__ at completion time, not now.
302 # to bind to __main__.__dict__ at completion time, not now.
303 if namespace is None:
303 if namespace is None:
304 self.use_main_ns = 1
304 self.use_main_ns = 1
305 else:
305 else:
306 self.use_main_ns = 0
306 self.use_main_ns = 0
307 self.namespace = namespace
307 self.namespace = namespace
308
308
309 # The global namespace, if given, can be bound directly
309 # The global namespace, if given, can be bound directly
310 if global_namespace is None:
310 if global_namespace is None:
311 self.global_namespace = {}
311 self.global_namespace = {}
312 else:
312 else:
313 self.global_namespace = global_namespace
313 self.global_namespace = global_namespace
314
314
315 super(Completer, self).__init__(**kwargs)
315 super(Completer, self).__init__(**kwargs)
316
316
317 def complete(self, text, state):
317 def complete(self, text, state):
318 """Return the next possible completion for 'text'.
318 """Return the next possible completion for 'text'.
319
319
320 This is called successively with state == 0, 1, 2, ... until it
320 This is called successively with state == 0, 1, 2, ... until it
321 returns None. The completion should begin with 'text'.
321 returns None. The completion should begin with 'text'.
322
322
323 """
323 """
324 if self.use_main_ns:
324 if self.use_main_ns:
325 self.namespace = __main__.__dict__
325 self.namespace = __main__.__dict__
326
326
327 if state == 0:
327 if state == 0:
328 if "." in text:
328 if "." in text:
329 self.matches = self.attr_matches(text)
329 self.matches = self.attr_matches(text)
330 else:
330 else:
331 self.matches = self.global_matches(text)
331 self.matches = self.global_matches(text)
332 try:
332 try:
333 return self.matches[state]
333 return self.matches[state]
334 except IndexError:
334 except IndexError:
335 return None
335 return None
336
336
337 def global_matches(self, text):
337 def global_matches(self, text):
338 """Compute matches when text is a simple name.
338 """Compute matches when text is a simple name.
339
339
340 Return a list of all keywords, built-in functions and names currently
340 Return a list of all keywords, built-in functions and names currently
341 defined in self.namespace or self.global_namespace that match.
341 defined in self.namespace or self.global_namespace that match.
342
342
343 """
343 """
344 matches = []
344 matches = []
345 match_append = matches.append
345 match_append = matches.append
346 n = len(text)
346 n = len(text)
347 for lst in [keyword.kwlist,
347 for lst in [keyword.kwlist,
348 builtin_mod.__dict__.keys(),
348 builtin_mod.__dict__.keys(),
349 self.namespace.keys(),
349 self.namespace.keys(),
350 self.global_namespace.keys()]:
350 self.global_namespace.keys()]:
351 for word in lst:
351 for word in lst:
352 if word[:n] == text and word != "__builtins__":
352 if word[:n] == text and word != "__builtins__":
353 match_append(word)
353 match_append(word)
354 return [cast_unicode_py2(m) for m in matches]
354 return [cast_unicode_py2(m) for m in matches]
355
355
356 def attr_matches(self, text):
356 def attr_matches(self, text):
357 """Compute matches when text contains a dot.
357 """Compute matches when text contains a dot.
358
358
359 Assuming the text is of the form NAME.NAME....[NAME], and is
359 Assuming the text is of the form NAME.NAME....[NAME], and is
360 evaluatable in self.namespace or self.global_namespace, it will be
360 evaluatable in self.namespace or self.global_namespace, it will be
361 evaluated and its attributes (as revealed by dir()) are used as
361 evaluated and its attributes (as revealed by dir()) are used as
362 possible completions. (For class instances, class members are are
362 possible completions. (For class instances, class members are are
363 also considered.)
363 also considered.)
364
364
365 WARNING: this can still invoke arbitrary C code, if an object
365 WARNING: this can still invoke arbitrary C code, if an object
366 with a __getattr__ hook is evaluated.
366 with a __getattr__ hook is evaluated.
367
367
368 """
368 """
369
369
370 # Another option, seems to work great. Catches things like ''.<tab>
370 # Another option, seems to work great. Catches things like ''.<tab>
371 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
371 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
372
372
373 if m:
373 if m:
374 expr, attr = m.group(1, 3)
374 expr, attr = m.group(1, 3)
375 elif self.greedy:
375 elif self.greedy:
376 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
376 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
377 if not m2:
377 if not m2:
378 return []
378 return []
379 expr, attr = m2.group(1,2)
379 expr, attr = m2.group(1,2)
380 else:
380 else:
381 return []
381 return []
382
382
383 try:
383 try:
384 obj = eval(expr, self.namespace)
384 obj = eval(expr, self.namespace)
385 except:
385 except:
386 try:
386 try:
387 obj = eval(expr, self.global_namespace)
387 obj = eval(expr, self.global_namespace)
388 except:
388 except:
389 return []
389 return []
390
390
391 if self.limit_to__all__ and hasattr(obj, '__all__'):
391 if self.limit_to__all__ and hasattr(obj, '__all__'):
392 words = get__all__entries(obj)
392 words = get__all__entries(obj)
393 else:
393 else:
394 words = dir2(obj)
394 words = dir2(obj)
395
395
396 try:
396 try:
397 words = generics.complete_object(obj, words)
397 words = generics.complete_object(obj, words)
398 except TryNext:
398 except TryNext:
399 pass
399 pass
400 except Exception:
400 except Exception:
401 # Silence errors from completion function
401 # Silence errors from completion function
402 #raise # dbg
402 #raise # dbg
403 pass
403 pass
404 # Build match list to return
404 # Build match list to return
405 n = len(attr)
405 n = len(attr)
406 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
406 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
407
407
408
408
409 def get__all__entries(obj):
409 def get__all__entries(obj):
410 """returns the strings in the __all__ attribute"""
410 """returns the strings in the __all__ attribute"""
411 try:
411 try:
412 words = getattr(obj, '__all__')
412 words = getattr(obj, '__all__')
413 except:
413 except:
414 return []
414 return []
415
415
416 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
416 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
417
417
418
418
419 def match_dict_keys(keys, prefix, delims):
419 def match_dict_keys(keys, prefix, delims):
420 """Used by dict_key_matches, matching the prefix to a list of keys"""
420 """Used by dict_key_matches, matching the prefix to a list of keys"""
421 if not prefix:
421 if not prefix:
422 return None, 0, [repr(k) for k in keys
422 return None, 0, [repr(k) for k in keys
423 if isinstance(k, (string_types, bytes))]
423 if isinstance(k, (string_types, bytes))]
424 quote_match = re.search('["\']', prefix)
424 quote_match = re.search('["\']', prefix)
425 quote = quote_match.group()
425 quote = quote_match.group()
426 try:
426 try:
427 prefix_str = eval(prefix + quote, {})
427 prefix_str = eval(prefix + quote, {})
428 except Exception:
428 except Exception:
429 return None, 0, []
429 return None, 0, []
430
430
431 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
431 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
432 token_match = re.search(pattern, prefix, re.UNICODE)
432 token_match = re.search(pattern, prefix, re.UNICODE)
433 token_start = token_match.start()
433 token_start = token_match.start()
434 token_prefix = token_match.group()
434 token_prefix = token_match.group()
435
435
436 # TODO: support bytes in Py3k
436 # TODO: support bytes in Py3k
437 matched = []
437 matched = []
438 for key in keys:
438 for key in keys:
439 try:
439 try:
440 if not key.startswith(prefix_str):
440 if not key.startswith(prefix_str):
441 continue
441 continue
442 except (AttributeError, TypeError, UnicodeError):
442 except (AttributeError, TypeError, UnicodeError):
443 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
443 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
444 continue
444 continue
445
445
446 # reformat remainder of key to begin with prefix
446 # reformat remainder of key to begin with prefix
447 rem = key[len(prefix_str):]
447 rem = key[len(prefix_str):]
448 # force repr wrapped in '
448 # force repr wrapped in '
449 rem_repr = repr(rem + '"')
449 rem_repr = repr(rem + '"')
450 if rem_repr.startswith('u') and prefix[0] not in 'uU':
450 if rem_repr.startswith('u') and prefix[0] not in 'uU':
451 # Found key is unicode, but prefix is Py2 string.
451 # Found key is unicode, but prefix is Py2 string.
452 # Therefore attempt to interpret key as string.
452 # Therefore attempt to interpret key as string.
453 try:
453 try:
454 rem_repr = repr(rem.encode('ascii') + '"')
454 rem_repr = repr(rem.encode('ascii') + '"')
455 except UnicodeEncodeError:
455 except UnicodeEncodeError:
456 continue
456 continue
457
457
458 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
458 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
459 if quote == '"':
459 if quote == '"':
460 # The entered prefix is quoted with ",
460 # The entered prefix is quoted with ",
461 # but the match is quoted with '.
461 # but the match is quoted with '.
462 # A contained " hence needs escaping for comparison:
462 # A contained " hence needs escaping for comparison:
463 rem_repr = rem_repr.replace('"', '\\"')
463 rem_repr = rem_repr.replace('"', '\\"')
464
464
465 # then reinsert prefix from start of token
465 # then reinsert prefix from start of token
466 matched.append('%s%s' % (token_prefix, rem_repr))
466 matched.append('%s%s' % (token_prefix, rem_repr))
467 return quote, token_start, matched
467 return quote, token_start, matched
468
468
469
469
470 def _safe_isinstance(obj, module, class_name):
470 def _safe_isinstance(obj, module, class_name):
471 """Checks if obj is an instance of module.class_name if loaded
471 """Checks if obj is an instance of module.class_name if loaded
472 """
472 """
473 return (module in sys.modules and
473 return (module in sys.modules and
474 isinstance(obj, getattr(__import__(module), class_name)))
474 isinstance(obj, getattr(__import__(module), class_name)))
475
475
476
476
477 def back_unicode_name_matches(text):
477 def back_unicode_name_matches(text):
478 u"""Match unicode characters back to unicode name
478 u"""Match unicode characters back to unicode name
479
479
480 This does ☃ -> \\snowman
480 This does ☃ -> \\snowman
481
481
482 Note that snowman is not a valid python3 combining character but will be expanded.
482 Note that snowman is not a valid python3 combining character but will be expanded.
483 Though it will not recombine back to the snowman character by the completion machinery.
483 Though it will not recombine back to the snowman character by the completion machinery.
484
484
485 This will not either back-complete standard sequences like \\n, \\b ...
485 This will not either back-complete standard sequences like \\n, \\b ...
486
486
487 Used on Python 3 only.
487 Used on Python 3 only.
488 """
488 """
489 if len(text)<2:
489 if len(text)<2:
490 return u'', ()
490 return u'', ()
491 maybe_slash = text[-2]
491 maybe_slash = text[-2]
492 if maybe_slash != '\\':
492 if maybe_slash != '\\':
493 return u'', ()
493 return u'', ()
494
494
495 char = text[-1]
495 char = text[-1]
496 # no expand on quote for completion in strings.
496 # no expand on quote for completion in strings.
497 # nor backcomplete standard ascii keys
497 # nor backcomplete standard ascii keys
498 if char in string.ascii_letters or char in ['"',"'"]:
498 if char in string.ascii_letters or char in ['"',"'"]:
499 return u'', ()
499 return u'', ()
500 try :
500 try :
501 unic = unicodedata.name(char)
501 unic = unicodedata.name(char)
502 return '\\'+char,['\\'+unic]
502 return '\\'+char,['\\'+unic]
503 except KeyError:
503 except KeyError:
504 pass
504 pass
505 return u'', ()
505 return u'', ()
506
506
507 def back_latex_name_matches(text):
507 def back_latex_name_matches(text):
508 u"""Match latex characters back to unicode name
508 u"""Match latex characters back to unicode name
509
509
510 This does ->\\sqrt
510 This does ->\\sqrt
511
511
512 Used on Python 3 only.
512 Used on Python 3 only.
513 """
513 """
514 if len(text)<2:
514 if len(text)<2:
515 return u'', ()
515 return u'', ()
516 maybe_slash = text[-2]
516 maybe_slash = text[-2]
517 if maybe_slash != '\\':
517 if maybe_slash != '\\':
518 return u'', ()
518 return u'', ()
519
519
520
520
521 char = text[-1]
521 char = text[-1]
522 # no expand on quote for completion in strings.
522 # no expand on quote for completion in strings.
523 # nor backcomplete standard ascii keys
523 # nor backcomplete standard ascii keys
524 if char in string.ascii_letters or char in ['"',"'"]:
524 if char in string.ascii_letters or char in ['"',"'"]:
525 return u'', ()
525 return u'', ()
526 try :
526 try :
527 latex = reverse_latex_symbol[char]
527 latex = reverse_latex_symbol[char]
528 # '\\' replace the \ as well
528 # '\\' replace the \ as well
529 return '\\'+char,[latex]
529 return '\\'+char,[latex]
530 except KeyError:
530 except KeyError:
531 pass
531 pass
532 return u'', ()
532 return u'', ()
533
533
534
534
535 class IPCompleter(Completer):
535 class IPCompleter(Completer):
536 """Extension of the completer class with IPython-specific features"""
536 """Extension of the completer class with IPython-specific features"""
537
537
538 @observe('greedy')
538 @observe('greedy')
539 def _greedy_changed(self, change):
539 def _greedy_changed(self, change):
540 """update the splitter and readline delims when greedy is changed"""
540 """update the splitter and readline delims when greedy is changed"""
541 if change['new']:
541 if change['new']:
542 self.splitter.delims = GREEDY_DELIMS
542 self.splitter.delims = GREEDY_DELIMS
543 else:
543 else:
544 self.splitter.delims = DELIMS
544 self.splitter.delims = DELIMS
545
545
546 if self.readline:
546 if self.readline:
547 self.readline.set_completer_delims(self.splitter.delims)
547 self.readline.set_completer_delims(self.splitter.delims)
548
548
549 merge_completions = Bool(True,
549 merge_completions = Bool(True,
550 help="""Whether to merge completion results into a single list
550 help="""Whether to merge completion results into a single list
551
551
552 If False, only the completion results from the first non-empty
552 If False, only the completion results from the first non-empty
553 completer will be returned.
553 completer will be returned.
554 """
554 """
555 ).tag(config=True)
555 ).tag(config=True)
556 omit__names = Enum((0,1,2), default_value=2,
556 omit__names = Enum((0,1,2), default_value=2,
557 help="""Instruct the completer to omit private method names
557 help="""Instruct the completer to omit private method names
558
558
559 Specifically, when completing on ``object.<tab>``.
559 Specifically, when completing on ``object.<tab>``.
560
560
561 When 2 [default]: all names that start with '_' will be excluded.
561 When 2 [default]: all names that start with '_' will be excluded.
562
562
563 When 1: all 'magic' names (``__foo__``) will be excluded.
563 When 1: all 'magic' names (``__foo__``) will be excluded.
564
564
565 When 0: nothing will be excluded.
565 When 0: nothing will be excluded.
566 """
566 """
567 ).tag(config=True)
567 ).tag(config=True)
568 limit_to__all__ = Bool(False,
568 limit_to__all__ = Bool(False,
569 help="""
569 help="""
570 DEPRECATED as of version 5.0.
570 DEPRECATED as of version 5.0.
571
571
572 Instruct the completer to use __all__ for the completion
572 Instruct the completer to use __all__ for the completion
573
573
574 Specifically, when completing on ``object.<tab>``.
574 Specifically, when completing on ``object.<tab>``.
575
575
576 When True: only those names in obj.__all__ will be included.
576 When True: only those names in obj.__all__ will be included.
577
577
578 When False [default]: the __all__ attribute is ignored
578 When False [default]: the __all__ attribute is ignored
579 """,
579 """,
580 ).tag(config=True)
580 ).tag(config=True)
581
581
582 def __init__(self, shell=None, namespace=None, global_namespace=None,
582 def __init__(self, shell=None, namespace=None, global_namespace=None,
583 use_readline=True, config=None, **kwargs):
583 use_readline=True, config=None, **kwargs):
584 """IPCompleter() -> completer
584 """IPCompleter() -> completer
585
585
586 Return a completer object suitable for use by the readline library
586 Return a completer object suitable for use by the readline library
587 via readline.set_completer().
587 via readline.set_completer().
588
588
589 Inputs:
589 Inputs:
590
590
591 - shell: a pointer to the ipython shell itself. This is needed
591 - shell: a pointer to the ipython shell itself. This is needed
592 because this completer knows about magic functions, and those can
592 because this completer knows about magic functions, and those can
593 only be accessed via the ipython instance.
593 only be accessed via the ipython instance.
594
594
595 - namespace: an optional dict where completions are performed.
595 - namespace: an optional dict where completions are performed.
596
596
597 - global_namespace: secondary optional dict for completions, to
597 - global_namespace: secondary optional dict for completions, to
598 handle cases (such as IPython embedded inside functions) where
598 handle cases (such as IPython embedded inside functions) where
599 both Python scopes are visible.
599 both Python scopes are visible.
600
600
601 use_readline : bool, optional
601 use_readline : bool, optional
602 If true, use the readline library. This completer can still function
602 If true, use the readline library. This completer can still function
603 without readline, though in that case callers must provide some extra
603 without readline, though in that case callers must provide some extra
604 information on each call about the current line."""
604 information on each call about the current line."""
605
605
606 self.magic_escape = ESC_MAGIC
606 self.magic_escape = ESC_MAGIC
607 self.splitter = CompletionSplitter()
607 self.splitter = CompletionSplitter()
608
608
609 # Readline configuration, only used by the rlcompleter method.
609 # Readline configuration, only used by the rlcompleter method.
610 if use_readline:
610 if use_readline:
611 # We store the right version of readline so that later code
611 # We store the right version of readline so that later code
612 import IPython.utils.rlineimpl as readline
612 import IPython.utils.rlineimpl as readline
613 self.readline = readline
613 self.readline = readline
614 else:
614 else:
615 self.readline = None
615 self.readline = None
616
616
617 # _greedy_changed() depends on splitter and readline being defined:
617 # _greedy_changed() depends on splitter and readline being defined:
618 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
618 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
619 config=config, **kwargs)
619 config=config, **kwargs)
620
620
621 # List where completion matches will be stored
621 # List where completion matches will be stored
622 self.matches = []
622 self.matches = []
623 self.shell = shell
623 self.shell = shell
624 # Regexp to split filenames with spaces in them
624 # Regexp to split filenames with spaces in them
625 self.space_name_re = re.compile(r'([^\\] )')
625 self.space_name_re = re.compile(r'([^\\] )')
626 # Hold a local ref. to glob.glob for speed
626 # Hold a local ref. to glob.glob for speed
627 self.glob = glob.glob
627 self.glob = glob.glob
628
628
629 # Determine if we are running on 'dumb' terminals, like (X)Emacs
629 # Determine if we are running on 'dumb' terminals, like (X)Emacs
630 # buffers, to avoid completion problems.
630 # buffers, to avoid completion problems.
631 term = os.environ.get('TERM','xterm')
631 term = os.environ.get('TERM','xterm')
632 self.dumb_terminal = term in ['dumb','emacs']
632 self.dumb_terminal = term in ['dumb','emacs']
633
633
634 # Special handling of backslashes needed in win32 platforms
634 # Special handling of backslashes needed in win32 platforms
635 if sys.platform == "win32":
635 if sys.platform == "win32":
636 self.clean_glob = self._clean_glob_win32
636 self.clean_glob = self._clean_glob_win32
637 else:
637 else:
638 self.clean_glob = self._clean_glob
638 self.clean_glob = self._clean_glob
639
639
640 #regexp to parse docstring for function signature
640 #regexp to parse docstring for function signature
641 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
641 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
642 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
642 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
643 #use this if positional argument name is also needed
643 #use this if positional argument name is also needed
644 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
644 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
645
645
646 # All active matcher routines for completion
646 # All active matcher routines for completion
647 self.matchers = [
647 self.matchers = [
648 self.python_matches,
648 self.python_matches,
649 self.file_matches,
649 self.file_matches,
650 self.magic_matches,
650 self.magic_matches,
651 self.python_func_kw_matches,
651 self.python_func_kw_matches,
652 self.dict_key_matches,
652 self.dict_key_matches,
653 ]
653 ]
654
654
655 def all_completions(self, text):
655 def all_completions(self, text):
656 """
656 """
657 Wrapper around the complete method for the benefit of emacs
657 Wrapper around the complete method for the benefit of emacs.
658 and pydb.
659 """
658 """
660 return self.complete(text)[1]
659 return self.complete(text)[1]
661
660
662 def _clean_glob(self, text):
661 def _clean_glob(self, text):
663 return self.glob("%s*" % text)
662 return self.glob("%s*" % text)
664
663
665 def _clean_glob_win32(self,text):
664 def _clean_glob_win32(self,text):
666 return [f.replace("\\","/")
665 return [f.replace("\\","/")
667 for f in self.glob("%s*" % text)]
666 for f in self.glob("%s*" % text)]
668
667
669 def file_matches(self, text):
668 def file_matches(self, text):
670 """Match filenames, expanding ~USER type strings.
669 """Match filenames, expanding ~USER type strings.
671
670
672 Most of the seemingly convoluted logic in this completer is an
671 Most of the seemingly convoluted logic in this completer is an
673 attempt to handle filenames with spaces in them. And yet it's not
672 attempt to handle filenames with spaces in them. And yet it's not
674 quite perfect, because Python's readline doesn't expose all of the
673 quite perfect, because Python's readline doesn't expose all of the
675 GNU readline details needed for this to be done correctly.
674 GNU readline details needed for this to be done correctly.
676
675
677 For a filename with a space in it, the printed completions will be
676 For a filename with a space in it, the printed completions will be
678 only the parts after what's already been typed (instead of the
677 only the parts after what's already been typed (instead of the
679 full completions, as is normally done). I don't think with the
678 full completions, as is normally done). I don't think with the
680 current (as of Python 2.3) Python readline it's possible to do
679 current (as of Python 2.3) Python readline it's possible to do
681 better."""
680 better."""
682
681
683 # chars that require escaping with backslash - i.e. chars
682 # chars that require escaping with backslash - i.e. chars
684 # that readline treats incorrectly as delimiters, but we
683 # that readline treats incorrectly as delimiters, but we
685 # don't want to treat as delimiters in filename matching
684 # don't want to treat as delimiters in filename matching
686 # when escaped with backslash
685 # when escaped with backslash
687 if text.startswith('!'):
686 if text.startswith('!'):
688 text = text[1:]
687 text = text[1:]
689 text_prefix = u'!'
688 text_prefix = u'!'
690 else:
689 else:
691 text_prefix = u''
690 text_prefix = u''
692
691
693 text_until_cursor = self.text_until_cursor
692 text_until_cursor = self.text_until_cursor
694 # track strings with open quotes
693 # track strings with open quotes
695 open_quotes = has_open_quotes(text_until_cursor)
694 open_quotes = has_open_quotes(text_until_cursor)
696
695
697 if '(' in text_until_cursor or '[' in text_until_cursor:
696 if '(' in text_until_cursor or '[' in text_until_cursor:
698 lsplit = text
697 lsplit = text
699 else:
698 else:
700 try:
699 try:
701 # arg_split ~ shlex.split, but with unicode bugs fixed by us
700 # arg_split ~ shlex.split, but with unicode bugs fixed by us
702 lsplit = arg_split(text_until_cursor)[-1]
701 lsplit = arg_split(text_until_cursor)[-1]
703 except ValueError:
702 except ValueError:
704 # typically an unmatched ", or backslash without escaped char.
703 # typically an unmatched ", or backslash without escaped char.
705 if open_quotes:
704 if open_quotes:
706 lsplit = text_until_cursor.split(open_quotes)[-1]
705 lsplit = text_until_cursor.split(open_quotes)[-1]
707 else:
706 else:
708 return []
707 return []
709 except IndexError:
708 except IndexError:
710 # tab pressed on empty line
709 # tab pressed on empty line
711 lsplit = ""
710 lsplit = ""
712
711
713 if not open_quotes and lsplit != protect_filename(lsplit):
712 if not open_quotes and lsplit != protect_filename(lsplit):
714 # if protectables are found, do matching on the whole escaped name
713 # if protectables are found, do matching on the whole escaped name
715 has_protectables = True
714 has_protectables = True
716 text0,text = text,lsplit
715 text0,text = text,lsplit
717 else:
716 else:
718 has_protectables = False
717 has_protectables = False
719 text = os.path.expanduser(text)
718 text = os.path.expanduser(text)
720
719
721 if text == "":
720 if text == "":
722 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
721 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
723
722
724 # Compute the matches from the filesystem
723 # Compute the matches from the filesystem
725 m0 = self.clean_glob(text.replace('\\',''))
724 m0 = self.clean_glob(text.replace('\\',''))
726
725
727 if has_protectables:
726 if has_protectables:
728 # If we had protectables, we need to revert our changes to the
727 # If we had protectables, we need to revert our changes to the
729 # beginning of filename so that we don't double-write the part
728 # beginning of filename so that we don't double-write the part
730 # of the filename we have so far
729 # of the filename we have so far
731 len_lsplit = len(lsplit)
730 len_lsplit = len(lsplit)
732 matches = [text_prefix + text0 +
731 matches = [text_prefix + text0 +
733 protect_filename(f[len_lsplit:]) for f in m0]
732 protect_filename(f[len_lsplit:]) for f in m0]
734 else:
733 else:
735 if open_quotes:
734 if open_quotes:
736 # if we have a string with an open quote, we don't need to
735 # if we have a string with an open quote, we don't need to
737 # protect the names at all (and we _shouldn't_, as it
736 # protect the names at all (and we _shouldn't_, as it
738 # would cause bugs when the filesystem call is made).
737 # would cause bugs when the filesystem call is made).
739 matches = m0
738 matches = m0
740 else:
739 else:
741 matches = [text_prefix +
740 matches = [text_prefix +
742 protect_filename(f) for f in m0]
741 protect_filename(f) for f in m0]
743
742
744 # Mark directories in input list by appending '/' to their names.
743 # Mark directories in input list by appending '/' to their names.
745 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
744 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
746
745
747 def magic_matches(self, text):
746 def magic_matches(self, text):
748 """Match magics"""
747 """Match magics"""
749 # Get all shell magics now rather than statically, so magics loaded at
748 # Get all shell magics now rather than statically, so magics loaded at
750 # runtime show up too.
749 # runtime show up too.
751 lsm = self.shell.magics_manager.lsmagic()
750 lsm = self.shell.magics_manager.lsmagic()
752 line_magics = lsm['line']
751 line_magics = lsm['line']
753 cell_magics = lsm['cell']
752 cell_magics = lsm['cell']
754 pre = self.magic_escape
753 pre = self.magic_escape
755 pre2 = pre+pre
754 pre2 = pre+pre
756
755
757 # Completion logic:
756 # Completion logic:
758 # - user gives %%: only do cell magics
757 # - user gives %%: only do cell magics
759 # - user gives %: do both line and cell magics
758 # - user gives %: do both line and cell magics
760 # - no prefix: do both
759 # - no prefix: do both
761 # In other words, line magics are skipped if the user gives %% explicitly
760 # In other words, line magics are skipped if the user gives %% explicitly
762 bare_text = text.lstrip(pre)
761 bare_text = text.lstrip(pre)
763 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
762 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
764 if not text.startswith(pre2):
763 if not text.startswith(pre2):
765 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
764 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
766 return [cast_unicode_py2(c) for c in comp]
765 return [cast_unicode_py2(c) for c in comp]
767
766
768
767
769 def python_matches(self, text):
768 def python_matches(self, text):
770 """Match attributes or global python names"""
769 """Match attributes or global python names"""
771 if "." in text:
770 if "." in text:
772 try:
771 try:
773 matches = self.attr_matches(text)
772 matches = self.attr_matches(text)
774 if text.endswith('.') and self.omit__names:
773 if text.endswith('.') and self.omit__names:
775 if self.omit__names == 1:
774 if self.omit__names == 1:
776 # true if txt is _not_ a __ name, false otherwise:
775 # true if txt is _not_ a __ name, false otherwise:
777 no__name = (lambda txt:
776 no__name = (lambda txt:
778 re.match(r'.*\.__.*?__',txt) is None)
777 re.match(r'.*\.__.*?__',txt) is None)
779 else:
778 else:
780 # true if txt is _not_ a _ name, false otherwise:
779 # true if txt is _not_ a _ name, false otherwise:
781 no__name = (lambda txt:
780 no__name = (lambda txt:
782 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
781 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
783 matches = filter(no__name, matches)
782 matches = filter(no__name, matches)
784 except NameError:
783 except NameError:
785 # catches <undefined attributes>.<tab>
784 # catches <undefined attributes>.<tab>
786 matches = []
785 matches = []
787 else:
786 else:
788 matches = self.global_matches(text)
787 matches = self.global_matches(text)
789 return matches
788 return matches
790
789
791 def _default_arguments_from_docstring(self, doc):
790 def _default_arguments_from_docstring(self, doc):
792 """Parse the first line of docstring for call signature.
791 """Parse the first line of docstring for call signature.
793
792
794 Docstring should be of the form 'min(iterable[, key=func])\n'.
793 Docstring should be of the form 'min(iterable[, key=func])\n'.
795 It can also parse cython docstring of the form
794 It can also parse cython docstring of the form
796 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
795 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
797 """
796 """
798 if doc is None:
797 if doc is None:
799 return []
798 return []
800
799
801 #care only the firstline
800 #care only the firstline
802 line = doc.lstrip().splitlines()[0]
801 line = doc.lstrip().splitlines()[0]
803
802
804 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
803 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
805 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
804 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
806 sig = self.docstring_sig_re.search(line)
805 sig = self.docstring_sig_re.search(line)
807 if sig is None:
806 if sig is None:
808 return []
807 return []
809 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
808 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
810 sig = sig.groups()[0].split(',')
809 sig = sig.groups()[0].split(',')
811 ret = []
810 ret = []
812 for s in sig:
811 for s in sig:
813 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
812 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
814 ret += self.docstring_kwd_re.findall(s)
813 ret += self.docstring_kwd_re.findall(s)
815 return ret
814 return ret
816
815
817 def _default_arguments(self, obj):
816 def _default_arguments(self, obj):
818 """Return the list of default arguments of obj if it is callable,
817 """Return the list of default arguments of obj if it is callable,
819 or empty list otherwise."""
818 or empty list otherwise."""
820 call_obj = obj
819 call_obj = obj
821 ret = []
820 ret = []
822 if inspect.isbuiltin(obj):
821 if inspect.isbuiltin(obj):
823 pass
822 pass
824 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
823 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
825 if inspect.isclass(obj):
824 if inspect.isclass(obj):
826 #for cython embededsignature=True the constructor docstring
825 #for cython embededsignature=True the constructor docstring
827 #belongs to the object itself not __init__
826 #belongs to the object itself not __init__
828 ret += self._default_arguments_from_docstring(
827 ret += self._default_arguments_from_docstring(
829 getattr(obj, '__doc__', ''))
828 getattr(obj, '__doc__', ''))
830 # for classes, check for __init__,__new__
829 # for classes, check for __init__,__new__
831 call_obj = (getattr(obj, '__init__', None) or
830 call_obj = (getattr(obj, '__init__', None) or
832 getattr(obj, '__new__', None))
831 getattr(obj, '__new__', None))
833 # for all others, check if they are __call__able
832 # for all others, check if they are __call__able
834 elif hasattr(obj, '__call__'):
833 elif hasattr(obj, '__call__'):
835 call_obj = obj.__call__
834 call_obj = obj.__call__
836 ret += self._default_arguments_from_docstring(
835 ret += self._default_arguments_from_docstring(
837 getattr(call_obj, '__doc__', ''))
836 getattr(call_obj, '__doc__', ''))
838
837
839 if PY3:
838 if PY3:
840 _keeps = (inspect.Parameter.KEYWORD_ONLY,
839 _keeps = (inspect.Parameter.KEYWORD_ONLY,
841 inspect.Parameter.POSITIONAL_OR_KEYWORD)
840 inspect.Parameter.POSITIONAL_OR_KEYWORD)
842 signature = inspect.signature
841 signature = inspect.signature
843 else:
842 else:
844 import IPython.utils.signatures
843 import IPython.utils.signatures
845 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
844 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
846 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
845 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
847 signature = IPython.utils.signatures.signature
846 signature = IPython.utils.signatures.signature
848
847
849 try:
848 try:
850 sig = signature(call_obj)
849 sig = signature(call_obj)
851 ret.extend(k for k, v in sig.parameters.items() if
850 ret.extend(k for k, v in sig.parameters.items() if
852 v.kind in _keeps)
851 v.kind in _keeps)
853 except ValueError:
852 except ValueError:
854 pass
853 pass
855
854
856 return list(set(ret))
855 return list(set(ret))
857
856
858 def python_func_kw_matches(self,text):
857 def python_func_kw_matches(self,text):
859 """Match named parameters (kwargs) of the last open function"""
858 """Match named parameters (kwargs) of the last open function"""
860
859
861 if "." in text: # a parameter cannot be dotted
860 if "." in text: # a parameter cannot be dotted
862 return []
861 return []
863 try: regexp = self.__funcParamsRegex
862 try: regexp = self.__funcParamsRegex
864 except AttributeError:
863 except AttributeError:
865 regexp = self.__funcParamsRegex = re.compile(r'''
864 regexp = self.__funcParamsRegex = re.compile(r'''
866 '.*?(?<!\\)' | # single quoted strings or
865 '.*?(?<!\\)' | # single quoted strings or
867 ".*?(?<!\\)" | # double quoted strings or
866 ".*?(?<!\\)" | # double quoted strings or
868 \w+ | # identifier
867 \w+ | # identifier
869 \S # other characters
868 \S # other characters
870 ''', re.VERBOSE | re.DOTALL)
869 ''', re.VERBOSE | re.DOTALL)
871 # 1. find the nearest identifier that comes before an unclosed
870 # 1. find the nearest identifier that comes before an unclosed
872 # parenthesis before the cursor
871 # parenthesis before the cursor
873 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
872 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
874 tokens = regexp.findall(self.text_until_cursor)
873 tokens = regexp.findall(self.text_until_cursor)
875 tokens.reverse()
874 tokens.reverse()
876 iterTokens = iter(tokens); openPar = 0
875 iterTokens = iter(tokens); openPar = 0
877
876
878 for token in iterTokens:
877 for token in iterTokens:
879 if token == ')':
878 if token == ')':
880 openPar -= 1
879 openPar -= 1
881 elif token == '(':
880 elif token == '(':
882 openPar += 1
881 openPar += 1
883 if openPar > 0:
882 if openPar > 0:
884 # found the last unclosed parenthesis
883 # found the last unclosed parenthesis
885 break
884 break
886 else:
885 else:
887 return []
886 return []
888 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
887 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
889 ids = []
888 ids = []
890 isId = re.compile(r'\w+$').match
889 isId = re.compile(r'\w+$').match
891
890
892 while True:
891 while True:
893 try:
892 try:
894 ids.append(next(iterTokens))
893 ids.append(next(iterTokens))
895 if not isId(ids[-1]):
894 if not isId(ids[-1]):
896 ids.pop(); break
895 ids.pop(); break
897 if not next(iterTokens) == '.':
896 if not next(iterTokens) == '.':
898 break
897 break
899 except StopIteration:
898 except StopIteration:
900 break
899 break
901 # lookup the candidate callable matches either using global_matches
900 # lookup the candidate callable matches either using global_matches
902 # or attr_matches for dotted names
901 # or attr_matches for dotted names
903 if len(ids) == 1:
902 if len(ids) == 1:
904 callableMatches = self.global_matches(ids[0])
903 callableMatches = self.global_matches(ids[0])
905 else:
904 else:
906 callableMatches = self.attr_matches('.'.join(ids[::-1]))
905 callableMatches = self.attr_matches('.'.join(ids[::-1]))
907 argMatches = []
906 argMatches = []
908 for callableMatch in callableMatches:
907 for callableMatch in callableMatches:
909 try:
908 try:
910 namedArgs = self._default_arguments(eval(callableMatch,
909 namedArgs = self._default_arguments(eval(callableMatch,
911 self.namespace))
910 self.namespace))
912 except:
911 except:
913 continue
912 continue
914
913
915 for namedArg in namedArgs:
914 for namedArg in namedArgs:
916 if namedArg.startswith(text):
915 if namedArg.startswith(text):
917 argMatches.append(u"%s=" %namedArg)
916 argMatches.append(u"%s=" %namedArg)
918 return argMatches
917 return argMatches
919
918
920 def dict_key_matches(self, text):
919 def dict_key_matches(self, text):
921 "Match string keys in a dictionary, after e.g. 'foo[' "
920 "Match string keys in a dictionary, after e.g. 'foo[' "
922 def get_keys(obj):
921 def get_keys(obj):
923 # Objects can define their own completions by defining an
922 # Objects can define their own completions by defining an
924 # _ipy_key_completions_() method.
923 # _ipy_key_completions_() method.
925 method = get_real_method(obj, '_ipython_key_completions_')
924 method = get_real_method(obj, '_ipython_key_completions_')
926 if method is not None:
925 if method is not None:
927 return method()
926 return method()
928
927
929 # Special case some common in-memory dict-like types
928 # Special case some common in-memory dict-like types
930 if isinstance(obj, dict) or\
929 if isinstance(obj, dict) or\
931 _safe_isinstance(obj, 'pandas', 'DataFrame'):
930 _safe_isinstance(obj, 'pandas', 'DataFrame'):
932 try:
931 try:
933 return list(obj.keys())
932 return list(obj.keys())
934 except Exception:
933 except Exception:
935 return []
934 return []
936 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
935 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
937 _safe_isinstance(obj, 'numpy', 'void'):
936 _safe_isinstance(obj, 'numpy', 'void'):
938 return obj.dtype.names or []
937 return obj.dtype.names or []
939 return []
938 return []
940
939
941 try:
940 try:
942 regexps = self.__dict_key_regexps
941 regexps = self.__dict_key_regexps
943 except AttributeError:
942 except AttributeError:
944 dict_key_re_fmt = r'''(?x)
943 dict_key_re_fmt = r'''(?x)
945 ( # match dict-referring expression wrt greedy setting
944 ( # match dict-referring expression wrt greedy setting
946 %s
945 %s
947 )
946 )
948 \[ # open bracket
947 \[ # open bracket
949 \s* # and optional whitespace
948 \s* # and optional whitespace
950 ([uUbB]? # string prefix (r not handled)
949 ([uUbB]? # string prefix (r not handled)
951 (?: # unclosed string
950 (?: # unclosed string
952 '(?:[^']|(?<!\\)\\')*
951 '(?:[^']|(?<!\\)\\')*
953 |
952 |
954 "(?:[^"]|(?<!\\)\\")*
953 "(?:[^"]|(?<!\\)\\")*
955 )
954 )
956 )?
955 )?
957 $
956 $
958 '''
957 '''
959 regexps = self.__dict_key_regexps = {
958 regexps = self.__dict_key_regexps = {
960 False: re.compile(dict_key_re_fmt % '''
959 False: re.compile(dict_key_re_fmt % '''
961 # identifiers separated by .
960 # identifiers separated by .
962 (?!\d)\w+
961 (?!\d)\w+
963 (?:\.(?!\d)\w+)*
962 (?:\.(?!\d)\w+)*
964 '''),
963 '''),
965 True: re.compile(dict_key_re_fmt % '''
964 True: re.compile(dict_key_re_fmt % '''
966 .+
965 .+
967 ''')
966 ''')
968 }
967 }
969
968
970 match = regexps[self.greedy].search(self.text_until_cursor)
969 match = regexps[self.greedy].search(self.text_until_cursor)
971 if match is None:
970 if match is None:
972 return []
971 return []
973
972
974 expr, prefix = match.groups()
973 expr, prefix = match.groups()
975 try:
974 try:
976 obj = eval(expr, self.namespace)
975 obj = eval(expr, self.namespace)
977 except Exception:
976 except Exception:
978 try:
977 try:
979 obj = eval(expr, self.global_namespace)
978 obj = eval(expr, self.global_namespace)
980 except Exception:
979 except Exception:
981 return []
980 return []
982
981
983 keys = get_keys(obj)
982 keys = get_keys(obj)
984 if not keys:
983 if not keys:
985 return keys
984 return keys
986 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
985 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
987 if not matches:
986 if not matches:
988 return matches
987 return matches
989
988
990 # get the cursor position of
989 # get the cursor position of
991 # - the text being completed
990 # - the text being completed
992 # - the start of the key text
991 # - the start of the key text
993 # - the start of the completion
992 # - the start of the completion
994 text_start = len(self.text_until_cursor) - len(text)
993 text_start = len(self.text_until_cursor) - len(text)
995 if prefix:
994 if prefix:
996 key_start = match.start(2)
995 key_start = match.start(2)
997 completion_start = key_start + token_offset
996 completion_start = key_start + token_offset
998 else:
997 else:
999 key_start = completion_start = match.end()
998 key_start = completion_start = match.end()
1000
999
1001 # grab the leading prefix, to make sure all completions start with `text`
1000 # grab the leading prefix, to make sure all completions start with `text`
1002 if text_start > key_start:
1001 if text_start > key_start:
1003 leading = ''
1002 leading = ''
1004 else:
1003 else:
1005 leading = text[text_start:completion_start]
1004 leading = text[text_start:completion_start]
1006
1005
1007 # the index of the `[` character
1006 # the index of the `[` character
1008 bracket_idx = match.end(1)
1007 bracket_idx = match.end(1)
1009
1008
1010 # append closing quote and bracket as appropriate
1009 # append closing quote and bracket as appropriate
1011 # this is *not* appropriate if the opening quote or bracket is outside
1010 # this is *not* appropriate if the opening quote or bracket is outside
1012 # the text given to this method
1011 # the text given to this method
1013 suf = ''
1012 suf = ''
1014 continuation = self.line_buffer[len(self.text_until_cursor):]
1013 continuation = self.line_buffer[len(self.text_until_cursor):]
1015 if key_start > text_start and closing_quote:
1014 if key_start > text_start and closing_quote:
1016 # quotes were opened inside text, maybe close them
1015 # quotes were opened inside text, maybe close them
1017 if continuation.startswith(closing_quote):
1016 if continuation.startswith(closing_quote):
1018 continuation = continuation[len(closing_quote):]
1017 continuation = continuation[len(closing_quote):]
1019 else:
1018 else:
1020 suf += closing_quote
1019 suf += closing_quote
1021 if bracket_idx > text_start:
1020 if bracket_idx > text_start:
1022 # brackets were opened inside text, maybe close them
1021 # brackets were opened inside text, maybe close them
1023 if not continuation.startswith(']'):
1022 if not continuation.startswith(']'):
1024 suf += ']'
1023 suf += ']'
1025
1024
1026 return [leading + k + suf for k in matches]
1025 return [leading + k + suf for k in matches]
1027
1026
1028 def unicode_name_matches(self, text):
1027 def unicode_name_matches(self, text):
1029 u"""Match Latex-like syntax for unicode characters base
1028 u"""Match Latex-like syntax for unicode characters base
1030 on the name of the character.
1029 on the name of the character.
1031
1030
1032 This does \\GREEK SMALL LETTER ETA -> η
1031 This does \\GREEK SMALL LETTER ETA -> η
1033
1032
1034 Works only on valid python 3 identifier, or on combining characters that
1033 Works only on valid python 3 identifier, or on combining characters that
1035 will combine to form a valid identifier.
1034 will combine to form a valid identifier.
1036
1035
1037 Used on Python 3 only.
1036 Used on Python 3 only.
1038 """
1037 """
1039 slashpos = text.rfind('\\')
1038 slashpos = text.rfind('\\')
1040 if slashpos > -1:
1039 if slashpos > -1:
1041 s = text[slashpos+1:]
1040 s = text[slashpos+1:]
1042 try :
1041 try :
1043 unic = unicodedata.lookup(s)
1042 unic = unicodedata.lookup(s)
1044 # allow combining chars
1043 # allow combining chars
1045 if ('a'+unic).isidentifier():
1044 if ('a'+unic).isidentifier():
1046 return '\\'+s,[unic]
1045 return '\\'+s,[unic]
1047 except KeyError:
1046 except KeyError:
1048 pass
1047 pass
1049 return u'', []
1048 return u'', []
1050
1049
1051
1050
1052
1051
1053
1052
1054 def latex_matches(self, text):
1053 def latex_matches(self, text):
1055 u"""Match Latex syntax for unicode characters.
1054 u"""Match Latex syntax for unicode characters.
1056
1055
1057 This does both \\alp -> \\alpha and \\alpha -> α
1056 This does both \\alp -> \\alpha and \\alpha -> α
1058
1057
1059 Used on Python 3 only.
1058 Used on Python 3 only.
1060 """
1059 """
1061 slashpos = text.rfind('\\')
1060 slashpos = text.rfind('\\')
1062 if slashpos > -1:
1061 if slashpos > -1:
1063 s = text[slashpos:]
1062 s = text[slashpos:]
1064 if s in latex_symbols:
1063 if s in latex_symbols:
1065 # Try to complete a full latex symbol to unicode
1064 # Try to complete a full latex symbol to unicode
1066 # \\alpha -> α
1065 # \\alpha -> α
1067 return s, [latex_symbols[s]]
1066 return s, [latex_symbols[s]]
1068 else:
1067 else:
1069 # If a user has partially typed a latex symbol, give them
1068 # If a user has partially typed a latex symbol, give them
1070 # a full list of options \al -> [\aleph, \alpha]
1069 # a full list of options \al -> [\aleph, \alpha]
1071 matches = [k for k in latex_symbols if k.startswith(s)]
1070 matches = [k for k in latex_symbols if k.startswith(s)]
1072 return s, matches
1071 return s, matches
1073 return u'', []
1072 return u'', []
1074
1073
1075 def dispatch_custom_completer(self, text):
1074 def dispatch_custom_completer(self, text):
1076 line = self.line_buffer
1075 line = self.line_buffer
1077 if not line.strip():
1076 if not line.strip():
1078 return None
1077 return None
1079
1078
1080 # Create a little structure to pass all the relevant information about
1079 # Create a little structure to pass all the relevant information about
1081 # the current completion to any custom completer.
1080 # the current completion to any custom completer.
1082 event = Bunch()
1081 event = Bunch()
1083 event.line = line
1082 event.line = line
1084 event.symbol = text
1083 event.symbol = text
1085 cmd = line.split(None,1)[0]
1084 cmd = line.split(None,1)[0]
1086 event.command = cmd
1085 event.command = cmd
1087 event.text_until_cursor = self.text_until_cursor
1086 event.text_until_cursor = self.text_until_cursor
1088
1087
1089 # for foo etc, try also to find completer for %foo
1088 # for foo etc, try also to find completer for %foo
1090 if not cmd.startswith(self.magic_escape):
1089 if not cmd.startswith(self.magic_escape):
1091 try_magic = self.custom_completers.s_matches(
1090 try_magic = self.custom_completers.s_matches(
1092 self.magic_escape + cmd)
1091 self.magic_escape + cmd)
1093 else:
1092 else:
1094 try_magic = []
1093 try_magic = []
1095
1094
1096 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1095 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1097 try_magic,
1096 try_magic,
1098 self.custom_completers.flat_matches(self.text_until_cursor)):
1097 self.custom_completers.flat_matches(self.text_until_cursor)):
1099 try:
1098 try:
1100 res = c(event)
1099 res = c(event)
1101 if res:
1100 if res:
1102 # first, try case sensitive match
1101 # first, try case sensitive match
1103 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1102 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1104 if withcase:
1103 if withcase:
1105 return withcase
1104 return withcase
1106 # if none, then case insensitive ones are ok too
1105 # if none, then case insensitive ones are ok too
1107 text_low = text.lower()
1106 text_low = text.lower()
1108 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1107 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1109 except TryNext:
1108 except TryNext:
1110 pass
1109 pass
1111
1110
1112 return None
1111 return None
1113
1112
1114 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1113 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1115 """Find completions for the given text and line context.
1114 """Find completions for the given text and line context.
1116
1115
1117 Note that both the text and the line_buffer are optional, but at least
1116 Note that both the text and the line_buffer are optional, but at least
1118 one of them must be given.
1117 one of them must be given.
1119
1118
1120 Parameters
1119 Parameters
1121 ----------
1120 ----------
1122 text : string, optional
1121 text : string, optional
1123 Text to perform the completion on. If not given, the line buffer
1122 Text to perform the completion on. If not given, the line buffer
1124 is split using the instance's CompletionSplitter object.
1123 is split using the instance's CompletionSplitter object.
1125
1124
1126 line_buffer : string, optional
1125 line_buffer : string, optional
1127 If not given, the completer attempts to obtain the current line
1126 If not given, the completer attempts to obtain the current line
1128 buffer via readline. This keyword allows clients which are
1127 buffer via readline. This keyword allows clients which are
1129 requesting for text completions in non-readline contexts to inform
1128 requesting for text completions in non-readline contexts to inform
1130 the completer of the entire text.
1129 the completer of the entire text.
1131
1130
1132 cursor_pos : int, optional
1131 cursor_pos : int, optional
1133 Index of the cursor in the full line buffer. Should be provided by
1132 Index of the cursor in the full line buffer. Should be provided by
1134 remote frontends where kernel has no access to frontend state.
1133 remote frontends where kernel has no access to frontend state.
1135
1134
1136 Returns
1135 Returns
1137 -------
1136 -------
1138 text : str
1137 text : str
1139 Text that was actually used in the completion.
1138 Text that was actually used in the completion.
1140
1139
1141 matches : list
1140 matches : list
1142 A list of completion matches.
1141 A list of completion matches.
1143 """
1142 """
1144 # if the cursor position isn't given, the only sane assumption we can
1143 # if the cursor position isn't given, the only sane assumption we can
1145 # make is that it's at the end of the line (the common case)
1144 # make is that it's at the end of the line (the common case)
1146 if cursor_pos is None:
1145 if cursor_pos is None:
1147 cursor_pos = len(line_buffer) if text is None else len(text)
1146 cursor_pos = len(line_buffer) if text is None else len(text)
1148
1147
1149 if PY3:
1148 if PY3:
1150
1149
1151 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1150 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1152 latex_text, latex_matches = self.latex_matches(base_text)
1151 latex_text, latex_matches = self.latex_matches(base_text)
1153 if latex_matches:
1152 if latex_matches:
1154 return latex_text, latex_matches
1153 return latex_text, latex_matches
1155 name_text = ''
1154 name_text = ''
1156 name_matches = []
1155 name_matches = []
1157 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1156 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1158 name_text, name_matches = meth(base_text)
1157 name_text, name_matches = meth(base_text)
1159 if name_text:
1158 if name_text:
1160 return name_text, name_matches
1159 return name_text, name_matches
1161
1160
1162 # if text is either None or an empty string, rely on the line buffer
1161 # if text is either None or an empty string, rely on the line buffer
1163 if not text:
1162 if not text:
1164 text = self.splitter.split_line(line_buffer, cursor_pos)
1163 text = self.splitter.split_line(line_buffer, cursor_pos)
1165
1164
1166 # If no line buffer is given, assume the input text is all there was
1165 # If no line buffer is given, assume the input text is all there was
1167 if line_buffer is None:
1166 if line_buffer is None:
1168 line_buffer = text
1167 line_buffer = text
1169
1168
1170 self.line_buffer = line_buffer
1169 self.line_buffer = line_buffer
1171 self.text_until_cursor = self.line_buffer[:cursor_pos]
1170 self.text_until_cursor = self.line_buffer[:cursor_pos]
1172
1171
1173 # Start with a clean slate of completions
1172 # Start with a clean slate of completions
1174 self.matches[:] = []
1173 self.matches[:] = []
1175 custom_res = self.dispatch_custom_completer(text)
1174 custom_res = self.dispatch_custom_completer(text)
1176 if custom_res is not None:
1175 if custom_res is not None:
1177 # did custom completers produce something?
1176 # did custom completers produce something?
1178 self.matches = custom_res
1177 self.matches = custom_res
1179 else:
1178 else:
1180 # Extend the list of completions with the results of each
1179 # Extend the list of completions with the results of each
1181 # matcher, so we return results to the user from all
1180 # matcher, so we return results to the user from all
1182 # namespaces.
1181 # namespaces.
1183 if self.merge_completions:
1182 if self.merge_completions:
1184 self.matches = []
1183 self.matches = []
1185 for matcher in self.matchers:
1184 for matcher in self.matchers:
1186 try:
1185 try:
1187 self.matches.extend(matcher(text))
1186 self.matches.extend(matcher(text))
1188 except:
1187 except:
1189 # Show the ugly traceback if the matcher causes an
1188 # Show the ugly traceback if the matcher causes an
1190 # exception, but do NOT crash the kernel!
1189 # exception, but do NOT crash the kernel!
1191 sys.excepthook(*sys.exc_info())
1190 sys.excepthook(*sys.exc_info())
1192 else:
1191 else:
1193 for matcher in self.matchers:
1192 for matcher in self.matchers:
1194 self.matches = matcher(text)
1193 self.matches = matcher(text)
1195 if self.matches:
1194 if self.matches:
1196 break
1195 break
1197 # FIXME: we should extend our api to return a dict with completions for
1196 # FIXME: we should extend our api to return a dict with completions for
1198 # different types of objects. The rlcomplete() method could then
1197 # different types of objects. The rlcomplete() method could then
1199 # simply collapse the dict into a list for readline, but we'd have
1198 # simply collapse the dict into a list for readline, but we'd have
1200 # richer completion semantics in other evironments.
1199 # richer completion semantics in other evironments.
1201 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1200 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1202
1201
1203 return text, self.matches
1202 return text, self.matches
1204
1203
1205 def rlcomplete(self, text, state):
1204 def rlcomplete(self, text, state):
1206 """Return the state-th possible completion for 'text'.
1205 """Return the state-th possible completion for 'text'.
1207
1206
1208 This is called successively with state == 0, 1, 2, ... until it
1207 This is called successively with state == 0, 1, 2, ... until it
1209 returns None. The completion should begin with 'text'.
1208 returns None. The completion should begin with 'text'.
1210
1209
1211 Parameters
1210 Parameters
1212 ----------
1211 ----------
1213 text : string
1212 text : string
1214 Text to perform the completion on.
1213 Text to perform the completion on.
1215
1214
1216 state : int
1215 state : int
1217 Counter used by readline.
1216 Counter used by readline.
1218 """
1217 """
1219 if state==0:
1218 if state==0:
1220
1219
1221 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1220 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1222 cursor_pos = self.readline.get_endidx()
1221 cursor_pos = self.readline.get_endidx()
1223
1222
1224 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1223 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1225 # (text, line_buffer, cursor_pos) ) # dbg
1224 # (text, line_buffer, cursor_pos) ) # dbg
1226
1225
1227 # if there is only a tab on a line with only whitespace, instead of
1226 # if there is only a tab on a line with only whitespace, instead of
1228 # the mostly useless 'do you want to see all million completions'
1227 # the mostly useless 'do you want to see all million completions'
1229 # message, just do the right thing and give the user his tab!
1228 # message, just do the right thing and give the user his tab!
1230 # Incidentally, this enables pasting of tabbed text from an editor
1229 # Incidentally, this enables pasting of tabbed text from an editor
1231 # (as long as autoindent is off).
1230 # (as long as autoindent is off).
1232
1231
1233 # It should be noted that at least pyreadline still shows file
1232 # It should be noted that at least pyreadline still shows file
1234 # completions - is there a way around it?
1233 # completions - is there a way around it?
1235
1234
1236 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1235 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1237 # we don't interfere with their own tab-completion mechanism.
1236 # we don't interfere with their own tab-completion mechanism.
1238 if not (self.dumb_terminal or line_buffer.strip()):
1237 if not (self.dumb_terminal or line_buffer.strip()):
1239 self.readline.insert_text('\t')
1238 self.readline.insert_text('\t')
1240 sys.stdout.flush()
1239 sys.stdout.flush()
1241 return None
1240 return None
1242
1241
1243 # Note: debugging exceptions that may occur in completion is very
1242 # Note: debugging exceptions that may occur in completion is very
1244 # tricky, because readline unconditionally silences them. So if
1243 # tricky, because readline unconditionally silences them. So if
1245 # during development you suspect a bug in the completion code, turn
1244 # during development you suspect a bug in the completion code, turn
1246 # this flag on temporarily by uncommenting the second form (don't
1245 # this flag on temporarily by uncommenting the second form (don't
1247 # flip the value in the first line, as the '# dbg' marker can be
1246 # flip the value in the first line, as the '# dbg' marker can be
1248 # automatically detected and is used elsewhere).
1247 # automatically detected and is used elsewhere).
1249 DEBUG = False
1248 DEBUG = False
1250 #DEBUG = True # dbg
1249 #DEBUG = True # dbg
1251 if DEBUG:
1250 if DEBUG:
1252 try:
1251 try:
1253 self.complete(text, line_buffer, cursor_pos)
1252 self.complete(text, line_buffer, cursor_pos)
1254 except:
1253 except:
1255 import traceback; traceback.print_exc()
1254 import traceback; traceback.print_exc()
1256 else:
1255 else:
1257 # The normal production version is here
1256 # The normal production version is here
1258
1257
1259 # This method computes the self.matches array
1258 # This method computes the self.matches array
1260 self.complete(text, line_buffer, cursor_pos)
1259 self.complete(text, line_buffer, cursor_pos)
1261
1260
1262 try:
1261 try:
1263 return self.matches[state]
1262 return self.matches[state]
1264 except IndexError:
1263 except IndexError:
1265 return None
1264 return None
1266
1265
@@ -1,648 +1,602 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, object):
194 class Pdb(OldPdb, object):
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 parseline(self, line):
274 def parseline(self, line):
315 if line.startswith("!!"):
275 if line.startswith("!!"):
316 # Force standard behavior.
276 # Force standard behavior.
317 return super(Pdb, self).parseline(line[2:])
277 return super(Pdb, self).parseline(line[2:])
318 # "Smart command mode" from pdb++: don't execute commands if a variable
278 # "Smart command mode" from pdb++: don't execute commands if a variable
319 # with the same name exists.
279 # with the same name exists.
320 cmd, arg, newline = super(Pdb, self).parseline(line)
280 cmd, arg, newline = super(Pdb, self).parseline(line)
321 if cmd in self.curframe.f_globals or cmd in self.curframe.f_locals:
281 if cmd in self.curframe.f_globals or cmd in self.curframe.f_locals:
322 return super(Pdb, self).parseline("!" + line)
282 return super(Pdb, self).parseline("!" + line)
323 return super(Pdb, self).parseline(line)
283 return super(Pdb, self).parseline(line)
324
284
325 def new_do_up(self, arg):
285 def new_do_up(self, arg):
326 OldPdb.do_up(self, arg)
286 OldPdb.do_up(self, arg)
327 self.shell.set_completer_frame(self.curframe)
287 self.shell.set_completer_frame(self.curframe)
328 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
288 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
329
289
330 def new_do_down(self, arg):
290 def new_do_down(self, arg):
331 OldPdb.do_down(self, arg)
291 OldPdb.do_down(self, arg)
332 self.shell.set_completer_frame(self.curframe)
292 self.shell.set_completer_frame(self.curframe)
333
293
334 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
294 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
335
295
336 def new_do_frame(self, arg):
296 def new_do_frame(self, arg):
337 OldPdb.do_frame(self, arg)
297 OldPdb.do_frame(self, arg)
338 self.shell.set_completer_frame(self.curframe)
298 self.shell.set_completer_frame(self.curframe)
339
299
340 def new_do_quit(self, arg):
300 def new_do_quit(self, arg):
341
301
342 if hasattr(self, 'old_all_completions'):
302 if hasattr(self, 'old_all_completions'):
343 self.shell.Completer.all_completions=self.old_all_completions
303 self.shell.Completer.all_completions=self.old_all_completions
344
304
345 return OldPdb.do_quit(self, arg)
305 return OldPdb.do_quit(self, arg)
346
306
347 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
307 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
348
308
349 def new_do_restart(self, arg):
309 def new_do_restart(self, arg):
350 """Restart command. In the context of ipython this is exactly the same
310 """Restart command. In the context of ipython this is exactly the same
351 thing as 'quit'."""
311 thing as 'quit'."""
352 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
312 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
353 return self.do_quit(arg)
313 return self.do_quit(arg)
354
314
355 def postloop(self):
315 def postloop(self):
356 self.shell.set_completer_frame(None)
316 self.shell.set_completer_frame(None)
357
317
358 def print_stack_trace(self, context=None):
318 def print_stack_trace(self, context=None):
359 if context is None:
319 if context is None:
360 context = self.context
320 context = self.context
361 try:
321 try:
362 context=int(context)
322 context=int(context)
363 if context <= 0:
323 if context <= 0:
364 raise ValueError("Context must be a positive integer")
324 raise ValueError("Context must be a positive integer")
365 except (TypeError, ValueError):
325 except (TypeError, ValueError):
366 raise ValueError("Context must be a positive integer")
326 raise ValueError("Context must be a positive integer")
367 try:
327 try:
368 for frame_lineno in self.stack:
328 for frame_lineno in self.stack:
369 self.print_stack_entry(frame_lineno, context=context)
329 self.print_stack_entry(frame_lineno, context=context)
370 except KeyboardInterrupt:
330 except KeyboardInterrupt:
371 pass
331 pass
372
332
373 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
333 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
374 context=None):
334 context=None):
375 if context is None:
335 if context is None:
376 context = self.context
336 context = self.context
377 try:
337 try:
378 context=int(context)
338 context=int(context)
379 if context <= 0:
339 if context <= 0:
380 raise ValueError("Context must be a positive integer")
340 raise ValueError("Context must be a positive integer")
381 except (TypeError, ValueError):
341 except (TypeError, ValueError):
382 raise ValueError("Context must be a positive integer")
342 raise ValueError("Context must be a positive integer")
383 print(self.format_stack_entry(frame_lineno, '', context))
343 print(self.format_stack_entry(frame_lineno, '', context))
384
344
385 # vds: >>
345 # vds: >>
386 frame, lineno = frame_lineno
346 frame, lineno = frame_lineno
387 filename = frame.f_code.co_filename
347 filename = frame.f_code.co_filename
388 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
348 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
389 # vds: <<
349 # vds: <<
390
350
391 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
351 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
392 if context is None:
352 if context is None:
393 context = self.context
353 context = self.context
394 try:
354 try:
395 context=int(context)
355 context=int(context)
396 if context <= 0:
356 if context <= 0:
397 print("Context must be a positive integer")
357 print("Context must be a positive integer")
398 except (TypeError, ValueError):
358 except (TypeError, ValueError):
399 print("Context must be a positive integer")
359 print("Context must be a positive integer")
400 try:
360 try:
401 import reprlib # Py 3
361 import reprlib # Py 3
402 except ImportError:
362 except ImportError:
403 import repr as reprlib # Py 2
363 import repr as reprlib # Py 2
404
364
405 ret = []
365 ret = []
406
366
407 Colors = self.color_scheme_table.active_colors
367 Colors = self.color_scheme_table.active_colors
408 ColorsNormal = Colors.Normal
368 ColorsNormal = Colors.Normal
409 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
369 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
410 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
370 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
411 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
371 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
412 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
372 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
413 ColorsNormal)
373 ColorsNormal)
414
374
415 frame, lineno = frame_lineno
375 frame, lineno = frame_lineno
416
376
417 return_value = ''
377 return_value = ''
418 if '__return__' in frame.f_locals:
378 if '__return__' in frame.f_locals:
419 rv = frame.f_locals['__return__']
379 rv = frame.f_locals['__return__']
420 #return_value += '->'
380 #return_value += '->'
421 return_value += reprlib.repr(rv) + '\n'
381 return_value += reprlib.repr(rv) + '\n'
422 ret.append(return_value)
382 ret.append(return_value)
423
383
424 #s = filename + '(' + `lineno` + ')'
384 #s = filename + '(' + `lineno` + ')'
425 filename = self.canonic(frame.f_code.co_filename)
385 filename = self.canonic(frame.f_code.co_filename)
426 link = tpl_link % py3compat.cast_unicode(filename)
386 link = tpl_link % py3compat.cast_unicode(filename)
427
387
428 if frame.f_code.co_name:
388 if frame.f_code.co_name:
429 func = frame.f_code.co_name
389 func = frame.f_code.co_name
430 else:
390 else:
431 func = "<lambda>"
391 func = "<lambda>"
432
392
433 call = ''
393 call = ''
434 if func != '?':
394 if func != '?':
435 if '__args__' in frame.f_locals:
395 if '__args__' in frame.f_locals:
436 args = reprlib.repr(frame.f_locals['__args__'])
396 args = reprlib.repr(frame.f_locals['__args__'])
437 else:
397 else:
438 args = '()'
398 args = '()'
439 call = tpl_call % (func, args)
399 call = tpl_call % (func, args)
440
400
441 # The level info should be generated in the same format pdb uses, to
401 # The level info should be generated in the same format pdb uses, to
442 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
402 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
443 if frame is self.curframe:
403 if frame is self.curframe:
444 ret.append('> ')
404 ret.append('> ')
445 else:
405 else:
446 ret.append(' ')
406 ret.append(' ')
447 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
407 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
448
408
449 start = lineno - 1 - context//2
409 start = lineno - 1 - context//2
450 lines = ulinecache.getlines(filename)
410 lines = ulinecache.getlines(filename)
451 start = min(start, len(lines) - context)
411 start = min(start, len(lines) - context)
452 start = max(start, 0)
412 start = max(start, 0)
453 lines = lines[start : start + context]
413 lines = lines[start : start + context]
454
414
455 for i,line in enumerate(lines):
415 for i,line in enumerate(lines):
456 show_arrow = (start + 1 + i == lineno)
416 show_arrow = (start + 1 + i == lineno)
457 linetpl = (frame is self.curframe or show_arrow) \
417 linetpl = (frame is self.curframe or show_arrow) \
458 and tpl_line_em \
418 and tpl_line_em \
459 or tpl_line
419 or tpl_line
460 ret.append(self.__format_line(linetpl, filename,
420 ret.append(self.__format_line(linetpl, filename,
461 start + 1 + i, line,
421 start + 1 + i, line,
462 arrow = show_arrow) )
422 arrow = show_arrow) )
463 return ''.join(ret)
423 return ''.join(ret)
464
424
465 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
425 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
466 bp_mark = ""
426 bp_mark = ""
467 bp_mark_color = ""
427 bp_mark_color = ""
468
428
469 scheme = self.color_scheme_table.active_scheme_name
429 scheme = self.color_scheme_table.active_scheme_name
470 new_line, err = self.parser.format2(line, 'str', scheme)
430 new_line, err = self.parser.format2(line, 'str', scheme)
471 if not err: line = new_line
431 if not err: line = new_line
472
432
473 bp = None
433 bp = None
474 if lineno in self.get_file_breaks(filename):
434 if lineno in self.get_file_breaks(filename):
475 bps = self.get_breaks(filename, lineno)
435 bps = self.get_breaks(filename, lineno)
476 bp = bps[-1]
436 bp = bps[-1]
477
437
478 if bp:
438 if bp:
479 Colors = self.color_scheme_table.active_colors
439 Colors = self.color_scheme_table.active_colors
480 bp_mark = str(bp.number)
440 bp_mark = str(bp.number)
481 bp_mark_color = Colors.breakpoint_enabled
441 bp_mark_color = Colors.breakpoint_enabled
482 if not bp.enabled:
442 if not bp.enabled:
483 bp_mark_color = Colors.breakpoint_disabled
443 bp_mark_color = Colors.breakpoint_disabled
484
444
485 numbers_width = 7
445 numbers_width = 7
486 if arrow:
446 if arrow:
487 # This is the line with the error
447 # This is the line with the error
488 pad = numbers_width - len(str(lineno)) - len(bp_mark)
448 pad = numbers_width - len(str(lineno)) - len(bp_mark)
489 num = '%s%s' % (make_arrow(pad), str(lineno))
449 num = '%s%s' % (make_arrow(pad), str(lineno))
490 else:
450 else:
491 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
451 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
492
452
493 return tpl_line % (bp_mark_color + bp_mark, num, line)
453 return tpl_line % (bp_mark_color + bp_mark, num, line)
494
454
495
455
496 def list_command_pydb(self, arg):
497 """List command to use if we have a newer pydb installed"""
498 filename, first, last = OldPdb.parse_list_cmd(self, arg)
499 if filename is not None:
500 self.print_list_lines(filename, first, last)
501
502 def print_list_lines(self, filename, first, last):
456 def print_list_lines(self, filename, first, last):
503 """The printing (as opposed to the parsing part of a 'list'
457 """The printing (as opposed to the parsing part of a 'list'
504 command."""
458 command."""
505 try:
459 try:
506 Colors = self.color_scheme_table.active_colors
460 Colors = self.color_scheme_table.active_colors
507 ColorsNormal = Colors.Normal
461 ColorsNormal = Colors.Normal
508 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
462 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
509 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
463 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
510 src = []
464 src = []
511 if filename == "<string>" and hasattr(self, "_exec_filename"):
465 if filename == "<string>" and hasattr(self, "_exec_filename"):
512 filename = self._exec_filename
466 filename = self._exec_filename
513
467
514 for lineno in range(first, last+1):
468 for lineno in range(first, last+1):
515 line = ulinecache.getline(filename, lineno)
469 line = ulinecache.getline(filename, lineno)
516 if not line:
470 if not line:
517 break
471 break
518
472
519 if lineno == self.curframe.f_lineno:
473 if lineno == self.curframe.f_lineno:
520 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
474 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
521 else:
475 else:
522 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
476 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
523
477
524 src.append(line)
478 src.append(line)
525 self.lineno = lineno
479 self.lineno = lineno
526
480
527 print(''.join(src))
481 print(''.join(src))
528
482
529 except KeyboardInterrupt:
483 except KeyboardInterrupt:
530 pass
484 pass
531
485
532 def do_list(self, arg):
486 def do_list(self, arg):
533 self.lastcmd = 'list'
487 self.lastcmd = 'list'
534 last = None
488 last = None
535 if arg:
489 if arg:
536 try:
490 try:
537 x = eval(arg, {}, {})
491 x = eval(arg, {}, {})
538 if type(x) == type(()):
492 if type(x) == type(()):
539 first, last = x
493 first, last = x
540 first = int(first)
494 first = int(first)
541 last = int(last)
495 last = int(last)
542 if last < first:
496 if last < first:
543 # Assume it's a count
497 # Assume it's a count
544 last = first + last
498 last = first + last
545 else:
499 else:
546 first = max(1, int(x) - 5)
500 first = max(1, int(x) - 5)
547 except:
501 except:
548 print('*** Error in argument:', repr(arg))
502 print('*** Error in argument:', repr(arg))
549 return
503 return
550 elif self.lineno is None:
504 elif self.lineno is None:
551 first = max(1, self.curframe.f_lineno - 5)
505 first = max(1, self.curframe.f_lineno - 5)
552 else:
506 else:
553 first = self.lineno + 1
507 first = self.lineno + 1
554 if last is None:
508 if last is None:
555 last = first + 10
509 last = first + 10
556 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
510 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
557
511
558 # vds: >>
512 # vds: >>
559 lineno = first
513 lineno = first
560 filename = self.curframe.f_code.co_filename
514 filename = self.curframe.f_code.co_filename
561 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
515 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
562 # vds: <<
516 # vds: <<
563
517
564 do_l = do_list
518 do_l = do_list
565
519
566 def getsourcelines(self, obj):
520 def getsourcelines(self, obj):
567 lines, lineno = inspect.findsource(obj)
521 lines, lineno = inspect.findsource(obj)
568 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
522 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
569 # must be a module frame: do not try to cut a block out of it
523 # must be a module frame: do not try to cut a block out of it
570 return lines, 1
524 return lines, 1
571 elif inspect.ismodule(obj):
525 elif inspect.ismodule(obj):
572 return lines, 1
526 return lines, 1
573 return inspect.getblock(lines[lineno:]), lineno+1
527 return inspect.getblock(lines[lineno:]), lineno+1
574
528
575 def do_longlist(self, arg):
529 def do_longlist(self, arg):
576 self.lastcmd = 'longlist'
530 self.lastcmd = 'longlist'
577 try:
531 try:
578 lines, lineno = self.getsourcelines(self.curframe)
532 lines, lineno = self.getsourcelines(self.curframe)
579 except OSError as err:
533 except OSError as err:
580 self.error(err)
534 self.error(err)
581 return
535 return
582 last = lineno + len(lines)
536 last = lineno + len(lines)
583 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
537 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
584 do_ll = do_longlist
538 do_ll = do_longlist
585
539
586 def do_pdef(self, arg):
540 def do_pdef(self, arg):
587 """Print the call signature for any callable object.
541 """Print the call signature for any callable object.
588
542
589 The debugger interface to %pdef"""
543 The debugger interface to %pdef"""
590 namespaces = [('Locals', self.curframe.f_locals),
544 namespaces = [('Locals', self.curframe.f_locals),
591 ('Globals', self.curframe.f_globals)]
545 ('Globals', self.curframe.f_globals)]
592 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
546 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
593
547
594 def do_pdoc(self, arg):
548 def do_pdoc(self, arg):
595 """Print the docstring for an object.
549 """Print the docstring for an object.
596
550
597 The debugger interface to %pdoc."""
551 The debugger interface to %pdoc."""
598 namespaces = [('Locals', self.curframe.f_locals),
552 namespaces = [('Locals', self.curframe.f_locals),
599 ('Globals', self.curframe.f_globals)]
553 ('Globals', self.curframe.f_globals)]
600 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
554 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
601
555
602 def do_pfile(self, arg):
556 def do_pfile(self, arg):
603 """Print (or run through pager) the file where an object is defined.
557 """Print (or run through pager) the file where an object is defined.
604
558
605 The debugger interface to %pfile.
559 The debugger interface to %pfile.
606 """
560 """
607 namespaces = [('Locals', self.curframe.f_locals),
561 namespaces = [('Locals', self.curframe.f_locals),
608 ('Globals', self.curframe.f_globals)]
562 ('Globals', self.curframe.f_globals)]
609 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
563 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
610
564
611 def do_pinfo(self, arg):
565 def do_pinfo(self, arg):
612 """Provide detailed information about an object.
566 """Provide detailed information about an object.
613
567
614 The debugger interface to %pinfo, i.e., obj?."""
568 The debugger interface to %pinfo, i.e., obj?."""
615 namespaces = [('Locals', self.curframe.f_locals),
569 namespaces = [('Locals', self.curframe.f_locals),
616 ('Globals', self.curframe.f_globals)]
570 ('Globals', self.curframe.f_globals)]
617 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
571 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
618
572
619 def do_pinfo2(self, arg):
573 def do_pinfo2(self, arg):
620 """Provide extra detailed information about an object.
574 """Provide extra detailed information about an object.
621
575
622 The debugger interface to %pinfo2, i.e., obj??."""
576 The debugger interface to %pinfo2, i.e., obj??."""
623 namespaces = [('Locals', self.curframe.f_locals),
577 namespaces = [('Locals', self.curframe.f_locals),
624 ('Globals', self.curframe.f_globals)]
578 ('Globals', self.curframe.f_globals)]
625 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
579 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
626
580
627 def do_psource(self, arg):
581 def do_psource(self, arg):
628 """Print (or run through pager) the source code for an object."""
582 """Print (or run through pager) the source code for an object."""
629 namespaces = [('Locals', self.curframe.f_locals),
583 namespaces = [('Locals', self.curframe.f_locals),
630 ('Globals', self.curframe.f_globals)]
584 ('Globals', self.curframe.f_globals)]
631 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
585 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
632
586
633 if sys.version_info > (3, ):
587 if sys.version_info > (3, ):
634 def do_where(self, arg):
588 def do_where(self, arg):
635 """w(here)
589 """w(here)
636 Print a stack trace, with the most recent frame at the bottom.
590 Print a stack trace, with the most recent frame at the bottom.
637 An arrow indicates the "current frame", which determines the
591 An arrow indicates the "current frame", which determines the
638 context of most commands. 'bt' is an alias for this command.
592 context of most commands. 'bt' is an alias for this command.
639
593
640 Take a number as argument as an (optional) number of context line to
594 Take a number as argument as an (optional) number of context line to
641 print"""
595 print"""
642 if arg:
596 if arg:
643 context = int(arg)
597 context = int(arg)
644 self.print_stack_trace(context)
598 self.print_stack_trace(context)
645 else:
599 else:
646 self.print_stack_trace()
600 self.print_stack_trace()
647
601
648 do_w = do_where
602 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