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