##// END OF EJS Templates
move completer configurables to IPCompleter where they belong...
MinRK -
Show More
@@ -1,910 +1,925 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 Original rlcompleter documentation:
9 Original rlcompleter documentation:
10
10
11 This requires the latest extension to the readline module (the
11 This requires the latest extension to the readline module (the
12 completes keywords, built-ins and globals in __main__; when completing
12 completes keywords, built-ins and globals in __main__; when completing
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 completes its attributes.
14 completes its attributes.
15
15
16 It's very cool to do "import string" type "string.", hit the
16 It's very cool to do "import string" type "string.", hit the
17 completion key (twice), and see the list of names defined by the
17 completion key (twice), and see the list of names defined by the
18 string module!
18 string module!
19
19
20 Tip: to use the tab key as the completion key, call
20 Tip: to use the tab key as the completion key, call
21
21
22 readline.parse_and_bind("tab: complete")
22 readline.parse_and_bind("tab: complete")
23
23
24 Notes:
24 Notes:
25
25
26 - Exceptions raised by the completer function are *ignored* (and
26 - Exceptions raised by the completer function are *ignored* (and
27 generally cause the completion to fail). This is a feature -- since
27 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
30 reset and restore the tty state.
31
31
32 - The evaluation of the NAME.NAME... form may cause arbitrary
32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 application defined code to be executed if an object with a
33 application defined code to be executed if an object with a
34 __getattr__ hook is found. Since it is the responsibility of the
34 __getattr__ hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
37 indexing operations) are *not* evaluated.
38
38
39 - GNU readline is also used by the built-in functions input() and
39 - GNU readline is also used by the built-in functions input() and
40 raw_input(), and thus these also benefit/suffer from the completer
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
42 specifying its own completer function and using raw_input() for all
43 its input.
43 its input.
44
44
45 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
47 """
47 """
48
48
49 #*****************************************************************************
49 #*****************************************************************************
50 #
50 #
51 # Since this file is essentially a minimally modified copy of the rlcompleter
51 # Since this file is essentially a minimally modified copy of the rlcompleter
52 # module which is part of the standard Python distribution, I assume that the
52 # module which is part of the standard Python distribution, I assume that the
53 # proper procedure is to maintain its copyright as belonging to the Python
53 # proper procedure is to maintain its copyright as belonging to the Python
54 # Software Foundation (in addition to my own, for all new code).
54 # Software Foundation (in addition to my own, for all new code).
55 #
55 #
56 # Copyright (C) 2008-2010 IPython Development Team
56 # Copyright (C) 2008-2010 IPython Development Team
57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #
62 #
63 #*****************************************************************************
63 #*****************************************************************************
64 from __future__ import print_function
64 from __future__ import print_function
65
65
66 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
67 # Imports
67 # Imports
68 #-----------------------------------------------------------------------------
68 #-----------------------------------------------------------------------------
69
69
70 import __builtin__
70 import __builtin__
71 import __main__
71 import __main__
72 import glob
72 import glob
73 import inspect
73 import inspect
74 import itertools
74 import itertools
75 import keyword
75 import keyword
76 import os
76 import os
77 import re
77 import re
78 import shlex
78 import shlex
79 import sys
79 import sys
80
80
81 from IPython.config.configurable import Configurable
81 from IPython.config.configurable import Configurable
82 from IPython.core.error import TryNext
82 from IPython.core.error import TryNext
83 from IPython.core.prefilter import ESC_MAGIC
83 from IPython.core.prefilter import ESC_MAGIC
84 from IPython.utils import generics
84 from IPython.utils import generics
85 from IPython.utils import io
85 from IPython.utils import io
86 from IPython.utils.dir2 import dir2
86 from IPython.utils.dir2 import dir2
87 from IPython.utils.process import arg_split
87 from IPython.utils.process import arg_split
88 from IPython.utils.traitlets import CBool
88 from IPython.utils.traitlets import CBool, Enum
89
89
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91 # Globals
91 # Globals
92 #-----------------------------------------------------------------------------
92 #-----------------------------------------------------------------------------
93
93
94 # Public API
94 # Public API
95 __all__ = ['Completer','IPCompleter']
95 __all__ = ['Completer','IPCompleter']
96
96
97 if sys.platform == 'win32':
97 if sys.platform == 'win32':
98 PROTECTABLES = ' '
98 PROTECTABLES = ' '
99 else:
99 else:
100 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
100 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
101
101
102 #-----------------------------------------------------------------------------
102 #-----------------------------------------------------------------------------
103 # Main functions and classes
103 # Main functions and classes
104 #-----------------------------------------------------------------------------
104 #-----------------------------------------------------------------------------
105
105
106 def has_open_quotes(s):
106 def has_open_quotes(s):
107 """Return whether a string has open quotes.
107 """Return whether a string has open quotes.
108
108
109 This simply counts whether the number of quote characters of either type in
109 This simply counts whether the number of quote characters of either type in
110 the string is odd.
110 the string is odd.
111
111
112 Returns
112 Returns
113 -------
113 -------
114 If there is an open quote, the quote character is returned. Else, return
114 If there is an open quote, the quote character is returned. Else, return
115 False.
115 False.
116 """
116 """
117 # We check " first, then ', so complex cases with nested quotes will get
117 # We check " first, then ', so complex cases with nested quotes will get
118 # the " to take precedence.
118 # the " to take precedence.
119 if s.count('"') % 2:
119 if s.count('"') % 2:
120 return '"'
120 return '"'
121 elif s.count("'") % 2:
121 elif s.count("'") % 2:
122 return "'"
122 return "'"
123 else:
123 else:
124 return False
124 return False
125
125
126
126
127 def protect_filename(s):
127 def protect_filename(s):
128 """Escape a string to protect certain characters."""
128 """Escape a string to protect certain characters."""
129
129
130 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
130 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
131 for ch in s])
131 for ch in s])
132
132
133
133
134 def mark_dirs(matches):
134 def mark_dirs(matches):
135 """Mark directories in input list by appending '/' to their names."""
135 """Mark directories in input list by appending '/' to their names."""
136 out = []
136 out = []
137 isdir = os.path.isdir
137 isdir = os.path.isdir
138 for x in matches:
138 for x in matches:
139 if isdir(x):
139 if isdir(x):
140 out.append(x+'/')
140 out.append(x+'/')
141 else:
141 else:
142 out.append(x)
142 out.append(x)
143 return out
143 return out
144
144
145
145
146 def expand_user(path):
146 def expand_user(path):
147 """Expand '~'-style usernames in strings.
147 """Expand '~'-style usernames in strings.
148
148
149 This is similar to :func:`os.path.expanduser`, but it computes and returns
149 This is similar to :func:`os.path.expanduser`, but it computes and returns
150 extra information that will be useful if the input was being used in
150 extra information that will be useful if the input was being used in
151 computing completions, and you wish to return the completions with the
151 computing completions, and you wish to return the completions with the
152 original '~' instead of its expanded value.
152 original '~' instead of its expanded value.
153
153
154 Parameters
154 Parameters
155 ----------
155 ----------
156 path : str
156 path : str
157 String to be expanded. If no ~ is present, the output is the same as the
157 String to be expanded. If no ~ is present, the output is the same as the
158 input.
158 input.
159
159
160 Returns
160 Returns
161 -------
161 -------
162 newpath : str
162 newpath : str
163 Result of ~ expansion in the input path.
163 Result of ~ expansion in the input path.
164 tilde_expand : bool
164 tilde_expand : bool
165 Whether any expansion was performed or not.
165 Whether any expansion was performed or not.
166 tilde_val : str
166 tilde_val : str
167 The value that ~ was replaced with.
167 The value that ~ was replaced with.
168 """
168 """
169 # Default values
169 # Default values
170 tilde_expand = False
170 tilde_expand = False
171 tilde_val = ''
171 tilde_val = ''
172 newpath = path
172 newpath = path
173
173
174 if path.startswith('~'):
174 if path.startswith('~'):
175 tilde_expand = True
175 tilde_expand = True
176 rest = len(path)-1
176 rest = len(path)-1
177 newpath = os.path.expanduser(path)
177 newpath = os.path.expanduser(path)
178 if rest:
178 if rest:
179 tilde_val = newpath[:-rest]
179 tilde_val = newpath[:-rest]
180 else:
180 else:
181 tilde_val = newpath
181 tilde_val = newpath
182
182
183 return newpath, tilde_expand, tilde_val
183 return newpath, tilde_expand, tilde_val
184
184
185
185
186 def compress_user(path, tilde_expand, tilde_val):
186 def compress_user(path, tilde_expand, tilde_val):
187 """Does the opposite of expand_user, with its outputs.
187 """Does the opposite of expand_user, with its outputs.
188 """
188 """
189 if tilde_expand:
189 if tilde_expand:
190 return path.replace(tilde_val, '~')
190 return path.replace(tilde_val, '~')
191 else:
191 else:
192 return path
192 return path
193
193
194
194
195 def single_dir_expand(matches):
195 def single_dir_expand(matches):
196 "Recursively expand match lists containing a single dir."
196 "Recursively expand match lists containing a single dir."
197
197
198 if len(matches) == 1 and os.path.isdir(matches[0]):
198 if len(matches) == 1 and os.path.isdir(matches[0]):
199 # Takes care of links to directories also. Use '/'
199 # Takes care of links to directories also. Use '/'
200 # explicitly, even under Windows, so that name completions
200 # explicitly, even under Windows, so that name completions
201 # don't end up escaped.
201 # don't end up escaped.
202 d = matches[0]
202 d = matches[0]
203 if d[-1] in ['/','\\']:
203 if d[-1] in ['/','\\']:
204 d = d[:-1]
204 d = d[:-1]
205
205
206 subdirs = os.listdir(d)
206 subdirs = os.listdir(d)
207 if subdirs:
207 if subdirs:
208 matches = [ (d + '/' + p) for p in subdirs]
208 matches = [ (d + '/' + p) for p in subdirs]
209 return single_dir_expand(matches)
209 return single_dir_expand(matches)
210 else:
210 else:
211 return matches
211 return matches
212 else:
212 else:
213 return matches
213 return matches
214
214
215
215
216 class Bunch(object): pass
216 class Bunch(object): pass
217
217
218 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
218 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
219 GREEDY_DELIMS = ' \r\n'
219 GREEDY_DELIMS = ' \r\n'
220
220
221 class CompletionSplitter(object):
221 class CompletionSplitter(object):
222 """An object to split an input line in a manner similar to readline.
222 """An object to split an input line in a manner similar to readline.
223
223
224 By having our own implementation, we can expose readline-like completion in
224 By having our own implementation, we can expose readline-like completion in
225 a uniform manner to all frontends. This object only needs to be given the
225 a uniform manner to all frontends. This object only needs to be given the
226 line of text to be split and the cursor position on said line, and it
226 line of text to be split and the cursor position on said line, and it
227 returns the 'word' to be completed on at the cursor after splitting the
227 returns the 'word' to be completed on at the cursor after splitting the
228 entire line.
228 entire line.
229
229
230 What characters are used as splitting delimiters can be controlled by
230 What characters are used as splitting delimiters can be controlled by
231 setting the `delims` attribute (this is a property that internally
231 setting the `delims` attribute (this is a property that internally
232 automatically builds the necessary """
232 automatically builds the necessary """
233
233
234 # Private interface
234 # Private interface
235
235
236 # A string of delimiter characters. The default value makes sense for
236 # A string of delimiter characters. The default value makes sense for
237 # IPython's most typical usage patterns.
237 # IPython's most typical usage patterns.
238 _delims = DELIMS
238 _delims = DELIMS
239
239
240 # The expression (a normal string) to be compiled into a regular expression
240 # The expression (a normal string) to be compiled into a regular expression
241 # for actual splitting. We store it as an attribute mostly for ease of
241 # for actual splitting. We store it as an attribute mostly for ease of
242 # debugging, since this type of code can be so tricky to debug.
242 # debugging, since this type of code can be so tricky to debug.
243 _delim_expr = None
243 _delim_expr = None
244
244
245 # The regular expression that does the actual splitting
245 # The regular expression that does the actual splitting
246 _delim_re = None
246 _delim_re = None
247
247
248 def __init__(self, delims=None):
248 def __init__(self, delims=None):
249 delims = CompletionSplitter._delims if delims is None else delims
249 delims = CompletionSplitter._delims if delims is None else delims
250 self.set_delims(delims)
250 self.set_delims(delims)
251
251
252 def set_delims(self, delims):
252 def set_delims(self, delims):
253 """Set the delimiters for line splitting."""
253 """Set the delimiters for line splitting."""
254 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
254 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
255 self._delim_re = re.compile(expr)
255 self._delim_re = re.compile(expr)
256 self._delims = delims
256 self._delims = delims
257 self._delim_expr = expr
257 self._delim_expr = expr
258
258
259 def get_delims(self):
259 def get_delims(self):
260 """Return the string of delimiter characters."""
260 """Return the string of delimiter characters."""
261 return self._delims
261 return self._delims
262
262
263 def split_line(self, line, cursor_pos=None):
263 def split_line(self, line, cursor_pos=None):
264 """Split a line of text with a cursor at the given position.
264 """Split a line of text with a cursor at the given position.
265 """
265 """
266 l = line if cursor_pos is None else line[:cursor_pos]
266 l = line if cursor_pos is None else line[:cursor_pos]
267 return self._delim_re.split(l)[-1]
267 return self._delim_re.split(l)[-1]
268
268
269
269
270 class Completer(Configurable):
270 class Completer(Configurable):
271
271
272 greedy = CBool(False, config=True,
272 greedy = CBool(False, config=True,
273 help="""Activate greedy completion
273 help="""Activate greedy completion
274
274
275 This will enable completion on elements of lists, results of function calls, etc.,
275 This will enable completion on elements of lists, results of function calls, etc.,
276 but can be unsafe because the code is actually evaluated on TAB.
276 but can be unsafe because the code is actually evaluated on TAB.
277 """
277 """
278 )
278 )
279
279
280
280 def __init__(self, namespace=None, global_namespace=None, config=None):
281 def __init__(self, namespace=None, global_namespace=None, config=None, **kwargs):
281 """Create a new completer for the command line.
282 """Create a new completer for the command line.
282
283
283 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
284 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
284
285
285 If unspecified, the default namespace where completions are performed
286 If unspecified, the default namespace where completions are performed
286 is __main__ (technically, __main__.__dict__). Namespaces should be
287 is __main__ (technically, __main__.__dict__). Namespaces should be
287 given as dictionaries.
288 given as dictionaries.
288
289
289 An optional second namespace can be given. This allows the completer
290 An optional second namespace can be given. This allows the completer
290 to handle cases where both the local and global scopes need to be
291 to handle cases where both the local and global scopes need to be
291 distinguished.
292 distinguished.
292
293
293 Completer instances should be used as the completion mechanism of
294 Completer instances should be used as the completion mechanism of
294 readline via the set_completer() call:
295 readline via the set_completer() call:
295
296
296 readline.set_completer(Completer(my_namespace).complete)
297 readline.set_completer(Completer(my_namespace).complete)
297 """
298 """
298
299
299 # Don't bind to namespace quite yet, but flag whether the user wants a
300 # Don't bind to namespace quite yet, but flag whether the user wants a
300 # specific namespace or to use __main__.__dict__. This will allow us
301 # specific namespace or to use __main__.__dict__. This will allow us
301 # to bind to __main__.__dict__ at completion time, not now.
302 # to bind to __main__.__dict__ at completion time, not now.
302 if namespace is None:
303 if namespace is None:
303 self.use_main_ns = 1
304 self.use_main_ns = 1
304 else:
305 else:
305 self.use_main_ns = 0
306 self.use_main_ns = 0
306 self.namespace = namespace
307 self.namespace = namespace
307
308
308 # The global namespace, if given, can be bound directly
309 # The global namespace, if given, can be bound directly
309 if global_namespace is None:
310 if global_namespace is None:
310 self.global_namespace = {}
311 self.global_namespace = {}
311 else:
312 else:
312 self.global_namespace = global_namespace
313 self.global_namespace = global_namespace
313
314
314 super(Completer, self).__init__(config=config)
315 super(Completer, self).__init__(config=config, **kwargs)
315
316
316 def complete(self, text, state):
317 def complete(self, text, state):
317 """Return the next possible completion for 'text'.
318 """Return the next possible completion for 'text'.
318
319
319 This is called successively with state == 0, 1, 2, ... until it
320 This is called successively with state == 0, 1, 2, ... until it
320 returns None. The completion should begin with 'text'.
321 returns None. The completion should begin with 'text'.
321
322
322 """
323 """
323 if self.use_main_ns:
324 if self.use_main_ns:
324 self.namespace = __main__.__dict__
325 self.namespace = __main__.__dict__
325
326
326 if state == 0:
327 if state == 0:
327 if "." in text:
328 if "." in text:
328 self.matches = self.attr_matches(text)
329 self.matches = self.attr_matches(text)
329 else:
330 else:
330 self.matches = self.global_matches(text)
331 self.matches = self.global_matches(text)
331 try:
332 try:
332 return self.matches[state]
333 return self.matches[state]
333 except IndexError:
334 except IndexError:
334 return None
335 return None
335
336
336 def global_matches(self, text):
337 def global_matches(self, text):
337 """Compute matches when text is a simple name.
338 """Compute matches when text is a simple name.
338
339
339 Return a list of all keywords, built-in functions and names currently
340 Return a list of all keywords, built-in functions and names currently
340 defined in self.namespace or self.global_namespace that match.
341 defined in self.namespace or self.global_namespace that match.
341
342
342 """
343 """
343 #print 'Completer->global_matches, txt=%r' % text # dbg
344 #print 'Completer->global_matches, txt=%r' % text # dbg
344 matches = []
345 matches = []
345 match_append = matches.append
346 match_append = matches.append
346 n = len(text)
347 n = len(text)
347 for lst in [keyword.kwlist,
348 for lst in [keyword.kwlist,
348 __builtin__.__dict__.keys(),
349 __builtin__.__dict__.keys(),
349 self.namespace.keys(),
350 self.namespace.keys(),
350 self.global_namespace.keys()]:
351 self.global_namespace.keys()]:
351 for word in lst:
352 for word in lst:
352 if word[:n] == text and word != "__builtins__":
353 if word[:n] == text and word != "__builtins__":
353 match_append(word)
354 match_append(word)
354 return matches
355 return matches
355
356
356 def attr_matches(self, text):
357 def attr_matches(self, text):
357 """Compute matches when text contains a dot.
358 """Compute matches when text contains a dot.
358
359
359 Assuming the text is of the form NAME.NAME....[NAME], and is
360 Assuming the text is of the form NAME.NAME....[NAME], and is
360 evaluatable in self.namespace or self.global_namespace, it will be
361 evaluatable in self.namespace or self.global_namespace, it will be
361 evaluated and its attributes (as revealed by dir()) are used as
362 evaluated and its attributes (as revealed by dir()) are used as
362 possible completions. (For class instances, class members are are
363 possible completions. (For class instances, class members are are
363 also considered.)
364 also considered.)
364
365
365 WARNING: this can still invoke arbitrary C code, if an object
366 WARNING: this can still invoke arbitrary C code, if an object
366 with a __getattr__ hook is evaluated.
367 with a __getattr__ hook is evaluated.
367
368
368 """
369 """
369
370
370 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
371 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
371 # Another option, seems to work great. Catches things like ''.<tab>
372 # Another option, seems to work great. Catches things like ''.<tab>
372 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
373 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
373
374
374 if m:
375 if m:
375 expr, attr = m.group(1, 3)
376 expr, attr = m.group(1, 3)
376 elif self.greedy:
377 elif self.greedy:
377 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
378 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
378 if not m2:
379 if not m2:
379 return []
380 return []
380 expr, attr = m2.group(1,2)
381 expr, attr = m2.group(1,2)
381 else:
382 else:
382 return []
383 return []
383
384
384 try:
385 try:
385 obj = eval(expr, self.namespace)
386 obj = eval(expr, self.namespace)
386 except:
387 except:
387 try:
388 try:
388 obj = eval(expr, self.global_namespace)
389 obj = eval(expr, self.global_namespace)
389 except:
390 except:
390 return []
391 return []
391
392
392 words = dir2(obj)
393 words = dir2(obj)
393
394
394 try:
395 try:
395 words = generics.complete_object(obj, words)
396 words = generics.complete_object(obj, words)
396 except TryNext:
397 except TryNext:
397 pass
398 pass
398 except Exception:
399 except Exception:
399 # Silence errors from completion function
400 # Silence errors from completion function
400 #raise # dbg
401 #raise # dbg
401 pass
402 pass
402 # Build match list to return
403 # Build match list to return
403 n = len(attr)
404 n = len(attr)
404 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
405 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
405 return res
406 return res
406
407
407
408
408 class IPCompleter(Completer):
409 class IPCompleter(Completer):
409 """Extension of the completer class with IPython-specific features"""
410 """Extension of the completer class with IPython-specific features"""
410
411
411 def _greedy_changed(self, name, old, new):
412 def _greedy_changed(self, name, old, new):
412 """update the splitter and readline delims when greedy is changed"""
413 """update the splitter and readline delims when greedy is changed"""
413 if new:
414 if new:
414 self.splitter.set_delims(GREEDY_DELIMS)
415 self.splitter.set_delims(GREEDY_DELIMS)
415 else:
416 else:
416 self.splitter.set_delims(DELIMS)
417 self.splitter.set_delims(DELIMS)
417
418
418 if self.readline:
419 if self.readline:
419 self.readline.set_completer_delims(self.splitter.get_delims())
420 self.readline.set_completer_delims(self.splitter.get_delims())
421
422 merge_completions = CBool(True, config=True,
423 help="""Whether to merge completion results into a single list
424
425 If False, only the completion results from the first non-empty
426 completer will be returned.
427 """
428 )
429 omit__names = Enum((0,1,2), default_value=2, config=True,
430 help="""Instruct the completer to omit private method names
431
432 Specifically, when completing on ``object.<tab>``.
433
434 When 2 [default]: all names that start with '_' will be excluded.
435
436 When 1: all 'magic' names (``__foo__``) will be excluded.
437
438 When 0: nothing will be excluded.
439 """
440 )
420
441
421 def __init__(self, shell=None, namespace=None, global_namespace=None,
442 def __init__(self, shell=None, namespace=None, global_namespace=None,
422 omit__names=True, alias_table=None, use_readline=True,
443 alias_table=None, use_readline=True,
423 config=None):
444 config=None, **kwargs):
424 """IPCompleter() -> completer
445 """IPCompleter() -> completer
425
446
426 Return a completer object suitable for use by the readline library
447 Return a completer object suitable for use by the readline library
427 via readline.set_completer().
448 via readline.set_completer().
428
449
429 Inputs:
450 Inputs:
430
451
431 - shell: a pointer to the ipython shell itself. This is needed
452 - shell: a pointer to the ipython shell itself. This is needed
432 because this completer knows about magic functions, and those can
453 because this completer knows about magic functions, and those can
433 only be accessed via the ipython instance.
454 only be accessed via the ipython instance.
434
455
435 - namespace: an optional dict where completions are performed.
456 - namespace: an optional dict where completions are performed.
436
457
437 - global_namespace: secondary optional dict for completions, to
458 - global_namespace: secondary optional dict for completions, to
438 handle cases (such as IPython embedded inside functions) where
459 handle cases (such as IPython embedded inside functions) where
439 both Python scopes are visible.
460 both Python scopes are visible.
440
461
441 - The optional omit__names parameter sets the completer to omit the
442 'magic' names (__magicname__) for python objects unless the text
443 to be completed explicitly starts with one or more underscores.
444
445 - If alias_table is supplied, it should be a dictionary of aliases
462 - If alias_table is supplied, it should be a dictionary of aliases
446 to complete.
463 to complete.
447
464
448 use_readline : bool, optional
465 use_readline : bool, optional
449 If true, use the readline library. This completer can still function
466 If true, use the readline library. This completer can still function
450 without readline, though in that case callers must provide some extra
467 without readline, though in that case callers must provide some extra
451 information on each call about the current line."""
468 information on each call about the current line."""
452
469
453 self.magic_escape = ESC_MAGIC
470 self.magic_escape = ESC_MAGIC
454 self.splitter = CompletionSplitter()
471 self.splitter = CompletionSplitter()
455
472
456 # Readline configuration, only used by the rlcompleter method.
473 # Readline configuration, only used by the rlcompleter method.
457 if use_readline:
474 if use_readline:
458 # We store the right version of readline so that later code
475 # We store the right version of readline so that later code
459 import IPython.utils.rlineimpl as readline
476 import IPython.utils.rlineimpl as readline
460 self.readline = readline
477 self.readline = readline
461 else:
478 else:
462 self.readline = None
479 self.readline = None
463
480
464 # _greedy_changed() depends on splitter and readline being defined:
481 # _greedy_changed() depends on splitter and readline being defined:
465 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
482 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
466 config=config)
483 config=config, **kwargs)
467
484
468 # List where completion matches will be stored
485 # List where completion matches will be stored
469 self.matches = []
486 self.matches = []
470 self.omit__names = omit__names
471 self.merge_completions = shell.readline_merge_completions
472 self.shell = shell.shell
487 self.shell = shell.shell
473 if alias_table is None:
488 if alias_table is None:
474 alias_table = {}
489 alias_table = {}
475 self.alias_table = alias_table
490 self.alias_table = alias_table
476 # Regexp to split filenames with spaces in them
491 # Regexp to split filenames with spaces in them
477 self.space_name_re = re.compile(r'([^\\] )')
492 self.space_name_re = re.compile(r'([^\\] )')
478 # Hold a local ref. to glob.glob for speed
493 # Hold a local ref. to glob.glob for speed
479 self.glob = glob.glob
494 self.glob = glob.glob
480
495
481 # Determine if we are running on 'dumb' terminals, like (X)Emacs
496 # Determine if we are running on 'dumb' terminals, like (X)Emacs
482 # buffers, to avoid completion problems.
497 # buffers, to avoid completion problems.
483 term = os.environ.get('TERM','xterm')
498 term = os.environ.get('TERM','xterm')
484 self.dumb_terminal = term in ['dumb','emacs']
499 self.dumb_terminal = term in ['dumb','emacs']
485
500
486 # Special handling of backslashes needed in win32 platforms
501 # Special handling of backslashes needed in win32 platforms
487 if sys.platform == "win32":
502 if sys.platform == "win32":
488 self.clean_glob = self._clean_glob_win32
503 self.clean_glob = self._clean_glob_win32
489 else:
504 else:
490 self.clean_glob = self._clean_glob
505 self.clean_glob = self._clean_glob
491
506
492 # All active matcher routines for completion
507 # All active matcher routines for completion
493 self.matchers = [self.python_matches,
508 self.matchers = [self.python_matches,
494 self.file_matches,
509 self.file_matches,
495 self.magic_matches,
510 self.magic_matches,
496 self.alias_matches,
511 self.alias_matches,
497 self.python_func_kw_matches,
512 self.python_func_kw_matches,
498 ]
513 ]
499
514
500 def all_completions(self, text):
515 def all_completions(self, text):
501 """
516 """
502 Wrapper around the complete method for the benefit of emacs
517 Wrapper around the complete method for the benefit of emacs
503 and pydb.
518 and pydb.
504 """
519 """
505 return self.complete(text)[1]
520 return self.complete(text)[1]
506
521
507 def _clean_glob(self,text):
522 def _clean_glob(self,text):
508 return self.glob("%s*" % text)
523 return self.glob("%s*" % text)
509
524
510 def _clean_glob_win32(self,text):
525 def _clean_glob_win32(self,text):
511 return [f.replace("\\","/")
526 return [f.replace("\\","/")
512 for f in self.glob("%s*" % text)]
527 for f in self.glob("%s*" % text)]
513
528
514 def file_matches(self, text):
529 def file_matches(self, text):
515 """Match filenames, expanding ~USER type strings.
530 """Match filenames, expanding ~USER type strings.
516
531
517 Most of the seemingly convoluted logic in this completer is an
532 Most of the seemingly convoluted logic in this completer is an
518 attempt to handle filenames with spaces in them. And yet it's not
533 attempt to handle filenames with spaces in them. And yet it's not
519 quite perfect, because Python's readline doesn't expose all of the
534 quite perfect, because Python's readline doesn't expose all of the
520 GNU readline details needed for this to be done correctly.
535 GNU readline details needed for this to be done correctly.
521
536
522 For a filename with a space in it, the printed completions will be
537 For a filename with a space in it, the printed completions will be
523 only the parts after what's already been typed (instead of the
538 only the parts after what's already been typed (instead of the
524 full completions, as is normally done). I don't think with the
539 full completions, as is normally done). I don't think with the
525 current (as of Python 2.3) Python readline it's possible to do
540 current (as of Python 2.3) Python readline it's possible to do
526 better."""
541 better."""
527
542
528 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
543 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
529
544
530 # chars that require escaping with backslash - i.e. chars
545 # chars that require escaping with backslash - i.e. chars
531 # that readline treats incorrectly as delimiters, but we
546 # that readline treats incorrectly as delimiters, but we
532 # don't want to treat as delimiters in filename matching
547 # don't want to treat as delimiters in filename matching
533 # when escaped with backslash
548 # when escaped with backslash
534 if text.startswith('!'):
549 if text.startswith('!'):
535 text = text[1:]
550 text = text[1:]
536 text_prefix = '!'
551 text_prefix = '!'
537 else:
552 else:
538 text_prefix = ''
553 text_prefix = ''
539
554
540 text_until_cursor = self.text_until_cursor
555 text_until_cursor = self.text_until_cursor
541 # track strings with open quotes
556 # track strings with open quotes
542 open_quotes = has_open_quotes(text_until_cursor)
557 open_quotes = has_open_quotes(text_until_cursor)
543
558
544 if '(' in text_until_cursor or '[' in text_until_cursor:
559 if '(' in text_until_cursor or '[' in text_until_cursor:
545 lsplit = text
560 lsplit = text
546 else:
561 else:
547 try:
562 try:
548 # arg_split ~ shlex.split, but with unicode bugs fixed by us
563 # arg_split ~ shlex.split, but with unicode bugs fixed by us
549 lsplit = arg_split(text_until_cursor)[-1]
564 lsplit = arg_split(text_until_cursor)[-1]
550 except ValueError:
565 except ValueError:
551 # typically an unmatched ", or backslash without escaped char.
566 # typically an unmatched ", or backslash without escaped char.
552 if open_quotes:
567 if open_quotes:
553 lsplit = text_until_cursor.split(open_quotes)[-1]
568 lsplit = text_until_cursor.split(open_quotes)[-1]
554 else:
569 else:
555 return []
570 return []
556 except IndexError:
571 except IndexError:
557 # tab pressed on empty line
572 # tab pressed on empty line
558 lsplit = ""
573 lsplit = ""
559
574
560 if not open_quotes and lsplit != protect_filename(lsplit):
575 if not open_quotes and lsplit != protect_filename(lsplit):
561 # if protectables are found, do matching on the whole escaped name
576 # if protectables are found, do matching on the whole escaped name
562 has_protectables = True
577 has_protectables = True
563 text0,text = text,lsplit
578 text0,text = text,lsplit
564 else:
579 else:
565 has_protectables = False
580 has_protectables = False
566 text = os.path.expanduser(text)
581 text = os.path.expanduser(text)
567
582
568 if text == "":
583 if text == "":
569 return [text_prefix + protect_filename(f) for f in self.glob("*")]
584 return [text_prefix + protect_filename(f) for f in self.glob("*")]
570
585
571 # Compute the matches from the filesystem
586 # Compute the matches from the filesystem
572 m0 = self.clean_glob(text.replace('\\',''))
587 m0 = self.clean_glob(text.replace('\\',''))
573
588
574 if has_protectables:
589 if has_protectables:
575 # If we had protectables, we need to revert our changes to the
590 # If we had protectables, we need to revert our changes to the
576 # beginning of filename so that we don't double-write the part
591 # beginning of filename so that we don't double-write the part
577 # of the filename we have so far
592 # of the filename we have so far
578 len_lsplit = len(lsplit)
593 len_lsplit = len(lsplit)
579 matches = [text_prefix + text0 +
594 matches = [text_prefix + text0 +
580 protect_filename(f[len_lsplit:]) for f in m0]
595 protect_filename(f[len_lsplit:]) for f in m0]
581 else:
596 else:
582 if open_quotes:
597 if open_quotes:
583 # if we have a string with an open quote, we don't need to
598 # if we have a string with an open quote, we don't need to
584 # protect the names at all (and we _shouldn't_, as it
599 # protect the names at all (and we _shouldn't_, as it
585 # would cause bugs when the filesystem call is made).
600 # would cause bugs when the filesystem call is made).
586 matches = m0
601 matches = m0
587 else:
602 else:
588 matches = [text_prefix +
603 matches = [text_prefix +
589 protect_filename(f) for f in m0]
604 protect_filename(f) for f in m0]
590
605
591 #io.rprint('mm', matches) # dbg
606 #io.rprint('mm', matches) # dbg
592 return mark_dirs(matches)
607 return mark_dirs(matches)
593
608
594 def magic_matches(self, text):
609 def magic_matches(self, text):
595 """Match magics"""
610 """Match magics"""
596 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
611 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
597 # Get all shell magics now rather than statically, so magics loaded at
612 # Get all shell magics now rather than statically, so magics loaded at
598 # runtime show up too
613 # runtime show up too
599 magics = self.shell.lsmagic()
614 magics = self.shell.lsmagic()
600 pre = self.magic_escape
615 pre = self.magic_escape
601 baretext = text.lstrip(pre)
616 baretext = text.lstrip(pre)
602 return [ pre+m for m in magics if m.startswith(baretext)]
617 return [ pre+m for m in magics if m.startswith(baretext)]
603
618
604 def alias_matches(self, text):
619 def alias_matches(self, text):
605 """Match internal system aliases"""
620 """Match internal system aliases"""
606 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
621 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
607
622
608 # if we are not in the first 'item', alias matching
623 # if we are not in the first 'item', alias matching
609 # doesn't make sense - unless we are starting with 'sudo' command.
624 # doesn't make sense - unless we are starting with 'sudo' command.
610 main_text = self.text_until_cursor.lstrip()
625 main_text = self.text_until_cursor.lstrip()
611 if ' ' in main_text and not main_text.startswith('sudo'):
626 if ' ' in main_text and not main_text.startswith('sudo'):
612 return []
627 return []
613 text = os.path.expanduser(text)
628 text = os.path.expanduser(text)
614 aliases = self.alias_table.keys()
629 aliases = self.alias_table.keys()
615 if text == '':
630 if text == '':
616 return aliases
631 return aliases
617 else:
632 else:
618 return [a for a in aliases if a.startswith(text)]
633 return [a for a in aliases if a.startswith(text)]
619
634
620 def python_matches(self,text):
635 def python_matches(self,text):
621 """Match attributes or global python names"""
636 """Match attributes or global python names"""
622
637
623 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
638 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
624 if "." in text:
639 if "." in text:
625 try:
640 try:
626 matches = self.attr_matches(text)
641 matches = self.attr_matches(text)
627 if text.endswith('.') and self.omit__names:
642 if text.endswith('.') and self.omit__names:
628 if self.omit__names == 1:
643 if self.omit__names == 1:
629 # true if txt is _not_ a __ name, false otherwise:
644 # true if txt is _not_ a __ name, false otherwise:
630 no__name = (lambda txt:
645 no__name = (lambda txt:
631 re.match(r'.*\.__.*?__',txt) is None)
646 re.match(r'.*\.__.*?__',txt) is None)
632 else:
647 else:
633 # true if txt is _not_ a _ name, false otherwise:
648 # true if txt is _not_ a _ name, false otherwise:
634 no__name = (lambda txt:
649 no__name = (lambda txt:
635 re.match(r'.*\._.*?',txt) is None)
650 re.match(r'.*\._.*?',txt) is None)
636 matches = filter(no__name, matches)
651 matches = filter(no__name, matches)
637 except NameError:
652 except NameError:
638 # catches <undefined attributes>.<tab>
653 # catches <undefined attributes>.<tab>
639 matches = []
654 matches = []
640 else:
655 else:
641 matches = self.global_matches(text)
656 matches = self.global_matches(text)
642
657
643 return matches
658 return matches
644
659
645 def _default_arguments(self, obj):
660 def _default_arguments(self, obj):
646 """Return the list of default arguments of obj if it is callable,
661 """Return the list of default arguments of obj if it is callable,
647 or empty list otherwise."""
662 or empty list otherwise."""
648
663
649 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
664 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
650 # for classes, check for __init__,__new__
665 # for classes, check for __init__,__new__
651 if inspect.isclass(obj):
666 if inspect.isclass(obj):
652 obj = (getattr(obj,'__init__',None) or
667 obj = (getattr(obj,'__init__',None) or
653 getattr(obj,'__new__',None))
668 getattr(obj,'__new__',None))
654 # for all others, check if they are __call__able
669 # for all others, check if they are __call__able
655 elif hasattr(obj, '__call__'):
670 elif hasattr(obj, '__call__'):
656 obj = obj.__call__
671 obj = obj.__call__
657 # XXX: is there a way to handle the builtins ?
672 # XXX: is there a way to handle the builtins ?
658 try:
673 try:
659 args,_,_1,defaults = inspect.getargspec(obj)
674 args,_,_1,defaults = inspect.getargspec(obj)
660 if defaults:
675 if defaults:
661 return args[-len(defaults):]
676 return args[-len(defaults):]
662 except TypeError: pass
677 except TypeError: pass
663 return []
678 return []
664
679
665 def python_func_kw_matches(self,text):
680 def python_func_kw_matches(self,text):
666 """Match named parameters (kwargs) of the last open function"""
681 """Match named parameters (kwargs) of the last open function"""
667
682
668 if "." in text: # a parameter cannot be dotted
683 if "." in text: # a parameter cannot be dotted
669 return []
684 return []
670 try: regexp = self.__funcParamsRegex
685 try: regexp = self.__funcParamsRegex
671 except AttributeError:
686 except AttributeError:
672 regexp = self.__funcParamsRegex = re.compile(r'''
687 regexp = self.__funcParamsRegex = re.compile(r'''
673 '.*?' | # single quoted strings or
688 '.*?' | # single quoted strings or
674 ".*?" | # double quoted strings or
689 ".*?" | # double quoted strings or
675 \w+ | # identifier
690 \w+ | # identifier
676 \S # other characters
691 \S # other characters
677 ''', re.VERBOSE | re.DOTALL)
692 ''', re.VERBOSE | re.DOTALL)
678 # 1. find the nearest identifier that comes before an unclosed
693 # 1. find the nearest identifier that comes before an unclosed
679 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
694 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
680 tokens = regexp.findall(self.line_buffer)
695 tokens = regexp.findall(self.line_buffer)
681 tokens.reverse()
696 tokens.reverse()
682 iterTokens = iter(tokens); openPar = 0
697 iterTokens = iter(tokens); openPar = 0
683 for token in iterTokens:
698 for token in iterTokens:
684 if token == ')':
699 if token == ')':
685 openPar -= 1
700 openPar -= 1
686 elif token == '(':
701 elif token == '(':
687 openPar += 1
702 openPar += 1
688 if openPar > 0:
703 if openPar > 0:
689 # found the last unclosed parenthesis
704 # found the last unclosed parenthesis
690 break
705 break
691 else:
706 else:
692 return []
707 return []
693 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
708 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
694 ids = []
709 ids = []
695 isId = re.compile(r'\w+$').match
710 isId = re.compile(r'\w+$').match
696 while True:
711 while True:
697 try:
712 try:
698 ids.append(iterTokens.next())
713 ids.append(iterTokens.next())
699 if not isId(ids[-1]):
714 if not isId(ids[-1]):
700 ids.pop(); break
715 ids.pop(); break
701 if not iterTokens.next() == '.':
716 if not iterTokens.next() == '.':
702 break
717 break
703 except StopIteration:
718 except StopIteration:
704 break
719 break
705 # lookup the candidate callable matches either using global_matches
720 # lookup the candidate callable matches either using global_matches
706 # or attr_matches for dotted names
721 # or attr_matches for dotted names
707 if len(ids) == 1:
722 if len(ids) == 1:
708 callableMatches = self.global_matches(ids[0])
723 callableMatches = self.global_matches(ids[0])
709 else:
724 else:
710 callableMatches = self.attr_matches('.'.join(ids[::-1]))
725 callableMatches = self.attr_matches('.'.join(ids[::-1]))
711 argMatches = []
726 argMatches = []
712 for callableMatch in callableMatches:
727 for callableMatch in callableMatches:
713 try:
728 try:
714 namedArgs = self._default_arguments(eval(callableMatch,
729 namedArgs = self._default_arguments(eval(callableMatch,
715 self.namespace))
730 self.namespace))
716 except:
731 except:
717 continue
732 continue
718 for namedArg in namedArgs:
733 for namedArg in namedArgs:
719 if namedArg.startswith(text):
734 if namedArg.startswith(text):
720 argMatches.append("%s=" %namedArg)
735 argMatches.append("%s=" %namedArg)
721 return argMatches
736 return argMatches
722
737
723 def dispatch_custom_completer(self, text):
738 def dispatch_custom_completer(self, text):
724 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
739 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
725 line = self.line_buffer
740 line = self.line_buffer
726 if not line.strip():
741 if not line.strip():
727 return None
742 return None
728
743
729 # Create a little structure to pass all the relevant information about
744 # Create a little structure to pass all the relevant information about
730 # the current completion to any custom completer.
745 # the current completion to any custom completer.
731 event = Bunch()
746 event = Bunch()
732 event.line = line
747 event.line = line
733 event.symbol = text
748 event.symbol = text
734 cmd = line.split(None,1)[0]
749 cmd = line.split(None,1)[0]
735 event.command = cmd
750 event.command = cmd
736 event.text_until_cursor = self.text_until_cursor
751 event.text_until_cursor = self.text_until_cursor
737
752
738 #print "\ncustom:{%s]\n" % event # dbg
753 #print "\ncustom:{%s]\n" % event # dbg
739
754
740 # for foo etc, try also to find completer for %foo
755 # for foo etc, try also to find completer for %foo
741 if not cmd.startswith(self.magic_escape):
756 if not cmd.startswith(self.magic_escape):
742 try_magic = self.custom_completers.s_matches(
757 try_magic = self.custom_completers.s_matches(
743 self.magic_escape + cmd)
758 self.magic_escape + cmd)
744 else:
759 else:
745 try_magic = []
760 try_magic = []
746
761
747 for c in itertools.chain(self.custom_completers.s_matches(cmd),
762 for c in itertools.chain(self.custom_completers.s_matches(cmd),
748 try_magic,
763 try_magic,
749 self.custom_completers.flat_matches(self.text_until_cursor)):
764 self.custom_completers.flat_matches(self.text_until_cursor)):
750 #print "try",c # dbg
765 #print "try",c # dbg
751 try:
766 try:
752 res = c(event)
767 res = c(event)
753 if res:
768 if res:
754 # first, try case sensitive match
769 # first, try case sensitive match
755 withcase = [r for r in res if r.startswith(text)]
770 withcase = [r for r in res if r.startswith(text)]
756 if withcase:
771 if withcase:
757 return withcase
772 return withcase
758 # if none, then case insensitive ones are ok too
773 # if none, then case insensitive ones are ok too
759 text_low = text.lower()
774 text_low = text.lower()
760 return [r for r in res if r.lower().startswith(text_low)]
775 return [r for r in res if r.lower().startswith(text_low)]
761 except TryNext:
776 except TryNext:
762 pass
777 pass
763
778
764 return None
779 return None
765
780
766 def complete(self, text=None, line_buffer=None, cursor_pos=None):
781 def complete(self, text=None, line_buffer=None, cursor_pos=None):
767 """Find completions for the given text and line context.
782 """Find completions for the given text and line context.
768
783
769 This is called successively with state == 0, 1, 2, ... until it
784 This is called successively with state == 0, 1, 2, ... until it
770 returns None. The completion should begin with 'text'.
785 returns None. The completion should begin with 'text'.
771
786
772 Note that both the text and the line_buffer are optional, but at least
787 Note that both the text and the line_buffer are optional, but at least
773 one of them must be given.
788 one of them must be given.
774
789
775 Parameters
790 Parameters
776 ----------
791 ----------
777 text : string, optional
792 text : string, optional
778 Text to perform the completion on. If not given, the line buffer
793 Text to perform the completion on. If not given, the line buffer
779 is split using the instance's CompletionSplitter object.
794 is split using the instance's CompletionSplitter object.
780
795
781 line_buffer : string, optional
796 line_buffer : string, optional
782 If not given, the completer attempts to obtain the current line
797 If not given, the completer attempts to obtain the current line
783 buffer via readline. This keyword allows clients which are
798 buffer via readline. This keyword allows clients which are
784 requesting for text completions in non-readline contexts to inform
799 requesting for text completions in non-readline contexts to inform
785 the completer of the entire text.
800 the completer of the entire text.
786
801
787 cursor_pos : int, optional
802 cursor_pos : int, optional
788 Index of the cursor in the full line buffer. Should be provided by
803 Index of the cursor in the full line buffer. Should be provided by
789 remote frontends where kernel has no access to frontend state.
804 remote frontends where kernel has no access to frontend state.
790
805
791 Returns
806 Returns
792 -------
807 -------
793 text : str
808 text : str
794 Text that was actually used in the completion.
809 Text that was actually used in the completion.
795
810
796 matches : list
811 matches : list
797 A list of completion matches.
812 A list of completion matches.
798 """
813 """
799 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
814 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
800
815
801 # if the cursor position isn't given, the only sane assumption we can
816 # if the cursor position isn't given, the only sane assumption we can
802 # make is that it's at the end of the line (the common case)
817 # make is that it's at the end of the line (the common case)
803 if cursor_pos is None:
818 if cursor_pos is None:
804 cursor_pos = len(line_buffer) if text is None else len(text)
819 cursor_pos = len(line_buffer) if text is None else len(text)
805
820
806 # if text is either None or an empty string, rely on the line buffer
821 # if text is either None or an empty string, rely on the line buffer
807 if not text:
822 if not text:
808 text = self.splitter.split_line(line_buffer, cursor_pos)
823 text = self.splitter.split_line(line_buffer, cursor_pos)
809
824
810 # If no line buffer is given, assume the input text is all there was
825 # If no line buffer is given, assume the input text is all there was
811 if line_buffer is None:
826 if line_buffer is None:
812 line_buffer = text
827 line_buffer = text
813
828
814 self.line_buffer = line_buffer
829 self.line_buffer = line_buffer
815 self.text_until_cursor = self.line_buffer[:cursor_pos]
830 self.text_until_cursor = self.line_buffer[:cursor_pos]
816 #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
831 #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
817
832
818 # Start with a clean slate of completions
833 # Start with a clean slate of completions
819 self.matches[:] = []
834 self.matches[:] = []
820 custom_res = self.dispatch_custom_completer(text)
835 custom_res = self.dispatch_custom_completer(text)
821 if custom_res is not None:
836 if custom_res is not None:
822 # did custom completers produce something?
837 # did custom completers produce something?
823 self.matches = custom_res
838 self.matches = custom_res
824 else:
839 else:
825 # Extend the list of completions with the results of each
840 # Extend the list of completions with the results of each
826 # matcher, so we return results to the user from all
841 # matcher, so we return results to the user from all
827 # namespaces.
842 # namespaces.
828 if self.merge_completions:
843 if self.merge_completions:
829 self.matches = []
844 self.matches = []
830 for matcher in self.matchers:
845 for matcher in self.matchers:
831 try:
846 try:
832 self.matches.extend(matcher(text))
847 self.matches.extend(matcher(text))
833 except:
848 except:
834 # Show the ugly traceback if the matcher causes an
849 # Show the ugly traceback if the matcher causes an
835 # exception, but do NOT crash the kernel!
850 # exception, but do NOT crash the kernel!
836 sys.excepthook(*sys.exc_info())
851 sys.excepthook(*sys.exc_info())
837 else:
852 else:
838 for matcher in self.matchers:
853 for matcher in self.matchers:
839 self.matches = matcher(text)
854 self.matches = matcher(text)
840 if self.matches:
855 if self.matches:
841 break
856 break
842 # FIXME: we should extend our api to return a dict with completions for
857 # FIXME: we should extend our api to return a dict with completions for
843 # different types of objects. The rlcomplete() method could then
858 # different types of objects. The rlcomplete() method could then
844 # simply collapse the dict into a list for readline, but we'd have
859 # simply collapse the dict into a list for readline, but we'd have
845 # richer completion semantics in other evironments.
860 # richer completion semantics in other evironments.
846 self.matches = sorted(set(self.matches))
861 self.matches = sorted(set(self.matches))
847 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
862 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
848 return text, self.matches
863 return text, self.matches
849
864
850 def rlcomplete(self, text, state):
865 def rlcomplete(self, text, state):
851 """Return the state-th possible completion for 'text'.
866 """Return the state-th possible completion for 'text'.
852
867
853 This is called successively with state == 0, 1, 2, ... until it
868 This is called successively with state == 0, 1, 2, ... until it
854 returns None. The completion should begin with 'text'.
869 returns None. The completion should begin with 'text'.
855
870
856 Parameters
871 Parameters
857 ----------
872 ----------
858 text : string
873 text : string
859 Text to perform the completion on.
874 Text to perform the completion on.
860
875
861 state : int
876 state : int
862 Counter used by readline.
877 Counter used by readline.
863 """
878 """
864 if state==0:
879 if state==0:
865
880
866 self.line_buffer = line_buffer = self.readline.get_line_buffer()
881 self.line_buffer = line_buffer = self.readline.get_line_buffer()
867 cursor_pos = self.readline.get_endidx()
882 cursor_pos = self.readline.get_endidx()
868
883
869 #io.rprint("\nRLCOMPLETE: %r %r %r" %
884 #io.rprint("\nRLCOMPLETE: %r %r %r" %
870 # (text, line_buffer, cursor_pos) ) # dbg
885 # (text, line_buffer, cursor_pos) ) # dbg
871
886
872 # if there is only a tab on a line with only whitespace, instead of
887 # if there is only a tab on a line with only whitespace, instead of
873 # the mostly useless 'do you want to see all million completions'
888 # the mostly useless 'do you want to see all million completions'
874 # message, just do the right thing and give the user his tab!
889 # message, just do the right thing and give the user his tab!
875 # Incidentally, this enables pasting of tabbed text from an editor
890 # Incidentally, this enables pasting of tabbed text from an editor
876 # (as long as autoindent is off).
891 # (as long as autoindent is off).
877
892
878 # It should be noted that at least pyreadline still shows file
893 # It should be noted that at least pyreadline still shows file
879 # completions - is there a way around it?
894 # completions - is there a way around it?
880
895
881 # don't apply this on 'dumb' terminals, such as emacs buffers, so
896 # don't apply this on 'dumb' terminals, such as emacs buffers, so
882 # we don't interfere with their own tab-completion mechanism.
897 # we don't interfere with their own tab-completion mechanism.
883 if not (self.dumb_terminal or line_buffer.strip()):
898 if not (self.dumb_terminal or line_buffer.strip()):
884 self.readline.insert_text('\t')
899 self.readline.insert_text('\t')
885 sys.stdout.flush()
900 sys.stdout.flush()
886 return None
901 return None
887
902
888 # Note: debugging exceptions that may occur in completion is very
903 # Note: debugging exceptions that may occur in completion is very
889 # tricky, because readline unconditionally silences them. So if
904 # tricky, because readline unconditionally silences them. So if
890 # during development you suspect a bug in the completion code, turn
905 # during development you suspect a bug in the completion code, turn
891 # this flag on temporarily by uncommenting the second form (don't
906 # this flag on temporarily by uncommenting the second form (don't
892 # flip the value in the first line, as the '# dbg' marker can be
907 # flip the value in the first line, as the '# dbg' marker can be
893 # automatically detected and is used elsewhere).
908 # automatically detected and is used elsewhere).
894 DEBUG = False
909 DEBUG = False
895 #DEBUG = True # dbg
910 #DEBUG = True # dbg
896 if DEBUG:
911 if DEBUG:
897 try:
912 try:
898 self.complete(text, line_buffer, cursor_pos)
913 self.complete(text, line_buffer, cursor_pos)
899 except:
914 except:
900 import traceback; traceback.print_exc()
915 import traceback; traceback.print_exc()
901 else:
916 else:
902 # The normal production version is here
917 # The normal production version is here
903
918
904 # This method computes the self.matches array
919 # This method computes the self.matches array
905 self.complete(text, line_buffer, cursor_pos)
920 self.complete(text, line_buffer, cursor_pos)
906
921
907 try:
922 try:
908 return self.matches[state]
923 return self.matches[state]
909 except IndexError:
924 except IndexError:
910 return None
925 return None
@@ -1,2695 +1,2692 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__ as builtin_mod
20 import __builtin__ as builtin_mod
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import codeop
25 import codeop
26 import inspect
26 import inspect
27 import os
27 import os
28 import re
28 import re
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32 try:
32 try:
33 from contextlib import nested
33 from contextlib import nested
34 except:
34 except:
35 from IPython.utils.nested_context import nested
35 from IPython.utils.nested_context import nested
36
36
37 from IPython.config.configurable import SingletonConfigurable
37 from IPython.config.configurable import SingletonConfigurable
38 from IPython.core import debugger, oinspect
38 from IPython.core import debugger, oinspect
39 from IPython.core import history as ipcorehist
39 from IPython.core import history as ipcorehist
40 from IPython.core import page
40 from IPython.core import page
41 from IPython.core import prefilter
41 from IPython.core import prefilter
42 from IPython.core import shadowns
42 from IPython.core import shadowns
43 from IPython.core import ultratb
43 from IPython.core import ultratb
44 from IPython.core.alias import AliasManager, AliasError
44 from IPython.core.alias import AliasManager, AliasError
45 from IPython.core.autocall import ExitAutocall
45 from IPython.core.autocall import ExitAutocall
46 from IPython.core.builtin_trap import BuiltinTrap
46 from IPython.core.builtin_trap import BuiltinTrap
47 from IPython.core.compilerop import CachingCompiler
47 from IPython.core.compilerop import CachingCompiler
48 from IPython.core.display_trap import DisplayTrap
48 from IPython.core.display_trap import DisplayTrap
49 from IPython.core.displayhook import DisplayHook
49 from IPython.core.displayhook import DisplayHook
50 from IPython.core.displaypub import DisplayPublisher
50 from IPython.core.displaypub import DisplayPublisher
51 from IPython.core.error import TryNext, UsageError
51 from IPython.core.error import TryNext, UsageError
52 from IPython.core.extensions import ExtensionManager
52 from IPython.core.extensions import ExtensionManager
53 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
53 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
54 from IPython.core.formatters import DisplayFormatter
54 from IPython.core.formatters import DisplayFormatter
55 from IPython.core.history import HistoryManager
55 from IPython.core.history import HistoryManager
56 from IPython.core.inputsplitter import IPythonInputSplitter
56 from IPython.core.inputsplitter import IPythonInputSplitter
57 from IPython.core.logger import Logger
57 from IPython.core.logger import Logger
58 from IPython.core.macro import Macro
58 from IPython.core.macro import Macro
59 from IPython.core.magic import Magic
59 from IPython.core.magic import Magic
60 from IPython.core.payload import PayloadManager
60 from IPython.core.payload import PayloadManager
61 from IPython.core.plugin import PluginManager
61 from IPython.core.plugin import PluginManager
62 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
62 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
63 from IPython.core.profiledir import ProfileDir
63 from IPython.core.profiledir import ProfileDir
64 from IPython.external.Itpl import ItplNS
64 from IPython.external.Itpl import ItplNS
65 from IPython.utils import PyColorize
65 from IPython.utils import PyColorize
66 from IPython.utils import io
66 from IPython.utils import io
67 from IPython.utils import py3compat
67 from IPython.utils import py3compat
68 from IPython.utils.doctestreload import doctest_reload
68 from IPython.utils.doctestreload import doctest_reload
69 from IPython.utils.io import ask_yes_no, rprint
69 from IPython.utils.io import ask_yes_no, rprint
70 from IPython.utils.ipstruct import Struct
70 from IPython.utils.ipstruct import Struct
71 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
71 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
72 from IPython.utils.pickleshare import PickleShareDB
72 from IPython.utils.pickleshare import PickleShareDB
73 from IPython.utils.process import system, getoutput
73 from IPython.utils.process import system, getoutput
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 num_ini_spaces, format_screen, LSString, SList
76 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
77 from IPython.utils.traitlets import (Int, CBool, CaselessStrEnum, Enum,
77 from IPython.utils.traitlets import (Int, CBool, CaselessStrEnum, Enum,
78 List, Unicode, Instance, Type)
78 List, Unicode, Instance, Type)
79 from IPython.utils.warn import warn, error, fatal
79 from IPython.utils.warn import warn, error, fatal
80 import IPython.core.hooks
80 import IPython.core.hooks
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 # Globals
83 # Globals
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85
85
86 # compiled regexps for autoindent management
86 # compiled regexps for autoindent management
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88
88
89 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
90 # Utilities
90 # Utilities
91 #-----------------------------------------------------------------------------
91 #-----------------------------------------------------------------------------
92
92
93 def softspace(file, newvalue):
93 def softspace(file, newvalue):
94 """Copied from code.py, to remove the dependency"""
94 """Copied from code.py, to remove the dependency"""
95
95
96 oldvalue = 0
96 oldvalue = 0
97 try:
97 try:
98 oldvalue = file.softspace
98 oldvalue = file.softspace
99 except AttributeError:
99 except AttributeError:
100 pass
100 pass
101 try:
101 try:
102 file.softspace = newvalue
102 file.softspace = newvalue
103 except (AttributeError, TypeError):
103 except (AttributeError, TypeError):
104 # "attribute-less object" or "read-only attributes"
104 # "attribute-less object" or "read-only attributes"
105 pass
105 pass
106 return oldvalue
106 return oldvalue
107
107
108
108
109 def no_op(*a, **kw): pass
109 def no_op(*a, **kw): pass
110
110
111 class NoOpContext(object):
111 class NoOpContext(object):
112 def __enter__(self): pass
112 def __enter__(self): pass
113 def __exit__(self, type, value, traceback): pass
113 def __exit__(self, type, value, traceback): pass
114 no_op_context = NoOpContext()
114 no_op_context = NoOpContext()
115
115
116 class SpaceInInput(Exception): pass
116 class SpaceInInput(Exception): pass
117
117
118 class Bunch: pass
118 class Bunch: pass
119
119
120
120
121 def get_default_colors():
121 def get_default_colors():
122 if sys.platform=='darwin':
122 if sys.platform=='darwin':
123 return "LightBG"
123 return "LightBG"
124 elif os.name=='nt':
124 elif os.name=='nt':
125 return 'Linux'
125 return 'Linux'
126 else:
126 else:
127 return 'Linux'
127 return 'Linux'
128
128
129
129
130 class SeparateUnicode(Unicode):
130 class SeparateUnicode(Unicode):
131 """A Unicode subclass to validate separate_in, separate_out, etc.
131 """A Unicode subclass to validate separate_in, separate_out, etc.
132
132
133 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
133 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
134 """
134 """
135
135
136 def validate(self, obj, value):
136 def validate(self, obj, value):
137 if value == '0': value = ''
137 if value == '0': value = ''
138 value = value.replace('\\n','\n')
138 value = value.replace('\\n','\n')
139 return super(SeparateUnicode, self).validate(obj, value)
139 return super(SeparateUnicode, self).validate(obj, value)
140
140
141
141
142 class ReadlineNoRecord(object):
142 class ReadlineNoRecord(object):
143 """Context manager to execute some code, then reload readline history
143 """Context manager to execute some code, then reload readline history
144 so that interactive input to the code doesn't appear when pressing up."""
144 so that interactive input to the code doesn't appear when pressing up."""
145 def __init__(self, shell):
145 def __init__(self, shell):
146 self.shell = shell
146 self.shell = shell
147 self._nested_level = 0
147 self._nested_level = 0
148
148
149 def __enter__(self):
149 def __enter__(self):
150 if self._nested_level == 0:
150 if self._nested_level == 0:
151 try:
151 try:
152 self.orig_length = self.current_length()
152 self.orig_length = self.current_length()
153 self.readline_tail = self.get_readline_tail()
153 self.readline_tail = self.get_readline_tail()
154 except (AttributeError, IndexError): # Can fail with pyreadline
154 except (AttributeError, IndexError): # Can fail with pyreadline
155 self.orig_length, self.readline_tail = 999999, []
155 self.orig_length, self.readline_tail = 999999, []
156 self._nested_level += 1
156 self._nested_level += 1
157
157
158 def __exit__(self, type, value, traceback):
158 def __exit__(self, type, value, traceback):
159 self._nested_level -= 1
159 self._nested_level -= 1
160 if self._nested_level == 0:
160 if self._nested_level == 0:
161 # Try clipping the end if it's got longer
161 # Try clipping the end if it's got longer
162 try:
162 try:
163 e = self.current_length() - self.orig_length
163 e = self.current_length() - self.orig_length
164 if e > 0:
164 if e > 0:
165 for _ in range(e):
165 for _ in range(e):
166 self.shell.readline.remove_history_item(self.orig_length)
166 self.shell.readline.remove_history_item(self.orig_length)
167
167
168 # If it still doesn't match, just reload readline history.
168 # If it still doesn't match, just reload readline history.
169 if self.current_length() != self.orig_length \
169 if self.current_length() != self.orig_length \
170 or self.get_readline_tail() != self.readline_tail:
170 or self.get_readline_tail() != self.readline_tail:
171 self.shell.refill_readline_hist()
171 self.shell.refill_readline_hist()
172 except (AttributeError, IndexError):
172 except (AttributeError, IndexError):
173 pass
173 pass
174 # Returning False will cause exceptions to propagate
174 # Returning False will cause exceptions to propagate
175 return False
175 return False
176
176
177 def current_length(self):
177 def current_length(self):
178 return self.shell.readline.get_current_history_length()
178 return self.shell.readline.get_current_history_length()
179
179
180 def get_readline_tail(self, n=10):
180 def get_readline_tail(self, n=10):
181 """Get the last n items in readline history."""
181 """Get the last n items in readline history."""
182 end = self.shell.readline.get_current_history_length() + 1
182 end = self.shell.readline.get_current_history_length() + 1
183 start = max(end-n, 1)
183 start = max(end-n, 1)
184 ghi = self.shell.readline.get_history_item
184 ghi = self.shell.readline.get_history_item
185 return [ghi(x) for x in range(start, end)]
185 return [ghi(x) for x in range(start, end)]
186
186
187
187
188 _autocall_help = """
188 _autocall_help = """
189 Make IPython automatically call any callable object even if
189 Make IPython automatically call any callable object even if
190 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
190 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
191 automatically. The value can be '0' to disable the feature, '1' for 'smart'
191 automatically. The value can be '0' to disable the feature, '1' for 'smart'
192 autocall, where it is not applied if there are no more arguments on the line,
192 autocall, where it is not applied if there are no more arguments on the line,
193 and '2' for 'full' autocall, where all callable objects are automatically
193 and '2' for 'full' autocall, where all callable objects are automatically
194 called (even if no arguments are present). The default is '1'.
194 called (even if no arguments are present). The default is '1'.
195 """
195 """
196
196
197 #-----------------------------------------------------------------------------
197 #-----------------------------------------------------------------------------
198 # Main IPython class
198 # Main IPython class
199 #-----------------------------------------------------------------------------
199 #-----------------------------------------------------------------------------
200
200
201 class InteractiveShell(SingletonConfigurable, Magic):
201 class InteractiveShell(SingletonConfigurable, Magic):
202 """An enhanced, interactive shell for Python."""
202 """An enhanced, interactive shell for Python."""
203
203
204 _instance = None
204 _instance = None
205
205
206 autocall = Enum((0,1,2), default_value=1, config=True, help=
206 autocall = Enum((0,1,2), default_value=1, config=True, help=
207 """
207 """
208 Make IPython automatically call any callable object even if you didn't
208 Make IPython automatically call any callable object even if you didn't
209 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
209 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
210 automatically. The value can be '0' to disable the feature, '1' for
210 automatically. The value can be '0' to disable the feature, '1' for
211 'smart' autocall, where it is not applied if there are no more
211 'smart' autocall, where it is not applied if there are no more
212 arguments on the line, and '2' for 'full' autocall, where all callable
212 arguments on the line, and '2' for 'full' autocall, where all callable
213 objects are automatically called (even if no arguments are present).
213 objects are automatically called (even if no arguments are present).
214 The default is '1'.
214 The default is '1'.
215 """
215 """
216 )
216 )
217 # TODO: remove all autoindent logic and put into frontends.
217 # TODO: remove all autoindent logic and put into frontends.
218 # We can't do this yet because even runlines uses the autoindent.
218 # We can't do this yet because even runlines uses the autoindent.
219 autoindent = CBool(True, config=True, help=
219 autoindent = CBool(True, config=True, help=
220 """
220 """
221 Autoindent IPython code entered interactively.
221 Autoindent IPython code entered interactively.
222 """
222 """
223 )
223 )
224 automagic = CBool(True, config=True, help=
224 automagic = CBool(True, config=True, help=
225 """
225 """
226 Enable magic commands to be called without the leading %.
226 Enable magic commands to be called without the leading %.
227 """
227 """
228 )
228 )
229 cache_size = Int(1000, config=True, help=
229 cache_size = Int(1000, config=True, help=
230 """
230 """
231 Set the size of the output cache. The default is 1000, you can
231 Set the size of the output cache. The default is 1000, you can
232 change it permanently in your config file. Setting it to 0 completely
232 change it permanently in your config file. Setting it to 0 completely
233 disables the caching system, and the minimum value accepted is 20 (if
233 disables the caching system, and the minimum value accepted is 20 (if
234 you provide a value less than 20, it is reset to 0 and a warning is
234 you provide a value less than 20, it is reset to 0 and a warning is
235 issued). This limit is defined because otherwise you'll spend more
235 issued). This limit is defined because otherwise you'll spend more
236 time re-flushing a too small cache than working
236 time re-flushing a too small cache than working
237 """
237 """
238 )
238 )
239 color_info = CBool(True, config=True, help=
239 color_info = CBool(True, config=True, help=
240 """
240 """
241 Use colors for displaying information about objects. Because this
241 Use colors for displaying information about objects. Because this
242 information is passed through a pager (like 'less'), and some pagers
242 information is passed through a pager (like 'less'), and some pagers
243 get confused with color codes, this capability can be turned off.
243 get confused with color codes, this capability can be turned off.
244 """
244 """
245 )
245 )
246 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
246 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
247 default_value=get_default_colors(), config=True,
247 default_value=get_default_colors(), config=True,
248 help="Set the color scheme (NoColor, Linux, or LightBG)."
248 help="Set the color scheme (NoColor, Linux, or LightBG)."
249 )
249 )
250 colors_force = CBool(False, help=
250 colors_force = CBool(False, help=
251 """
251 """
252 Force use of ANSI color codes, regardless of OS and readline
252 Force use of ANSI color codes, regardless of OS and readline
253 availability.
253 availability.
254 """
254 """
255 # FIXME: This is essentially a hack to allow ZMQShell to show colors
255 # FIXME: This is essentially a hack to allow ZMQShell to show colors
256 # without readline on Win32. When the ZMQ formatting system is
256 # without readline on Win32. When the ZMQ formatting system is
257 # refactored, this should be removed.
257 # refactored, this should be removed.
258 )
258 )
259 debug = CBool(False, config=True)
259 debug = CBool(False, config=True)
260 deep_reload = CBool(False, config=True, help=
260 deep_reload = CBool(False, config=True, help=
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 )
270 )
271 display_formatter = Instance(DisplayFormatter)
271 display_formatter = Instance(DisplayFormatter)
272 displayhook_class = Type(DisplayHook)
272 displayhook_class = Type(DisplayHook)
273 display_pub_class = Type(DisplayPublisher)
273 display_pub_class = Type(DisplayPublisher)
274
274
275 exit_now = CBool(False)
275 exit_now = CBool(False)
276 exiter = Instance(ExitAutocall)
276 exiter = Instance(ExitAutocall)
277 def _exiter_default(self):
277 def _exiter_default(self):
278 return ExitAutocall(self)
278 return ExitAutocall(self)
279 # Monotonically increasing execution counter
279 # Monotonically increasing execution counter
280 execution_count = Int(1)
280 execution_count = Int(1)
281 filename = Unicode("<ipython console>")
281 filename = Unicode("<ipython console>")
282 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
282 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
283
283
284 # Input splitter, to split entire cells of input into either individual
284 # Input splitter, to split entire cells of input into either individual
285 # interactive statements or whole blocks.
285 # interactive statements or whole blocks.
286 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
286 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
287 (), {})
287 (), {})
288 logstart = CBool(False, config=True, help=
288 logstart = CBool(False, config=True, help=
289 """
289 """
290 Start logging to the default log file.
290 Start logging to the default log file.
291 """
291 """
292 )
292 )
293 logfile = Unicode('', config=True, help=
293 logfile = Unicode('', config=True, help=
294 """
294 """
295 The name of the logfile to use.
295 The name of the logfile to use.
296 """
296 """
297 )
297 )
298 logappend = Unicode('', config=True, help=
298 logappend = Unicode('', config=True, help=
299 """
299 """
300 Start logging to the given file in append mode.
300 Start logging to the given file in append mode.
301 """
301 """
302 )
302 )
303 object_info_string_level = Enum((0,1,2), default_value=0,
303 object_info_string_level = Enum((0,1,2), default_value=0,
304 config=True)
304 config=True)
305 pdb = CBool(False, config=True, help=
305 pdb = CBool(False, config=True, help=
306 """
306 """
307 Automatically call the pdb debugger after every exception.
307 Automatically call the pdb debugger after every exception.
308 """
308 """
309 )
309 )
310 multiline_history = CBool(sys.platform != 'win32', config=True,
310 multiline_history = CBool(sys.platform != 'win32', config=True,
311 help="Store multiple line spanning cells as a single entry in history."
311 help="Store multiple line spanning cells as a single entry in history."
312 )
312 )
313
313
314 prompt_in1 = Unicode('In [\\#]: ', config=True)
314 prompt_in1 = Unicode('In [\\#]: ', config=True)
315 prompt_in2 = Unicode(' .\\D.: ', config=True)
315 prompt_in2 = Unicode(' .\\D.: ', config=True)
316 prompt_out = Unicode('Out[\\#]: ', config=True)
316 prompt_out = Unicode('Out[\\#]: ', config=True)
317 prompts_pad_left = CBool(True, config=True)
317 prompts_pad_left = CBool(True, config=True)
318 quiet = CBool(False, config=True)
318 quiet = CBool(False, config=True)
319
319
320 history_length = Int(10000, config=True)
320 history_length = Int(10000, config=True)
321
321
322 # The readline stuff will eventually be moved to the terminal subclass
322 # The readline stuff will eventually be moved to the terminal subclass
323 # but for now, we can't do that as readline is welded in everywhere.
323 # but for now, we can't do that as readline is welded in everywhere.
324 readline_use = CBool(True, config=True)
324 readline_use = CBool(True, config=True)
325 readline_merge_completions = CBool(True, config=True)
326 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
327 readline_remove_delims = Unicode('-/~', config=True)
325 readline_remove_delims = Unicode('-/~', config=True)
328 # don't use \M- bindings by default, because they
326 # don't use \M- bindings by default, because they
329 # conflict with 8-bit encodings. See gh-58,gh-88
327 # conflict with 8-bit encodings. See gh-58,gh-88
330 readline_parse_and_bind = List([
328 readline_parse_and_bind = List([
331 'tab: complete',
329 'tab: complete',
332 '"\C-l": clear-screen',
330 '"\C-l": clear-screen',
333 'set show-all-if-ambiguous on',
331 'set show-all-if-ambiguous on',
334 '"\C-o": tab-insert',
332 '"\C-o": tab-insert',
335 '"\C-r": reverse-search-history',
333 '"\C-r": reverse-search-history',
336 '"\C-s": forward-search-history',
334 '"\C-s": forward-search-history',
337 '"\C-p": history-search-backward',
335 '"\C-p": history-search-backward',
338 '"\C-n": history-search-forward',
336 '"\C-n": history-search-forward',
339 '"\e[A": history-search-backward',
337 '"\e[A": history-search-backward',
340 '"\e[B": history-search-forward',
338 '"\e[B": history-search-forward',
341 '"\C-k": kill-line',
339 '"\C-k": kill-line',
342 '"\C-u": unix-line-discard',
340 '"\C-u": unix-line-discard',
343 ], allow_none=False, config=True)
341 ], allow_none=False, config=True)
344
342
345 # TODO: this part of prompt management should be moved to the frontends.
343 # TODO: this part of prompt management should be moved to the frontends.
346 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
344 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
347 separate_in = SeparateUnicode('\n', config=True)
345 separate_in = SeparateUnicode('\n', config=True)
348 separate_out = SeparateUnicode('', config=True)
346 separate_out = SeparateUnicode('', config=True)
349 separate_out2 = SeparateUnicode('', config=True)
347 separate_out2 = SeparateUnicode('', config=True)
350 wildcards_case_sensitive = CBool(True, config=True)
348 wildcards_case_sensitive = CBool(True, config=True)
351 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
349 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
352 default_value='Context', config=True)
350 default_value='Context', config=True)
353
351
354 # Subcomponents of InteractiveShell
352 # Subcomponents of InteractiveShell
355 alias_manager = Instance('IPython.core.alias.AliasManager')
353 alias_manager = Instance('IPython.core.alias.AliasManager')
356 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
354 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
357 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
355 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
358 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
356 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
359 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
357 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
360 plugin_manager = Instance('IPython.core.plugin.PluginManager')
358 plugin_manager = Instance('IPython.core.plugin.PluginManager')
361 payload_manager = Instance('IPython.core.payload.PayloadManager')
359 payload_manager = Instance('IPython.core.payload.PayloadManager')
362 history_manager = Instance('IPython.core.history.HistoryManager')
360 history_manager = Instance('IPython.core.history.HistoryManager')
363
361
364 profile_dir = Instance('IPython.core.application.ProfileDir')
362 profile_dir = Instance('IPython.core.application.ProfileDir')
365 @property
363 @property
366 def profile(self):
364 def profile(self):
367 if self.profile_dir is not None:
365 if self.profile_dir is not None:
368 name = os.path.basename(self.profile_dir.location)
366 name = os.path.basename(self.profile_dir.location)
369 return name.replace('profile_','')
367 return name.replace('profile_','')
370
368
371
369
372 # Private interface
370 # Private interface
373 _post_execute = Instance(dict)
371 _post_execute = Instance(dict)
374
372
375 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
373 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
376 user_ns=None, user_global_ns=None,
374 user_ns=None, user_global_ns=None,
377 custom_exceptions=((), None)):
375 custom_exceptions=((), None)):
378
376
379 # This is where traits with a config_key argument are updated
377 # This is where traits with a config_key argument are updated
380 # from the values on config.
378 # from the values on config.
381 super(InteractiveShell, self).__init__(config=config)
379 super(InteractiveShell, self).__init__(config=config)
382 self.configurables = [self]
380 self.configurables = [self]
383
381
384 # These are relatively independent and stateless
382 # These are relatively independent and stateless
385 self.init_ipython_dir(ipython_dir)
383 self.init_ipython_dir(ipython_dir)
386 self.init_profile_dir(profile_dir)
384 self.init_profile_dir(profile_dir)
387 self.init_instance_attrs()
385 self.init_instance_attrs()
388 self.init_environment()
386 self.init_environment()
389
387
390 # Create namespaces (user_ns, user_global_ns, etc.)
388 # Create namespaces (user_ns, user_global_ns, etc.)
391 self.init_create_namespaces(user_ns, user_global_ns)
389 self.init_create_namespaces(user_ns, user_global_ns)
392 # This has to be done after init_create_namespaces because it uses
390 # This has to be done after init_create_namespaces because it uses
393 # something in self.user_ns, but before init_sys_modules, which
391 # something in self.user_ns, but before init_sys_modules, which
394 # is the first thing to modify sys.
392 # is the first thing to modify sys.
395 # TODO: When we override sys.stdout and sys.stderr before this class
393 # TODO: When we override sys.stdout and sys.stderr before this class
396 # is created, we are saving the overridden ones here. Not sure if this
394 # is created, we are saving the overridden ones here. Not sure if this
397 # is what we want to do.
395 # is what we want to do.
398 self.save_sys_module_state()
396 self.save_sys_module_state()
399 self.init_sys_modules()
397 self.init_sys_modules()
400
398
401 # While we're trying to have each part of the code directly access what
399 # While we're trying to have each part of the code directly access what
402 # it needs without keeping redundant references to objects, we have too
400 # it needs without keeping redundant references to objects, we have too
403 # much legacy code that expects ip.db to exist.
401 # much legacy code that expects ip.db to exist.
404 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
402 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
405
403
406 self.init_history()
404 self.init_history()
407 self.init_encoding()
405 self.init_encoding()
408 self.init_prefilter()
406 self.init_prefilter()
409
407
410 Magic.__init__(self, self)
408 Magic.__init__(self, self)
411
409
412 self.init_syntax_highlighting()
410 self.init_syntax_highlighting()
413 self.init_hooks()
411 self.init_hooks()
414 self.init_pushd_popd_magic()
412 self.init_pushd_popd_magic()
415 # self.init_traceback_handlers use to be here, but we moved it below
413 # self.init_traceback_handlers use to be here, but we moved it below
416 # because it and init_io have to come after init_readline.
414 # because it and init_io have to come after init_readline.
417 self.init_user_ns()
415 self.init_user_ns()
418 self.init_logger()
416 self.init_logger()
419 self.init_alias()
417 self.init_alias()
420 self.init_builtins()
418 self.init_builtins()
421
419
422 # pre_config_initialization
420 # pre_config_initialization
423
421
424 # The next section should contain everything that was in ipmaker.
422 # The next section should contain everything that was in ipmaker.
425 self.init_logstart()
423 self.init_logstart()
426
424
427 # The following was in post_config_initialization
425 # The following was in post_config_initialization
428 self.init_inspector()
426 self.init_inspector()
429 # init_readline() must come before init_io(), because init_io uses
427 # init_readline() must come before init_io(), because init_io uses
430 # readline related things.
428 # readline related things.
431 self.init_readline()
429 self.init_readline()
432 # We save this here in case user code replaces raw_input, but it needs
430 # We save this here in case user code replaces raw_input, but it needs
433 # to be after init_readline(), because PyPy's readline works by replacing
431 # to be after init_readline(), because PyPy's readline works by replacing
434 # raw_input.
432 # raw_input.
435 if py3compat.PY3:
433 if py3compat.PY3:
436 self.raw_input_original = input
434 self.raw_input_original = input
437 else:
435 else:
438 self.raw_input_original = raw_input
436 self.raw_input_original = raw_input
439 # init_completer must come after init_readline, because it needs to
437 # init_completer must come after init_readline, because it needs to
440 # know whether readline is present or not system-wide to configure the
438 # know whether readline is present or not system-wide to configure the
441 # completers, since the completion machinery can now operate
439 # completers, since the completion machinery can now operate
442 # independently of readline (e.g. over the network)
440 # independently of readline (e.g. over the network)
443 self.init_completer()
441 self.init_completer()
444 # TODO: init_io() needs to happen before init_traceback handlers
442 # TODO: init_io() needs to happen before init_traceback handlers
445 # because the traceback handlers hardcode the stdout/stderr streams.
443 # because the traceback handlers hardcode the stdout/stderr streams.
446 # This logic in in debugger.Pdb and should eventually be changed.
444 # This logic in in debugger.Pdb and should eventually be changed.
447 self.init_io()
445 self.init_io()
448 self.init_traceback_handlers(custom_exceptions)
446 self.init_traceback_handlers(custom_exceptions)
449 self.init_prompts()
447 self.init_prompts()
450 self.init_display_formatter()
448 self.init_display_formatter()
451 self.init_display_pub()
449 self.init_display_pub()
452 self.init_displayhook()
450 self.init_displayhook()
453 self.init_reload_doctest()
451 self.init_reload_doctest()
454 self.init_magics()
452 self.init_magics()
455 self.init_pdb()
453 self.init_pdb()
456 self.init_extension_manager()
454 self.init_extension_manager()
457 self.init_plugin_manager()
455 self.init_plugin_manager()
458 self.init_payload()
456 self.init_payload()
459 self.hooks.late_startup_hook()
457 self.hooks.late_startup_hook()
460 atexit.register(self.atexit_operations)
458 atexit.register(self.atexit_operations)
461
459
462 def get_ipython(self):
460 def get_ipython(self):
463 """Return the currently running IPython instance."""
461 """Return the currently running IPython instance."""
464 return self
462 return self
465
463
466 #-------------------------------------------------------------------------
464 #-------------------------------------------------------------------------
467 # Trait changed handlers
465 # Trait changed handlers
468 #-------------------------------------------------------------------------
466 #-------------------------------------------------------------------------
469
467
470 def _ipython_dir_changed(self, name, new):
468 def _ipython_dir_changed(self, name, new):
471 if not os.path.isdir(new):
469 if not os.path.isdir(new):
472 os.makedirs(new, mode = 0777)
470 os.makedirs(new, mode = 0777)
473
471
474 def set_autoindent(self,value=None):
472 def set_autoindent(self,value=None):
475 """Set the autoindent flag, checking for readline support.
473 """Set the autoindent flag, checking for readline support.
476
474
477 If called with no arguments, it acts as a toggle."""
475 If called with no arguments, it acts as a toggle."""
478
476
479 if value != 0 and not self.has_readline:
477 if value != 0 and not self.has_readline:
480 if os.name == 'posix':
478 if os.name == 'posix':
481 warn("The auto-indent feature requires the readline library")
479 warn("The auto-indent feature requires the readline library")
482 self.autoindent = 0
480 self.autoindent = 0
483 return
481 return
484 if value is None:
482 if value is None:
485 self.autoindent = not self.autoindent
483 self.autoindent = not self.autoindent
486 else:
484 else:
487 self.autoindent = value
485 self.autoindent = value
488
486
489 #-------------------------------------------------------------------------
487 #-------------------------------------------------------------------------
490 # init_* methods called by __init__
488 # init_* methods called by __init__
491 #-------------------------------------------------------------------------
489 #-------------------------------------------------------------------------
492
490
493 def init_ipython_dir(self, ipython_dir):
491 def init_ipython_dir(self, ipython_dir):
494 if ipython_dir is not None:
492 if ipython_dir is not None:
495 self.ipython_dir = ipython_dir
493 self.ipython_dir = ipython_dir
496 return
494 return
497
495
498 self.ipython_dir = get_ipython_dir()
496 self.ipython_dir = get_ipython_dir()
499
497
500 def init_profile_dir(self, profile_dir):
498 def init_profile_dir(self, profile_dir):
501 if profile_dir is not None:
499 if profile_dir is not None:
502 self.profile_dir = profile_dir
500 self.profile_dir = profile_dir
503 return
501 return
504 self.profile_dir =\
502 self.profile_dir =\
505 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
503 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
506
504
507 def init_instance_attrs(self):
505 def init_instance_attrs(self):
508 self.more = False
506 self.more = False
509
507
510 # command compiler
508 # command compiler
511 self.compile = CachingCompiler()
509 self.compile = CachingCompiler()
512
510
513 # Make an empty namespace, which extension writers can rely on both
511 # Make an empty namespace, which extension writers can rely on both
514 # existing and NEVER being used by ipython itself. This gives them a
512 # existing and NEVER being used by ipython itself. This gives them a
515 # convenient location for storing additional information and state
513 # convenient location for storing additional information and state
516 # their extensions may require, without fear of collisions with other
514 # their extensions may require, without fear of collisions with other
517 # ipython names that may develop later.
515 # ipython names that may develop later.
518 self.meta = Struct()
516 self.meta = Struct()
519
517
520 # Temporary files used for various purposes. Deleted at exit.
518 # Temporary files used for various purposes. Deleted at exit.
521 self.tempfiles = []
519 self.tempfiles = []
522
520
523 # Keep track of readline usage (later set by init_readline)
521 # Keep track of readline usage (later set by init_readline)
524 self.has_readline = False
522 self.has_readline = False
525
523
526 # keep track of where we started running (mainly for crash post-mortem)
524 # keep track of where we started running (mainly for crash post-mortem)
527 # This is not being used anywhere currently.
525 # This is not being used anywhere currently.
528 self.starting_dir = os.getcwdu()
526 self.starting_dir = os.getcwdu()
529
527
530 # Indentation management
528 # Indentation management
531 self.indent_current_nsp = 0
529 self.indent_current_nsp = 0
532
530
533 # Dict to track post-execution functions that have been registered
531 # Dict to track post-execution functions that have been registered
534 self._post_execute = {}
532 self._post_execute = {}
535
533
536 def init_environment(self):
534 def init_environment(self):
537 """Any changes we need to make to the user's environment."""
535 """Any changes we need to make to the user's environment."""
538 pass
536 pass
539
537
540 def init_encoding(self):
538 def init_encoding(self):
541 # Get system encoding at startup time. Certain terminals (like Emacs
539 # Get system encoding at startup time. Certain terminals (like Emacs
542 # under Win32 have it set to None, and we need to have a known valid
540 # under Win32 have it set to None, and we need to have a known valid
543 # encoding to use in the raw_input() method
541 # encoding to use in the raw_input() method
544 try:
542 try:
545 self.stdin_encoding = sys.stdin.encoding or 'ascii'
543 self.stdin_encoding = sys.stdin.encoding or 'ascii'
546 except AttributeError:
544 except AttributeError:
547 self.stdin_encoding = 'ascii'
545 self.stdin_encoding = 'ascii'
548
546
549 def init_syntax_highlighting(self):
547 def init_syntax_highlighting(self):
550 # Python source parser/formatter for syntax highlighting
548 # Python source parser/formatter for syntax highlighting
551 pyformat = PyColorize.Parser().format
549 pyformat = PyColorize.Parser().format
552 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
550 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
553
551
554 def init_pushd_popd_magic(self):
552 def init_pushd_popd_magic(self):
555 # for pushd/popd management
553 # for pushd/popd management
556 try:
554 try:
557 self.home_dir = get_home_dir()
555 self.home_dir = get_home_dir()
558 except HomeDirError, msg:
556 except HomeDirError, msg:
559 fatal(msg)
557 fatal(msg)
560
558
561 self.dir_stack = []
559 self.dir_stack = []
562
560
563 def init_logger(self):
561 def init_logger(self):
564 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
562 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
565 logmode='rotate')
563 logmode='rotate')
566
564
567 def init_logstart(self):
565 def init_logstart(self):
568 """Initialize logging in case it was requested at the command line.
566 """Initialize logging in case it was requested at the command line.
569 """
567 """
570 if self.logappend:
568 if self.logappend:
571 self.magic_logstart(self.logappend + ' append')
569 self.magic_logstart(self.logappend + ' append')
572 elif self.logfile:
570 elif self.logfile:
573 self.magic_logstart(self.logfile)
571 self.magic_logstart(self.logfile)
574 elif self.logstart:
572 elif self.logstart:
575 self.magic_logstart()
573 self.magic_logstart()
576
574
577 def init_builtins(self):
575 def init_builtins(self):
578 self.builtin_trap = BuiltinTrap(shell=self)
576 self.builtin_trap = BuiltinTrap(shell=self)
579
577
580 def init_inspector(self):
578 def init_inspector(self):
581 # Object inspector
579 # Object inspector
582 self.inspector = oinspect.Inspector(oinspect.InspectColors,
580 self.inspector = oinspect.Inspector(oinspect.InspectColors,
583 PyColorize.ANSICodeColors,
581 PyColorize.ANSICodeColors,
584 'NoColor',
582 'NoColor',
585 self.object_info_string_level)
583 self.object_info_string_level)
586
584
587 def init_io(self):
585 def init_io(self):
588 # This will just use sys.stdout and sys.stderr. If you want to
586 # This will just use sys.stdout and sys.stderr. If you want to
589 # override sys.stdout and sys.stderr themselves, you need to do that
587 # override sys.stdout and sys.stderr themselves, you need to do that
590 # *before* instantiating this class, because io holds onto
588 # *before* instantiating this class, because io holds onto
591 # references to the underlying streams.
589 # references to the underlying streams.
592 if sys.platform == 'win32' and self.has_readline:
590 if sys.platform == 'win32' and self.has_readline:
593 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
591 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
594 else:
592 else:
595 io.stdout = io.IOStream(sys.stdout)
593 io.stdout = io.IOStream(sys.stdout)
596 io.stderr = io.IOStream(sys.stderr)
594 io.stderr = io.IOStream(sys.stderr)
597
595
598 def init_prompts(self):
596 def init_prompts(self):
599 # TODO: This is a pass for now because the prompts are managed inside
597 # TODO: This is a pass for now because the prompts are managed inside
600 # the DisplayHook. Once there is a separate prompt manager, this
598 # the DisplayHook. Once there is a separate prompt manager, this
601 # will initialize that object and all prompt related information.
599 # will initialize that object and all prompt related information.
602 pass
600 pass
603
601
604 def init_display_formatter(self):
602 def init_display_formatter(self):
605 self.display_formatter = DisplayFormatter(config=self.config)
603 self.display_formatter = DisplayFormatter(config=self.config)
606 self.configurables.append(self.display_formatter)
604 self.configurables.append(self.display_formatter)
607
605
608 def init_display_pub(self):
606 def init_display_pub(self):
609 self.display_pub = self.display_pub_class(config=self.config)
607 self.display_pub = self.display_pub_class(config=self.config)
610 self.configurables.append(self.display_pub)
608 self.configurables.append(self.display_pub)
611
609
612 def init_displayhook(self):
610 def init_displayhook(self):
613 # Initialize displayhook, set in/out prompts and printing system
611 # Initialize displayhook, set in/out prompts and printing system
614 self.displayhook = self.displayhook_class(
612 self.displayhook = self.displayhook_class(
615 config=self.config,
613 config=self.config,
616 shell=self,
614 shell=self,
617 cache_size=self.cache_size,
615 cache_size=self.cache_size,
618 input_sep = self.separate_in,
616 input_sep = self.separate_in,
619 output_sep = self.separate_out,
617 output_sep = self.separate_out,
620 output_sep2 = self.separate_out2,
618 output_sep2 = self.separate_out2,
621 ps1 = self.prompt_in1,
619 ps1 = self.prompt_in1,
622 ps2 = self.prompt_in2,
620 ps2 = self.prompt_in2,
623 ps_out = self.prompt_out,
621 ps_out = self.prompt_out,
624 pad_left = self.prompts_pad_left
622 pad_left = self.prompts_pad_left
625 )
623 )
626 self.configurables.append(self.displayhook)
624 self.configurables.append(self.displayhook)
627 # This is a context manager that installs/revmoes the displayhook at
625 # This is a context manager that installs/revmoes the displayhook at
628 # the appropriate time.
626 # the appropriate time.
629 self.display_trap = DisplayTrap(hook=self.displayhook)
627 self.display_trap = DisplayTrap(hook=self.displayhook)
630
628
631 def init_reload_doctest(self):
629 def init_reload_doctest(self):
632 # Do a proper resetting of doctest, including the necessary displayhook
630 # Do a proper resetting of doctest, including the necessary displayhook
633 # monkeypatching
631 # monkeypatching
634 try:
632 try:
635 doctest_reload()
633 doctest_reload()
636 except ImportError:
634 except ImportError:
637 warn("doctest module does not exist.")
635 warn("doctest module does not exist.")
638
636
639 #-------------------------------------------------------------------------
637 #-------------------------------------------------------------------------
640 # Things related to injections into the sys module
638 # Things related to injections into the sys module
641 #-------------------------------------------------------------------------
639 #-------------------------------------------------------------------------
642
640
643 def save_sys_module_state(self):
641 def save_sys_module_state(self):
644 """Save the state of hooks in the sys module.
642 """Save the state of hooks in the sys module.
645
643
646 This has to be called after self.user_ns is created.
644 This has to be called after self.user_ns is created.
647 """
645 """
648 self._orig_sys_module_state = {}
646 self._orig_sys_module_state = {}
649 self._orig_sys_module_state['stdin'] = sys.stdin
647 self._orig_sys_module_state['stdin'] = sys.stdin
650 self._orig_sys_module_state['stdout'] = sys.stdout
648 self._orig_sys_module_state['stdout'] = sys.stdout
651 self._orig_sys_module_state['stderr'] = sys.stderr
649 self._orig_sys_module_state['stderr'] = sys.stderr
652 self._orig_sys_module_state['excepthook'] = sys.excepthook
650 self._orig_sys_module_state['excepthook'] = sys.excepthook
653 try:
651 try:
654 self._orig_sys_modules_main_name = self.user_ns['__name__']
652 self._orig_sys_modules_main_name = self.user_ns['__name__']
655 except KeyError:
653 except KeyError:
656 pass
654 pass
657
655
658 def restore_sys_module_state(self):
656 def restore_sys_module_state(self):
659 """Restore the state of the sys module."""
657 """Restore the state of the sys module."""
660 try:
658 try:
661 for k, v in self._orig_sys_module_state.iteritems():
659 for k, v in self._orig_sys_module_state.iteritems():
662 setattr(sys, k, v)
660 setattr(sys, k, v)
663 except AttributeError:
661 except AttributeError:
664 pass
662 pass
665 # Reset what what done in self.init_sys_modules
663 # Reset what what done in self.init_sys_modules
666 try:
664 try:
667 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
665 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
668 except (AttributeError, KeyError):
666 except (AttributeError, KeyError):
669 pass
667 pass
670
668
671 #-------------------------------------------------------------------------
669 #-------------------------------------------------------------------------
672 # Things related to hooks
670 # Things related to hooks
673 #-------------------------------------------------------------------------
671 #-------------------------------------------------------------------------
674
672
675 def init_hooks(self):
673 def init_hooks(self):
676 # hooks holds pointers used for user-side customizations
674 # hooks holds pointers used for user-side customizations
677 self.hooks = Struct()
675 self.hooks = Struct()
678
676
679 self.strdispatchers = {}
677 self.strdispatchers = {}
680
678
681 # Set all default hooks, defined in the IPython.hooks module.
679 # Set all default hooks, defined in the IPython.hooks module.
682 hooks = IPython.core.hooks
680 hooks = IPython.core.hooks
683 for hook_name in hooks.__all__:
681 for hook_name in hooks.__all__:
684 # default hooks have priority 100, i.e. low; user hooks should have
682 # default hooks have priority 100, i.e. low; user hooks should have
685 # 0-100 priority
683 # 0-100 priority
686 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
684 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
687
685
688 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
686 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
689 """set_hook(name,hook) -> sets an internal IPython hook.
687 """set_hook(name,hook) -> sets an internal IPython hook.
690
688
691 IPython exposes some of its internal API as user-modifiable hooks. By
689 IPython exposes some of its internal API as user-modifiable hooks. By
692 adding your function to one of these hooks, you can modify IPython's
690 adding your function to one of these hooks, you can modify IPython's
693 behavior to call at runtime your own routines."""
691 behavior to call at runtime your own routines."""
694
692
695 # At some point in the future, this should validate the hook before it
693 # At some point in the future, this should validate the hook before it
696 # accepts it. Probably at least check that the hook takes the number
694 # accepts it. Probably at least check that the hook takes the number
697 # of args it's supposed to.
695 # of args it's supposed to.
698
696
699 f = types.MethodType(hook,self)
697 f = types.MethodType(hook,self)
700
698
701 # check if the hook is for strdispatcher first
699 # check if the hook is for strdispatcher first
702 if str_key is not None:
700 if str_key is not None:
703 sdp = self.strdispatchers.get(name, StrDispatch())
701 sdp = self.strdispatchers.get(name, StrDispatch())
704 sdp.add_s(str_key, f, priority )
702 sdp.add_s(str_key, f, priority )
705 self.strdispatchers[name] = sdp
703 self.strdispatchers[name] = sdp
706 return
704 return
707 if re_key is not None:
705 if re_key is not None:
708 sdp = self.strdispatchers.get(name, StrDispatch())
706 sdp = self.strdispatchers.get(name, StrDispatch())
709 sdp.add_re(re.compile(re_key), f, priority )
707 sdp.add_re(re.compile(re_key), f, priority )
710 self.strdispatchers[name] = sdp
708 self.strdispatchers[name] = sdp
711 return
709 return
712
710
713 dp = getattr(self.hooks, name, None)
711 dp = getattr(self.hooks, name, None)
714 if name not in IPython.core.hooks.__all__:
712 if name not in IPython.core.hooks.__all__:
715 print "Warning! Hook '%s' is not one of %s" % \
713 print "Warning! Hook '%s' is not one of %s" % \
716 (name, IPython.core.hooks.__all__ )
714 (name, IPython.core.hooks.__all__ )
717 if not dp:
715 if not dp:
718 dp = IPython.core.hooks.CommandChainDispatcher()
716 dp = IPython.core.hooks.CommandChainDispatcher()
719
717
720 try:
718 try:
721 dp.add(f,priority)
719 dp.add(f,priority)
722 except AttributeError:
720 except AttributeError:
723 # it was not commandchain, plain old func - replace
721 # it was not commandchain, plain old func - replace
724 dp = f
722 dp = f
725
723
726 setattr(self.hooks,name, dp)
724 setattr(self.hooks,name, dp)
727
725
728 def register_post_execute(self, func):
726 def register_post_execute(self, func):
729 """Register a function for calling after code execution.
727 """Register a function for calling after code execution.
730 """
728 """
731 if not callable(func):
729 if not callable(func):
732 raise ValueError('argument %s must be callable' % func)
730 raise ValueError('argument %s must be callable' % func)
733 self._post_execute[func] = True
731 self._post_execute[func] = True
734
732
735 #-------------------------------------------------------------------------
733 #-------------------------------------------------------------------------
736 # Things related to the "main" module
734 # Things related to the "main" module
737 #-------------------------------------------------------------------------
735 #-------------------------------------------------------------------------
738
736
739 def new_main_mod(self,ns=None):
737 def new_main_mod(self,ns=None):
740 """Return a new 'main' module object for user code execution.
738 """Return a new 'main' module object for user code execution.
741 """
739 """
742 main_mod = self._user_main_module
740 main_mod = self._user_main_module
743 init_fakemod_dict(main_mod,ns)
741 init_fakemod_dict(main_mod,ns)
744 return main_mod
742 return main_mod
745
743
746 def cache_main_mod(self,ns,fname):
744 def cache_main_mod(self,ns,fname):
747 """Cache a main module's namespace.
745 """Cache a main module's namespace.
748
746
749 When scripts are executed via %run, we must keep a reference to the
747 When scripts are executed via %run, we must keep a reference to the
750 namespace of their __main__ module (a FakeModule instance) around so
748 namespace of their __main__ module (a FakeModule instance) around so
751 that Python doesn't clear it, rendering objects defined therein
749 that Python doesn't clear it, rendering objects defined therein
752 useless.
750 useless.
753
751
754 This method keeps said reference in a private dict, keyed by the
752 This method keeps said reference in a private dict, keyed by the
755 absolute path of the module object (which corresponds to the script
753 absolute path of the module object (which corresponds to the script
756 path). This way, for multiple executions of the same script we only
754 path). This way, for multiple executions of the same script we only
757 keep one copy of the namespace (the last one), thus preventing memory
755 keep one copy of the namespace (the last one), thus preventing memory
758 leaks from old references while allowing the objects from the last
756 leaks from old references while allowing the objects from the last
759 execution to be accessible.
757 execution to be accessible.
760
758
761 Note: we can not allow the actual FakeModule instances to be deleted,
759 Note: we can not allow the actual FakeModule instances to be deleted,
762 because of how Python tears down modules (it hard-sets all their
760 because of how Python tears down modules (it hard-sets all their
763 references to None without regard for reference counts). This method
761 references to None without regard for reference counts). This method
764 must therefore make a *copy* of the given namespace, to allow the
762 must therefore make a *copy* of the given namespace, to allow the
765 original module's __dict__ to be cleared and reused.
763 original module's __dict__ to be cleared and reused.
766
764
767
765
768 Parameters
766 Parameters
769 ----------
767 ----------
770 ns : a namespace (a dict, typically)
768 ns : a namespace (a dict, typically)
771
769
772 fname : str
770 fname : str
773 Filename associated with the namespace.
771 Filename associated with the namespace.
774
772
775 Examples
773 Examples
776 --------
774 --------
777
775
778 In [10]: import IPython
776 In [10]: import IPython
779
777
780 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
778 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
781
779
782 In [12]: IPython.__file__ in _ip._main_ns_cache
780 In [12]: IPython.__file__ in _ip._main_ns_cache
783 Out[12]: True
781 Out[12]: True
784 """
782 """
785 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
783 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
786
784
787 def clear_main_mod_cache(self):
785 def clear_main_mod_cache(self):
788 """Clear the cache of main modules.
786 """Clear the cache of main modules.
789
787
790 Mainly for use by utilities like %reset.
788 Mainly for use by utilities like %reset.
791
789
792 Examples
790 Examples
793 --------
791 --------
794
792
795 In [15]: import IPython
793 In [15]: import IPython
796
794
797 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
795 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
798
796
799 In [17]: len(_ip._main_ns_cache) > 0
797 In [17]: len(_ip._main_ns_cache) > 0
800 Out[17]: True
798 Out[17]: True
801
799
802 In [18]: _ip.clear_main_mod_cache()
800 In [18]: _ip.clear_main_mod_cache()
803
801
804 In [19]: len(_ip._main_ns_cache) == 0
802 In [19]: len(_ip._main_ns_cache) == 0
805 Out[19]: True
803 Out[19]: True
806 """
804 """
807 self._main_ns_cache.clear()
805 self._main_ns_cache.clear()
808
806
809 #-------------------------------------------------------------------------
807 #-------------------------------------------------------------------------
810 # Things related to debugging
808 # Things related to debugging
811 #-------------------------------------------------------------------------
809 #-------------------------------------------------------------------------
812
810
813 def init_pdb(self):
811 def init_pdb(self):
814 # Set calling of pdb on exceptions
812 # Set calling of pdb on exceptions
815 # self.call_pdb is a property
813 # self.call_pdb is a property
816 self.call_pdb = self.pdb
814 self.call_pdb = self.pdb
817
815
818 def _get_call_pdb(self):
816 def _get_call_pdb(self):
819 return self._call_pdb
817 return self._call_pdb
820
818
821 def _set_call_pdb(self,val):
819 def _set_call_pdb(self,val):
822
820
823 if val not in (0,1,False,True):
821 if val not in (0,1,False,True):
824 raise ValueError,'new call_pdb value must be boolean'
822 raise ValueError,'new call_pdb value must be boolean'
825
823
826 # store value in instance
824 # store value in instance
827 self._call_pdb = val
825 self._call_pdb = val
828
826
829 # notify the actual exception handlers
827 # notify the actual exception handlers
830 self.InteractiveTB.call_pdb = val
828 self.InteractiveTB.call_pdb = val
831
829
832 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
830 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
833 'Control auto-activation of pdb at exceptions')
831 'Control auto-activation of pdb at exceptions')
834
832
835 def debugger(self,force=False):
833 def debugger(self,force=False):
836 """Call the pydb/pdb debugger.
834 """Call the pydb/pdb debugger.
837
835
838 Keywords:
836 Keywords:
839
837
840 - force(False): by default, this routine checks the instance call_pdb
838 - force(False): by default, this routine checks the instance call_pdb
841 flag and does not actually invoke the debugger if the flag is false.
839 flag and does not actually invoke the debugger if the flag is false.
842 The 'force' option forces the debugger to activate even if the flag
840 The 'force' option forces the debugger to activate even if the flag
843 is false.
841 is false.
844 """
842 """
845
843
846 if not (force or self.call_pdb):
844 if not (force or self.call_pdb):
847 return
845 return
848
846
849 if not hasattr(sys,'last_traceback'):
847 if not hasattr(sys,'last_traceback'):
850 error('No traceback has been produced, nothing to debug.')
848 error('No traceback has been produced, nothing to debug.')
851 return
849 return
852
850
853 # use pydb if available
851 # use pydb if available
854 if debugger.has_pydb:
852 if debugger.has_pydb:
855 from pydb import pm
853 from pydb import pm
856 else:
854 else:
857 # fallback to our internal debugger
855 # fallback to our internal debugger
858 pm = lambda : self.InteractiveTB.debugger(force=True)
856 pm = lambda : self.InteractiveTB.debugger(force=True)
859
857
860 with self.readline_no_record:
858 with self.readline_no_record:
861 pm()
859 pm()
862
860
863 #-------------------------------------------------------------------------
861 #-------------------------------------------------------------------------
864 # Things related to IPython's various namespaces
862 # Things related to IPython's various namespaces
865 #-------------------------------------------------------------------------
863 #-------------------------------------------------------------------------
866
864
867 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
865 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
868 # Create the namespace where the user will operate. user_ns is
866 # Create the namespace where the user will operate. user_ns is
869 # normally the only one used, and it is passed to the exec calls as
867 # normally the only one used, and it is passed to the exec calls as
870 # the locals argument. But we do carry a user_global_ns namespace
868 # the locals argument. But we do carry a user_global_ns namespace
871 # given as the exec 'globals' argument, This is useful in embedding
869 # given as the exec 'globals' argument, This is useful in embedding
872 # situations where the ipython shell opens in a context where the
870 # situations where the ipython shell opens in a context where the
873 # distinction between locals and globals is meaningful. For
871 # distinction between locals and globals is meaningful. For
874 # non-embedded contexts, it is just the same object as the user_ns dict.
872 # non-embedded contexts, it is just the same object as the user_ns dict.
875
873
876 # FIXME. For some strange reason, __builtins__ is showing up at user
874 # FIXME. For some strange reason, __builtins__ is showing up at user
877 # level as a dict instead of a module. This is a manual fix, but I
875 # level as a dict instead of a module. This is a manual fix, but I
878 # should really track down where the problem is coming from. Alex
876 # should really track down where the problem is coming from. Alex
879 # Schmolck reported this problem first.
877 # Schmolck reported this problem first.
880
878
881 # A useful post by Alex Martelli on this topic:
879 # A useful post by Alex Martelli on this topic:
882 # Re: inconsistent value from __builtins__
880 # Re: inconsistent value from __builtins__
883 # Von: Alex Martelli <aleaxit@yahoo.com>
881 # Von: Alex Martelli <aleaxit@yahoo.com>
884 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
882 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
885 # Gruppen: comp.lang.python
883 # Gruppen: comp.lang.python
886
884
887 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
885 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
888 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
886 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
889 # > <type 'dict'>
887 # > <type 'dict'>
890 # > >>> print type(__builtins__)
888 # > >>> print type(__builtins__)
891 # > <type 'module'>
889 # > <type 'module'>
892 # > Is this difference in return value intentional?
890 # > Is this difference in return value intentional?
893
891
894 # Well, it's documented that '__builtins__' can be either a dictionary
892 # Well, it's documented that '__builtins__' can be either a dictionary
895 # or a module, and it's been that way for a long time. Whether it's
893 # or a module, and it's been that way for a long time. Whether it's
896 # intentional (or sensible), I don't know. In any case, the idea is
894 # intentional (or sensible), I don't know. In any case, the idea is
897 # that if you need to access the built-in namespace directly, you
895 # that if you need to access the built-in namespace directly, you
898 # should start with "import __builtin__" (note, no 's') which will
896 # should start with "import __builtin__" (note, no 's') which will
899 # definitely give you a module. Yeah, it's somewhat confusing:-(.
897 # definitely give you a module. Yeah, it's somewhat confusing:-(.
900
898
901 # These routines return properly built dicts as needed by the rest of
899 # These routines return properly built dicts as needed by the rest of
902 # the code, and can also be used by extension writers to generate
900 # the code, and can also be used by extension writers to generate
903 # properly initialized namespaces.
901 # properly initialized namespaces.
904 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
902 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
905 user_global_ns)
903 user_global_ns)
906
904
907 # Assign namespaces
905 # Assign namespaces
908 # This is the namespace where all normal user variables live
906 # This is the namespace where all normal user variables live
909 self.user_ns = user_ns
907 self.user_ns = user_ns
910 self.user_global_ns = user_global_ns
908 self.user_global_ns = user_global_ns
911
909
912 # An auxiliary namespace that checks what parts of the user_ns were
910 # An auxiliary namespace that checks what parts of the user_ns were
913 # loaded at startup, so we can list later only variables defined in
911 # loaded at startup, so we can list later only variables defined in
914 # actual interactive use. Since it is always a subset of user_ns, it
912 # actual interactive use. Since it is always a subset of user_ns, it
915 # doesn't need to be separately tracked in the ns_table.
913 # doesn't need to be separately tracked in the ns_table.
916 self.user_ns_hidden = {}
914 self.user_ns_hidden = {}
917
915
918 # A namespace to keep track of internal data structures to prevent
916 # A namespace to keep track of internal data structures to prevent
919 # them from cluttering user-visible stuff. Will be updated later
917 # them from cluttering user-visible stuff. Will be updated later
920 self.internal_ns = {}
918 self.internal_ns = {}
921
919
922 # Now that FakeModule produces a real module, we've run into a nasty
920 # Now that FakeModule produces a real module, we've run into a nasty
923 # problem: after script execution (via %run), the module where the user
921 # problem: after script execution (via %run), the module where the user
924 # code ran is deleted. Now that this object is a true module (needed
922 # code ran is deleted. Now that this object is a true module (needed
925 # so docetst and other tools work correctly), the Python module
923 # so docetst and other tools work correctly), the Python module
926 # teardown mechanism runs over it, and sets to None every variable
924 # teardown mechanism runs over it, and sets to None every variable
927 # present in that module. Top-level references to objects from the
925 # present in that module. Top-level references to objects from the
928 # script survive, because the user_ns is updated with them. However,
926 # script survive, because the user_ns is updated with them. However,
929 # calling functions defined in the script that use other things from
927 # calling functions defined in the script that use other things from
930 # the script will fail, because the function's closure had references
928 # the script will fail, because the function's closure had references
931 # to the original objects, which are now all None. So we must protect
929 # to the original objects, which are now all None. So we must protect
932 # these modules from deletion by keeping a cache.
930 # these modules from deletion by keeping a cache.
933 #
931 #
934 # To avoid keeping stale modules around (we only need the one from the
932 # To avoid keeping stale modules around (we only need the one from the
935 # last run), we use a dict keyed with the full path to the script, so
933 # last run), we use a dict keyed with the full path to the script, so
936 # only the last version of the module is held in the cache. Note,
934 # only the last version of the module is held in the cache. Note,
937 # however, that we must cache the module *namespace contents* (their
935 # however, that we must cache the module *namespace contents* (their
938 # __dict__). Because if we try to cache the actual modules, old ones
936 # __dict__). Because if we try to cache the actual modules, old ones
939 # (uncached) could be destroyed while still holding references (such as
937 # (uncached) could be destroyed while still holding references (such as
940 # those held by GUI objects that tend to be long-lived)>
938 # those held by GUI objects that tend to be long-lived)>
941 #
939 #
942 # The %reset command will flush this cache. See the cache_main_mod()
940 # The %reset command will flush this cache. See the cache_main_mod()
943 # and clear_main_mod_cache() methods for details on use.
941 # and clear_main_mod_cache() methods for details on use.
944
942
945 # This is the cache used for 'main' namespaces
943 # This is the cache used for 'main' namespaces
946 self._main_ns_cache = {}
944 self._main_ns_cache = {}
947 # And this is the single instance of FakeModule whose __dict__ we keep
945 # And this is the single instance of FakeModule whose __dict__ we keep
948 # copying and clearing for reuse on each %run
946 # copying and clearing for reuse on each %run
949 self._user_main_module = FakeModule()
947 self._user_main_module = FakeModule()
950
948
951 # A table holding all the namespaces IPython deals with, so that
949 # A table holding all the namespaces IPython deals with, so that
952 # introspection facilities can search easily.
950 # introspection facilities can search easily.
953 self.ns_table = {'user':user_ns,
951 self.ns_table = {'user':user_ns,
954 'user_global':user_global_ns,
952 'user_global':user_global_ns,
955 'internal':self.internal_ns,
953 'internal':self.internal_ns,
956 'builtin':builtin_mod.__dict__
954 'builtin':builtin_mod.__dict__
957 }
955 }
958
956
959 # Similarly, track all namespaces where references can be held and that
957 # Similarly, track all namespaces where references can be held and that
960 # we can safely clear (so it can NOT include builtin). This one can be
958 # we can safely clear (so it can NOT include builtin). This one can be
961 # a simple list. Note that the main execution namespaces, user_ns and
959 # a simple list. Note that the main execution namespaces, user_ns and
962 # user_global_ns, can NOT be listed here, as clearing them blindly
960 # user_global_ns, can NOT be listed here, as clearing them blindly
963 # causes errors in object __del__ methods. Instead, the reset() method
961 # causes errors in object __del__ methods. Instead, the reset() method
964 # clears them manually and carefully.
962 # clears them manually and carefully.
965 self.ns_refs_table = [ self.user_ns_hidden,
963 self.ns_refs_table = [ self.user_ns_hidden,
966 self.internal_ns, self._main_ns_cache ]
964 self.internal_ns, self._main_ns_cache ]
967
965
968 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
966 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
969 """Return a valid local and global user interactive namespaces.
967 """Return a valid local and global user interactive namespaces.
970
968
971 This builds a dict with the minimal information needed to operate as a
969 This builds a dict with the minimal information needed to operate as a
972 valid IPython user namespace, which you can pass to the various
970 valid IPython user namespace, which you can pass to the various
973 embedding classes in ipython. The default implementation returns the
971 embedding classes in ipython. The default implementation returns the
974 same dict for both the locals and the globals to allow functions to
972 same dict for both the locals and the globals to allow functions to
975 refer to variables in the namespace. Customized implementations can
973 refer to variables in the namespace. Customized implementations can
976 return different dicts. The locals dictionary can actually be anything
974 return different dicts. The locals dictionary can actually be anything
977 following the basic mapping protocol of a dict, but the globals dict
975 following the basic mapping protocol of a dict, but the globals dict
978 must be a true dict, not even a subclass. It is recommended that any
976 must be a true dict, not even a subclass. It is recommended that any
979 custom object for the locals namespace synchronize with the globals
977 custom object for the locals namespace synchronize with the globals
980 dict somehow.
978 dict somehow.
981
979
982 Raises TypeError if the provided globals namespace is not a true dict.
980 Raises TypeError if the provided globals namespace is not a true dict.
983
981
984 Parameters
982 Parameters
985 ----------
983 ----------
986 user_ns : dict-like, optional
984 user_ns : dict-like, optional
987 The current user namespace. The items in this namespace should
985 The current user namespace. The items in this namespace should
988 be included in the output. If None, an appropriate blank
986 be included in the output. If None, an appropriate blank
989 namespace should be created.
987 namespace should be created.
990 user_global_ns : dict, optional
988 user_global_ns : dict, optional
991 The current user global namespace. The items in this namespace
989 The current user global namespace. The items in this namespace
992 should be included in the output. If None, an appropriate
990 should be included in the output. If None, an appropriate
993 blank namespace should be created.
991 blank namespace should be created.
994
992
995 Returns
993 Returns
996 -------
994 -------
997 A pair of dictionary-like object to be used as the local namespace
995 A pair of dictionary-like object to be used as the local namespace
998 of the interpreter and a dict to be used as the global namespace.
996 of the interpreter and a dict to be used as the global namespace.
999 """
997 """
1000
998
1001
999
1002 # We must ensure that __builtin__ (without the final 's') is always
1000 # We must ensure that __builtin__ (without the final 's') is always
1003 # available and pointing to the __builtin__ *module*. For more details:
1001 # available and pointing to the __builtin__ *module*. For more details:
1004 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1002 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1005
1003
1006 if user_ns is None:
1004 if user_ns is None:
1007 # Set __name__ to __main__ to better match the behavior of the
1005 # Set __name__ to __main__ to better match the behavior of the
1008 # normal interpreter.
1006 # normal interpreter.
1009 user_ns = {'__name__' :'__main__',
1007 user_ns = {'__name__' :'__main__',
1010 py3compat.builtin_mod_name: builtin_mod,
1008 py3compat.builtin_mod_name: builtin_mod,
1011 '__builtins__' : builtin_mod,
1009 '__builtins__' : builtin_mod,
1012 }
1010 }
1013 else:
1011 else:
1014 user_ns.setdefault('__name__','__main__')
1012 user_ns.setdefault('__name__','__main__')
1015 user_ns.setdefault(py3compat.builtin_mod_name,builtin_mod)
1013 user_ns.setdefault(py3compat.builtin_mod_name,builtin_mod)
1016 user_ns.setdefault('__builtins__',builtin_mod)
1014 user_ns.setdefault('__builtins__',builtin_mod)
1017
1015
1018 if user_global_ns is None:
1016 if user_global_ns is None:
1019 user_global_ns = user_ns
1017 user_global_ns = user_ns
1020 if type(user_global_ns) is not dict:
1018 if type(user_global_ns) is not dict:
1021 raise TypeError("user_global_ns must be a true dict; got %r"
1019 raise TypeError("user_global_ns must be a true dict; got %r"
1022 % type(user_global_ns))
1020 % type(user_global_ns))
1023
1021
1024 return user_ns, user_global_ns
1022 return user_ns, user_global_ns
1025
1023
1026 def init_sys_modules(self):
1024 def init_sys_modules(self):
1027 # We need to insert into sys.modules something that looks like a
1025 # We need to insert into sys.modules something that looks like a
1028 # module but which accesses the IPython namespace, for shelve and
1026 # module but which accesses the IPython namespace, for shelve and
1029 # pickle to work interactively. Normally they rely on getting
1027 # pickle to work interactively. Normally they rely on getting
1030 # everything out of __main__, but for embedding purposes each IPython
1028 # everything out of __main__, but for embedding purposes each IPython
1031 # instance has its own private namespace, so we can't go shoving
1029 # instance has its own private namespace, so we can't go shoving
1032 # everything into __main__.
1030 # everything into __main__.
1033
1031
1034 # note, however, that we should only do this for non-embedded
1032 # note, however, that we should only do this for non-embedded
1035 # ipythons, which really mimic the __main__.__dict__ with their own
1033 # ipythons, which really mimic the __main__.__dict__ with their own
1036 # namespace. Embedded instances, on the other hand, should not do
1034 # namespace. Embedded instances, on the other hand, should not do
1037 # this because they need to manage the user local/global namespaces
1035 # this because they need to manage the user local/global namespaces
1038 # only, but they live within a 'normal' __main__ (meaning, they
1036 # only, but they live within a 'normal' __main__ (meaning, they
1039 # shouldn't overtake the execution environment of the script they're
1037 # shouldn't overtake the execution environment of the script they're
1040 # embedded in).
1038 # embedded in).
1041
1039
1042 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1040 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1043
1041
1044 try:
1042 try:
1045 main_name = self.user_ns['__name__']
1043 main_name = self.user_ns['__name__']
1046 except KeyError:
1044 except KeyError:
1047 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1045 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1048 else:
1046 else:
1049 sys.modules[main_name] = FakeModule(self.user_ns)
1047 sys.modules[main_name] = FakeModule(self.user_ns)
1050
1048
1051 def init_user_ns(self):
1049 def init_user_ns(self):
1052 """Initialize all user-visible namespaces to their minimum defaults.
1050 """Initialize all user-visible namespaces to their minimum defaults.
1053
1051
1054 Certain history lists are also initialized here, as they effectively
1052 Certain history lists are also initialized here, as they effectively
1055 act as user namespaces.
1053 act as user namespaces.
1056
1054
1057 Notes
1055 Notes
1058 -----
1056 -----
1059 All data structures here are only filled in, they are NOT reset by this
1057 All data structures here are only filled in, they are NOT reset by this
1060 method. If they were not empty before, data will simply be added to
1058 method. If they were not empty before, data will simply be added to
1061 therm.
1059 therm.
1062 """
1060 """
1063 # This function works in two parts: first we put a few things in
1061 # This function works in two parts: first we put a few things in
1064 # user_ns, and we sync that contents into user_ns_hidden so that these
1062 # user_ns, and we sync that contents into user_ns_hidden so that these
1065 # initial variables aren't shown by %who. After the sync, we add the
1063 # initial variables aren't shown by %who. After the sync, we add the
1066 # rest of what we *do* want the user to see with %who even on a new
1064 # rest of what we *do* want the user to see with %who even on a new
1067 # session (probably nothing, so theye really only see their own stuff)
1065 # session (probably nothing, so theye really only see their own stuff)
1068
1066
1069 # The user dict must *always* have a __builtin__ reference to the
1067 # The user dict must *always* have a __builtin__ reference to the
1070 # Python standard __builtin__ namespace, which must be imported.
1068 # Python standard __builtin__ namespace, which must be imported.
1071 # This is so that certain operations in prompt evaluation can be
1069 # This is so that certain operations in prompt evaluation can be
1072 # reliably executed with builtins. Note that we can NOT use
1070 # reliably executed with builtins. Note that we can NOT use
1073 # __builtins__ (note the 's'), because that can either be a dict or a
1071 # __builtins__ (note the 's'), because that can either be a dict or a
1074 # module, and can even mutate at runtime, depending on the context
1072 # module, and can even mutate at runtime, depending on the context
1075 # (Python makes no guarantees on it). In contrast, __builtin__ is
1073 # (Python makes no guarantees on it). In contrast, __builtin__ is
1076 # always a module object, though it must be explicitly imported.
1074 # always a module object, though it must be explicitly imported.
1077
1075
1078 # For more details:
1076 # For more details:
1079 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1077 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1080 ns = dict(__builtin__ = builtin_mod)
1078 ns = dict(__builtin__ = builtin_mod)
1081
1079
1082 # Put 'help' in the user namespace
1080 # Put 'help' in the user namespace
1083 try:
1081 try:
1084 from site import _Helper
1082 from site import _Helper
1085 ns['help'] = _Helper()
1083 ns['help'] = _Helper()
1086 except ImportError:
1084 except ImportError:
1087 warn('help() not available - check site.py')
1085 warn('help() not available - check site.py')
1088
1086
1089 # make global variables for user access to the histories
1087 # make global variables for user access to the histories
1090 ns['_ih'] = self.history_manager.input_hist_parsed
1088 ns['_ih'] = self.history_manager.input_hist_parsed
1091 ns['_oh'] = self.history_manager.output_hist
1089 ns['_oh'] = self.history_manager.output_hist
1092 ns['_dh'] = self.history_manager.dir_hist
1090 ns['_dh'] = self.history_manager.dir_hist
1093
1091
1094 ns['_sh'] = shadowns
1092 ns['_sh'] = shadowns
1095
1093
1096 # user aliases to input and output histories. These shouldn't show up
1094 # user aliases to input and output histories. These shouldn't show up
1097 # in %who, as they can have very large reprs.
1095 # in %who, as they can have very large reprs.
1098 ns['In'] = self.history_manager.input_hist_parsed
1096 ns['In'] = self.history_manager.input_hist_parsed
1099 ns['Out'] = self.history_manager.output_hist
1097 ns['Out'] = self.history_manager.output_hist
1100
1098
1101 # Store myself as the public api!!!
1099 # Store myself as the public api!!!
1102 ns['get_ipython'] = self.get_ipython
1100 ns['get_ipython'] = self.get_ipython
1103
1101
1104 ns['exit'] = self.exiter
1102 ns['exit'] = self.exiter
1105 ns['quit'] = self.exiter
1103 ns['quit'] = self.exiter
1106
1104
1107 # Sync what we've added so far to user_ns_hidden so these aren't seen
1105 # Sync what we've added so far to user_ns_hidden so these aren't seen
1108 # by %who
1106 # by %who
1109 self.user_ns_hidden.update(ns)
1107 self.user_ns_hidden.update(ns)
1110
1108
1111 # Anything put into ns now would show up in %who. Think twice before
1109 # Anything put into ns now would show up in %who. Think twice before
1112 # putting anything here, as we really want %who to show the user their
1110 # putting anything here, as we really want %who to show the user their
1113 # stuff, not our variables.
1111 # stuff, not our variables.
1114
1112
1115 # Finally, update the real user's namespace
1113 # Finally, update the real user's namespace
1116 self.user_ns.update(ns)
1114 self.user_ns.update(ns)
1117
1115
1118 def reset(self, new_session=True):
1116 def reset(self, new_session=True):
1119 """Clear all internal namespaces, and attempt to release references to
1117 """Clear all internal namespaces, and attempt to release references to
1120 user objects.
1118 user objects.
1121
1119
1122 If new_session is True, a new history session will be opened.
1120 If new_session is True, a new history session will be opened.
1123 """
1121 """
1124 # Clear histories
1122 # Clear histories
1125 self.history_manager.reset(new_session)
1123 self.history_manager.reset(new_session)
1126 # Reset counter used to index all histories
1124 # Reset counter used to index all histories
1127 if new_session:
1125 if new_session:
1128 self.execution_count = 1
1126 self.execution_count = 1
1129
1127
1130 # Flush cached output items
1128 # Flush cached output items
1131 if self.displayhook.do_full_cache:
1129 if self.displayhook.do_full_cache:
1132 self.displayhook.flush()
1130 self.displayhook.flush()
1133
1131
1134 # Restore the user namespaces to minimal usability
1132 # Restore the user namespaces to minimal usability
1135 for ns in self.ns_refs_table:
1133 for ns in self.ns_refs_table:
1136 ns.clear()
1134 ns.clear()
1137
1135
1138 # The main execution namespaces must be cleared very carefully,
1136 # The main execution namespaces must be cleared very carefully,
1139 # skipping the deletion of the builtin-related keys, because doing so
1137 # skipping the deletion of the builtin-related keys, because doing so
1140 # would cause errors in many object's __del__ methods.
1138 # would cause errors in many object's __del__ methods.
1141 for ns in [self.user_ns, self.user_global_ns]:
1139 for ns in [self.user_ns, self.user_global_ns]:
1142 drop_keys = set(ns.keys())
1140 drop_keys = set(ns.keys())
1143 drop_keys.discard('__builtin__')
1141 drop_keys.discard('__builtin__')
1144 drop_keys.discard('__builtins__')
1142 drop_keys.discard('__builtins__')
1145 for k in drop_keys:
1143 for k in drop_keys:
1146 del ns[k]
1144 del ns[k]
1147
1145
1148 # Restore the user namespaces to minimal usability
1146 # Restore the user namespaces to minimal usability
1149 self.init_user_ns()
1147 self.init_user_ns()
1150
1148
1151 # Restore the default and user aliases
1149 # Restore the default and user aliases
1152 self.alias_manager.clear_aliases()
1150 self.alias_manager.clear_aliases()
1153 self.alias_manager.init_aliases()
1151 self.alias_manager.init_aliases()
1154
1152
1155 # Flush the private list of module references kept for script
1153 # Flush the private list of module references kept for script
1156 # execution protection
1154 # execution protection
1157 self.clear_main_mod_cache()
1155 self.clear_main_mod_cache()
1158
1156
1159 # Clear out the namespace from the last %run
1157 # Clear out the namespace from the last %run
1160 self.new_main_mod()
1158 self.new_main_mod()
1161
1159
1162 def del_var(self, varname, by_name=False):
1160 def del_var(self, varname, by_name=False):
1163 """Delete a variable from the various namespaces, so that, as
1161 """Delete a variable from the various namespaces, so that, as
1164 far as possible, we're not keeping any hidden references to it.
1162 far as possible, we're not keeping any hidden references to it.
1165
1163
1166 Parameters
1164 Parameters
1167 ----------
1165 ----------
1168 varname : str
1166 varname : str
1169 The name of the variable to delete.
1167 The name of the variable to delete.
1170 by_name : bool
1168 by_name : bool
1171 If True, delete variables with the given name in each
1169 If True, delete variables with the given name in each
1172 namespace. If False (default), find the variable in the user
1170 namespace. If False (default), find the variable in the user
1173 namespace, and delete references to it.
1171 namespace, and delete references to it.
1174 """
1172 """
1175 if varname in ('__builtin__', '__builtins__'):
1173 if varname in ('__builtin__', '__builtins__'):
1176 raise ValueError("Refusing to delete %s" % varname)
1174 raise ValueError("Refusing to delete %s" % varname)
1177 ns_refs = self.ns_refs_table + [self.user_ns,
1175 ns_refs = self.ns_refs_table + [self.user_ns,
1178 self.user_global_ns, self._user_main_module.__dict__] +\
1176 self.user_global_ns, self._user_main_module.__dict__] +\
1179 self._main_ns_cache.values()
1177 self._main_ns_cache.values()
1180
1178
1181 if by_name: # Delete by name
1179 if by_name: # Delete by name
1182 for ns in ns_refs:
1180 for ns in ns_refs:
1183 try:
1181 try:
1184 del ns[varname]
1182 del ns[varname]
1185 except KeyError:
1183 except KeyError:
1186 pass
1184 pass
1187 else: # Delete by object
1185 else: # Delete by object
1188 try:
1186 try:
1189 obj = self.user_ns[varname]
1187 obj = self.user_ns[varname]
1190 except KeyError:
1188 except KeyError:
1191 raise NameError("name '%s' is not defined" % varname)
1189 raise NameError("name '%s' is not defined" % varname)
1192 # Also check in output history
1190 # Also check in output history
1193 ns_refs.append(self.history_manager.output_hist)
1191 ns_refs.append(self.history_manager.output_hist)
1194 for ns in ns_refs:
1192 for ns in ns_refs:
1195 to_delete = [n for n, o in ns.iteritems() if o is obj]
1193 to_delete = [n for n, o in ns.iteritems() if o is obj]
1196 for name in to_delete:
1194 for name in to_delete:
1197 del ns[name]
1195 del ns[name]
1198
1196
1199 # displayhook keeps extra references, but not in a dictionary
1197 # displayhook keeps extra references, but not in a dictionary
1200 for name in ('_', '__', '___'):
1198 for name in ('_', '__', '___'):
1201 if getattr(self.displayhook, name) is obj:
1199 if getattr(self.displayhook, name) is obj:
1202 setattr(self.displayhook, name, None)
1200 setattr(self.displayhook, name, None)
1203
1201
1204 def reset_selective(self, regex=None):
1202 def reset_selective(self, regex=None):
1205 """Clear selective variables from internal namespaces based on a
1203 """Clear selective variables from internal namespaces based on a
1206 specified regular expression.
1204 specified regular expression.
1207
1205
1208 Parameters
1206 Parameters
1209 ----------
1207 ----------
1210 regex : string or compiled pattern, optional
1208 regex : string or compiled pattern, optional
1211 A regular expression pattern that will be used in searching
1209 A regular expression pattern that will be used in searching
1212 variable names in the users namespaces.
1210 variable names in the users namespaces.
1213 """
1211 """
1214 if regex is not None:
1212 if regex is not None:
1215 try:
1213 try:
1216 m = re.compile(regex)
1214 m = re.compile(regex)
1217 except TypeError:
1215 except TypeError:
1218 raise TypeError('regex must be a string or compiled pattern')
1216 raise TypeError('regex must be a string or compiled pattern')
1219 # Search for keys in each namespace that match the given regex
1217 # Search for keys in each namespace that match the given regex
1220 # If a match is found, delete the key/value pair.
1218 # If a match is found, delete the key/value pair.
1221 for ns in self.ns_refs_table:
1219 for ns in self.ns_refs_table:
1222 for var in ns:
1220 for var in ns:
1223 if m.search(var):
1221 if m.search(var):
1224 del ns[var]
1222 del ns[var]
1225
1223
1226 def push(self, variables, interactive=True):
1224 def push(self, variables, interactive=True):
1227 """Inject a group of variables into the IPython user namespace.
1225 """Inject a group of variables into the IPython user namespace.
1228
1226
1229 Parameters
1227 Parameters
1230 ----------
1228 ----------
1231 variables : dict, str or list/tuple of str
1229 variables : dict, str or list/tuple of str
1232 The variables to inject into the user's namespace. If a dict, a
1230 The variables to inject into the user's namespace. If a dict, a
1233 simple update is done. If a str, the string is assumed to have
1231 simple update is done. If a str, the string is assumed to have
1234 variable names separated by spaces. A list/tuple of str can also
1232 variable names separated by spaces. A list/tuple of str can also
1235 be used to give the variable names. If just the variable names are
1233 be used to give the variable names. If just the variable names are
1236 give (list/tuple/str) then the variable values looked up in the
1234 give (list/tuple/str) then the variable values looked up in the
1237 callers frame.
1235 callers frame.
1238 interactive : bool
1236 interactive : bool
1239 If True (default), the variables will be listed with the ``who``
1237 If True (default), the variables will be listed with the ``who``
1240 magic.
1238 magic.
1241 """
1239 """
1242 vdict = None
1240 vdict = None
1243
1241
1244 # We need a dict of name/value pairs to do namespace updates.
1242 # We need a dict of name/value pairs to do namespace updates.
1245 if isinstance(variables, dict):
1243 if isinstance(variables, dict):
1246 vdict = variables
1244 vdict = variables
1247 elif isinstance(variables, (basestring, list, tuple)):
1245 elif isinstance(variables, (basestring, list, tuple)):
1248 if isinstance(variables, basestring):
1246 if isinstance(variables, basestring):
1249 vlist = variables.split()
1247 vlist = variables.split()
1250 else:
1248 else:
1251 vlist = variables
1249 vlist = variables
1252 vdict = {}
1250 vdict = {}
1253 cf = sys._getframe(1)
1251 cf = sys._getframe(1)
1254 for name in vlist:
1252 for name in vlist:
1255 try:
1253 try:
1256 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1254 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1257 except:
1255 except:
1258 print ('Could not get variable %s from %s' %
1256 print ('Could not get variable %s from %s' %
1259 (name,cf.f_code.co_name))
1257 (name,cf.f_code.co_name))
1260 else:
1258 else:
1261 raise ValueError('variables must be a dict/str/list/tuple')
1259 raise ValueError('variables must be a dict/str/list/tuple')
1262
1260
1263 # Propagate variables to user namespace
1261 # Propagate variables to user namespace
1264 self.user_ns.update(vdict)
1262 self.user_ns.update(vdict)
1265
1263
1266 # And configure interactive visibility
1264 # And configure interactive visibility
1267 config_ns = self.user_ns_hidden
1265 config_ns = self.user_ns_hidden
1268 if interactive:
1266 if interactive:
1269 for name, val in vdict.iteritems():
1267 for name, val in vdict.iteritems():
1270 config_ns.pop(name, None)
1268 config_ns.pop(name, None)
1271 else:
1269 else:
1272 for name,val in vdict.iteritems():
1270 for name,val in vdict.iteritems():
1273 config_ns[name] = val
1271 config_ns[name] = val
1274
1272
1275 def drop_by_id(self, variables):
1273 def drop_by_id(self, variables):
1276 """Remove a dict of variables from the user namespace, if they are the
1274 """Remove a dict of variables from the user namespace, if they are the
1277 same as the values in the dictionary.
1275 same as the values in the dictionary.
1278
1276
1279 This is intended for use by extensions: variables that they've added can
1277 This is intended for use by extensions: variables that they've added can
1280 be taken back out if they are unloaded, without removing any that the
1278 be taken back out if they are unloaded, without removing any that the
1281 user has overwritten.
1279 user has overwritten.
1282
1280
1283 Parameters
1281 Parameters
1284 ----------
1282 ----------
1285 variables : dict
1283 variables : dict
1286 A dictionary mapping object names (as strings) to the objects.
1284 A dictionary mapping object names (as strings) to the objects.
1287 """
1285 """
1288 for name, obj in variables.iteritems():
1286 for name, obj in variables.iteritems():
1289 if name in self.user_ns and self.user_ns[name] is obj:
1287 if name in self.user_ns and self.user_ns[name] is obj:
1290 del self.user_ns[name]
1288 del self.user_ns[name]
1291 self.user_ns_hidden.pop(name, None)
1289 self.user_ns_hidden.pop(name, None)
1292
1290
1293 #-------------------------------------------------------------------------
1291 #-------------------------------------------------------------------------
1294 # Things related to object introspection
1292 # Things related to object introspection
1295 #-------------------------------------------------------------------------
1293 #-------------------------------------------------------------------------
1296
1294
1297 def _ofind(self, oname, namespaces=None):
1295 def _ofind(self, oname, namespaces=None):
1298 """Find an object in the available namespaces.
1296 """Find an object in the available namespaces.
1299
1297
1300 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1298 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1301
1299
1302 Has special code to detect magic functions.
1300 Has special code to detect magic functions.
1303 """
1301 """
1304 oname = oname.strip()
1302 oname = oname.strip()
1305 #print '1- oname: <%r>' % oname # dbg
1303 #print '1- oname: <%r>' % oname # dbg
1306 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1304 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1307 return dict(found=False)
1305 return dict(found=False)
1308
1306
1309 alias_ns = None
1307 alias_ns = None
1310 if namespaces is None:
1308 if namespaces is None:
1311 # Namespaces to search in:
1309 # Namespaces to search in:
1312 # Put them in a list. The order is important so that we
1310 # Put them in a list. The order is important so that we
1313 # find things in the same order that Python finds them.
1311 # find things in the same order that Python finds them.
1314 namespaces = [ ('Interactive', self.user_ns),
1312 namespaces = [ ('Interactive', self.user_ns),
1315 ('IPython internal', self.internal_ns),
1313 ('IPython internal', self.internal_ns),
1316 ('Python builtin', builtin_mod.__dict__),
1314 ('Python builtin', builtin_mod.__dict__),
1317 ('Alias', self.alias_manager.alias_table),
1315 ('Alias', self.alias_manager.alias_table),
1318 ]
1316 ]
1319 alias_ns = self.alias_manager.alias_table
1317 alias_ns = self.alias_manager.alias_table
1320
1318
1321 # initialize results to 'null'
1319 # initialize results to 'null'
1322 found = False; obj = None; ospace = None; ds = None;
1320 found = False; obj = None; ospace = None; ds = None;
1323 ismagic = False; isalias = False; parent = None
1321 ismagic = False; isalias = False; parent = None
1324
1322
1325 # We need to special-case 'print', which as of python2.6 registers as a
1323 # We need to special-case 'print', which as of python2.6 registers as a
1326 # function but should only be treated as one if print_function was
1324 # function but should only be treated as one if print_function was
1327 # loaded with a future import. In this case, just bail.
1325 # loaded with a future import. In this case, just bail.
1328 if (oname == 'print' and not py3compat.PY3 and not \
1326 if (oname == 'print' and not py3compat.PY3 and not \
1329 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1327 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1330 return {'found':found, 'obj':obj, 'namespace':ospace,
1328 return {'found':found, 'obj':obj, 'namespace':ospace,
1331 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1329 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1332
1330
1333 # Look for the given name by splitting it in parts. If the head is
1331 # Look for the given name by splitting it in parts. If the head is
1334 # found, then we look for all the remaining parts as members, and only
1332 # found, then we look for all the remaining parts as members, and only
1335 # declare success if we can find them all.
1333 # declare success if we can find them all.
1336 oname_parts = oname.split('.')
1334 oname_parts = oname.split('.')
1337 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1335 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1338 for nsname,ns in namespaces:
1336 for nsname,ns in namespaces:
1339 try:
1337 try:
1340 obj = ns[oname_head]
1338 obj = ns[oname_head]
1341 except KeyError:
1339 except KeyError:
1342 continue
1340 continue
1343 else:
1341 else:
1344 #print 'oname_rest:', oname_rest # dbg
1342 #print 'oname_rest:', oname_rest # dbg
1345 for part in oname_rest:
1343 for part in oname_rest:
1346 try:
1344 try:
1347 parent = obj
1345 parent = obj
1348 obj = getattr(obj,part)
1346 obj = getattr(obj,part)
1349 except:
1347 except:
1350 # Blanket except b/c some badly implemented objects
1348 # Blanket except b/c some badly implemented objects
1351 # allow __getattr__ to raise exceptions other than
1349 # allow __getattr__ to raise exceptions other than
1352 # AttributeError, which then crashes IPython.
1350 # AttributeError, which then crashes IPython.
1353 break
1351 break
1354 else:
1352 else:
1355 # If we finish the for loop (no break), we got all members
1353 # If we finish the for loop (no break), we got all members
1356 found = True
1354 found = True
1357 ospace = nsname
1355 ospace = nsname
1358 if ns == alias_ns:
1356 if ns == alias_ns:
1359 isalias = True
1357 isalias = True
1360 break # namespace loop
1358 break # namespace loop
1361
1359
1362 # Try to see if it's magic
1360 # Try to see if it's magic
1363 if not found:
1361 if not found:
1364 if oname.startswith(ESC_MAGIC):
1362 if oname.startswith(ESC_MAGIC):
1365 oname = oname[1:]
1363 oname = oname[1:]
1366 obj = getattr(self,'magic_'+oname,None)
1364 obj = getattr(self,'magic_'+oname,None)
1367 if obj is not None:
1365 if obj is not None:
1368 found = True
1366 found = True
1369 ospace = 'IPython internal'
1367 ospace = 'IPython internal'
1370 ismagic = True
1368 ismagic = True
1371
1369
1372 # Last try: special-case some literals like '', [], {}, etc:
1370 # Last try: special-case some literals like '', [], {}, etc:
1373 if not found and oname_head in ["''",'""','[]','{}','()']:
1371 if not found and oname_head in ["''",'""','[]','{}','()']:
1374 obj = eval(oname_head)
1372 obj = eval(oname_head)
1375 found = True
1373 found = True
1376 ospace = 'Interactive'
1374 ospace = 'Interactive'
1377
1375
1378 return {'found':found, 'obj':obj, 'namespace':ospace,
1376 return {'found':found, 'obj':obj, 'namespace':ospace,
1379 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1377 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1380
1378
1381 def _ofind_property(self, oname, info):
1379 def _ofind_property(self, oname, info):
1382 """Second part of object finding, to look for property details."""
1380 """Second part of object finding, to look for property details."""
1383 if info.found:
1381 if info.found:
1384 # Get the docstring of the class property if it exists.
1382 # Get the docstring of the class property if it exists.
1385 path = oname.split('.')
1383 path = oname.split('.')
1386 root = '.'.join(path[:-1])
1384 root = '.'.join(path[:-1])
1387 if info.parent is not None:
1385 if info.parent is not None:
1388 try:
1386 try:
1389 target = getattr(info.parent, '__class__')
1387 target = getattr(info.parent, '__class__')
1390 # The object belongs to a class instance.
1388 # The object belongs to a class instance.
1391 try:
1389 try:
1392 target = getattr(target, path[-1])
1390 target = getattr(target, path[-1])
1393 # The class defines the object.
1391 # The class defines the object.
1394 if isinstance(target, property):
1392 if isinstance(target, property):
1395 oname = root + '.__class__.' + path[-1]
1393 oname = root + '.__class__.' + path[-1]
1396 info = Struct(self._ofind(oname))
1394 info = Struct(self._ofind(oname))
1397 except AttributeError: pass
1395 except AttributeError: pass
1398 except AttributeError: pass
1396 except AttributeError: pass
1399
1397
1400 # We return either the new info or the unmodified input if the object
1398 # We return either the new info or the unmodified input if the object
1401 # hadn't been found
1399 # hadn't been found
1402 return info
1400 return info
1403
1401
1404 def _object_find(self, oname, namespaces=None):
1402 def _object_find(self, oname, namespaces=None):
1405 """Find an object and return a struct with info about it."""
1403 """Find an object and return a struct with info about it."""
1406 inf = Struct(self._ofind(oname, namespaces))
1404 inf = Struct(self._ofind(oname, namespaces))
1407 return Struct(self._ofind_property(oname, inf))
1405 return Struct(self._ofind_property(oname, inf))
1408
1406
1409 def _inspect(self, meth, oname, namespaces=None, **kw):
1407 def _inspect(self, meth, oname, namespaces=None, **kw):
1410 """Generic interface to the inspector system.
1408 """Generic interface to the inspector system.
1411
1409
1412 This function is meant to be called by pdef, pdoc & friends."""
1410 This function is meant to be called by pdef, pdoc & friends."""
1413 info = self._object_find(oname)
1411 info = self._object_find(oname)
1414 if info.found:
1412 if info.found:
1415 pmethod = getattr(self.inspector, meth)
1413 pmethod = getattr(self.inspector, meth)
1416 formatter = format_screen if info.ismagic else None
1414 formatter = format_screen if info.ismagic else None
1417 if meth == 'pdoc':
1415 if meth == 'pdoc':
1418 pmethod(info.obj, oname, formatter)
1416 pmethod(info.obj, oname, formatter)
1419 elif meth == 'pinfo':
1417 elif meth == 'pinfo':
1420 pmethod(info.obj, oname, formatter, info, **kw)
1418 pmethod(info.obj, oname, formatter, info, **kw)
1421 else:
1419 else:
1422 pmethod(info.obj, oname)
1420 pmethod(info.obj, oname)
1423 else:
1421 else:
1424 print 'Object `%s` not found.' % oname
1422 print 'Object `%s` not found.' % oname
1425 return 'not found' # so callers can take other action
1423 return 'not found' # so callers can take other action
1426
1424
1427 def object_inspect(self, oname):
1425 def object_inspect(self, oname):
1428 with self.builtin_trap:
1426 with self.builtin_trap:
1429 info = self._object_find(oname)
1427 info = self._object_find(oname)
1430 if info.found:
1428 if info.found:
1431 return self.inspector.info(info.obj, oname, info=info)
1429 return self.inspector.info(info.obj, oname, info=info)
1432 else:
1430 else:
1433 return oinspect.object_info(name=oname, found=False)
1431 return oinspect.object_info(name=oname, found=False)
1434
1432
1435 #-------------------------------------------------------------------------
1433 #-------------------------------------------------------------------------
1436 # Things related to history management
1434 # Things related to history management
1437 #-------------------------------------------------------------------------
1435 #-------------------------------------------------------------------------
1438
1436
1439 def init_history(self):
1437 def init_history(self):
1440 """Sets up the command history, and starts regular autosaves."""
1438 """Sets up the command history, and starts regular autosaves."""
1441 self.history_manager = HistoryManager(shell=self, config=self.config)
1439 self.history_manager = HistoryManager(shell=self, config=self.config)
1442 self.configurables.append(self.history_manager)
1440 self.configurables.append(self.history_manager)
1443
1441
1444 #-------------------------------------------------------------------------
1442 #-------------------------------------------------------------------------
1445 # Things related to exception handling and tracebacks (not debugging)
1443 # Things related to exception handling and tracebacks (not debugging)
1446 #-------------------------------------------------------------------------
1444 #-------------------------------------------------------------------------
1447
1445
1448 def init_traceback_handlers(self, custom_exceptions):
1446 def init_traceback_handlers(self, custom_exceptions):
1449 # Syntax error handler.
1447 # Syntax error handler.
1450 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1448 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1451
1449
1452 # The interactive one is initialized with an offset, meaning we always
1450 # The interactive one is initialized with an offset, meaning we always
1453 # want to remove the topmost item in the traceback, which is our own
1451 # want to remove the topmost item in the traceback, which is our own
1454 # internal code. Valid modes: ['Plain','Context','Verbose']
1452 # internal code. Valid modes: ['Plain','Context','Verbose']
1455 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1453 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1456 color_scheme='NoColor',
1454 color_scheme='NoColor',
1457 tb_offset = 1,
1455 tb_offset = 1,
1458 check_cache=self.compile.check_cache)
1456 check_cache=self.compile.check_cache)
1459
1457
1460 # The instance will store a pointer to the system-wide exception hook,
1458 # The instance will store a pointer to the system-wide exception hook,
1461 # so that runtime code (such as magics) can access it. This is because
1459 # so that runtime code (such as magics) can access it. This is because
1462 # during the read-eval loop, it may get temporarily overwritten.
1460 # during the read-eval loop, it may get temporarily overwritten.
1463 self.sys_excepthook = sys.excepthook
1461 self.sys_excepthook = sys.excepthook
1464
1462
1465 # and add any custom exception handlers the user may have specified
1463 # and add any custom exception handlers the user may have specified
1466 self.set_custom_exc(*custom_exceptions)
1464 self.set_custom_exc(*custom_exceptions)
1467
1465
1468 # Set the exception mode
1466 # Set the exception mode
1469 self.InteractiveTB.set_mode(mode=self.xmode)
1467 self.InteractiveTB.set_mode(mode=self.xmode)
1470
1468
1471 def set_custom_exc(self, exc_tuple, handler):
1469 def set_custom_exc(self, exc_tuple, handler):
1472 """set_custom_exc(exc_tuple,handler)
1470 """set_custom_exc(exc_tuple,handler)
1473
1471
1474 Set a custom exception handler, which will be called if any of the
1472 Set a custom exception handler, which will be called if any of the
1475 exceptions in exc_tuple occur in the mainloop (specifically, in the
1473 exceptions in exc_tuple occur in the mainloop (specifically, in the
1476 run_code() method).
1474 run_code() method).
1477
1475
1478 Parameters
1476 Parameters
1479 ----------
1477 ----------
1480
1478
1481 exc_tuple : tuple of exception classes
1479 exc_tuple : tuple of exception classes
1482 A *tuple* of exception classes, for which to call the defined
1480 A *tuple* of exception classes, for which to call the defined
1483 handler. It is very important that you use a tuple, and NOT A
1481 handler. It is very important that you use a tuple, and NOT A
1484 LIST here, because of the way Python's except statement works. If
1482 LIST here, because of the way Python's except statement works. If
1485 you only want to trap a single exception, use a singleton tuple::
1483 you only want to trap a single exception, use a singleton tuple::
1486
1484
1487 exc_tuple == (MyCustomException,)
1485 exc_tuple == (MyCustomException,)
1488
1486
1489 handler : callable
1487 handler : callable
1490 handler must have the following signature::
1488 handler must have the following signature::
1491
1489
1492 def my_handler(self, etype, value, tb, tb_offset=None):
1490 def my_handler(self, etype, value, tb, tb_offset=None):
1493 ...
1491 ...
1494 return structured_traceback
1492 return structured_traceback
1495
1493
1496 Your handler must return a structured traceback (a list of strings),
1494 Your handler must return a structured traceback (a list of strings),
1497 or None.
1495 or None.
1498
1496
1499 This will be made into an instance method (via types.MethodType)
1497 This will be made into an instance method (via types.MethodType)
1500 of IPython itself, and it will be called if any of the exceptions
1498 of IPython itself, and it will be called if any of the exceptions
1501 listed in the exc_tuple are caught. If the handler is None, an
1499 listed in the exc_tuple are caught. If the handler is None, an
1502 internal basic one is used, which just prints basic info.
1500 internal basic one is used, which just prints basic info.
1503
1501
1504 To protect IPython from crashes, if your handler ever raises an
1502 To protect IPython from crashes, if your handler ever raises an
1505 exception or returns an invalid result, it will be immediately
1503 exception or returns an invalid result, it will be immediately
1506 disabled.
1504 disabled.
1507
1505
1508 WARNING: by putting in your own exception handler into IPython's main
1506 WARNING: by putting in your own exception handler into IPython's main
1509 execution loop, you run a very good chance of nasty crashes. This
1507 execution loop, you run a very good chance of nasty crashes. This
1510 facility should only be used if you really know what you are doing."""
1508 facility should only be used if you really know what you are doing."""
1511
1509
1512 assert type(exc_tuple)==type(()) , \
1510 assert type(exc_tuple)==type(()) , \
1513 "The custom exceptions must be given AS A TUPLE."
1511 "The custom exceptions must be given AS A TUPLE."
1514
1512
1515 def dummy_handler(self,etype,value,tb,tb_offset=None):
1513 def dummy_handler(self,etype,value,tb,tb_offset=None):
1516 print '*** Simple custom exception handler ***'
1514 print '*** Simple custom exception handler ***'
1517 print 'Exception type :',etype
1515 print 'Exception type :',etype
1518 print 'Exception value:',value
1516 print 'Exception value:',value
1519 print 'Traceback :',tb
1517 print 'Traceback :',tb
1520 #print 'Source code :','\n'.join(self.buffer)
1518 #print 'Source code :','\n'.join(self.buffer)
1521
1519
1522 def validate_stb(stb):
1520 def validate_stb(stb):
1523 """validate structured traceback return type
1521 """validate structured traceback return type
1524
1522
1525 return type of CustomTB *should* be a list of strings, but allow
1523 return type of CustomTB *should* be a list of strings, but allow
1526 single strings or None, which are harmless.
1524 single strings or None, which are harmless.
1527
1525
1528 This function will *always* return a list of strings,
1526 This function will *always* return a list of strings,
1529 and will raise a TypeError if stb is inappropriate.
1527 and will raise a TypeError if stb is inappropriate.
1530 """
1528 """
1531 msg = "CustomTB must return list of strings, not %r" % stb
1529 msg = "CustomTB must return list of strings, not %r" % stb
1532 if stb is None:
1530 if stb is None:
1533 return []
1531 return []
1534 elif isinstance(stb, basestring):
1532 elif isinstance(stb, basestring):
1535 return [stb]
1533 return [stb]
1536 elif not isinstance(stb, list):
1534 elif not isinstance(stb, list):
1537 raise TypeError(msg)
1535 raise TypeError(msg)
1538 # it's a list
1536 # it's a list
1539 for line in stb:
1537 for line in stb:
1540 # check every element
1538 # check every element
1541 if not isinstance(line, basestring):
1539 if not isinstance(line, basestring):
1542 raise TypeError(msg)
1540 raise TypeError(msg)
1543 return stb
1541 return stb
1544
1542
1545 if handler is None:
1543 if handler is None:
1546 wrapped = dummy_handler
1544 wrapped = dummy_handler
1547 else:
1545 else:
1548 def wrapped(self,etype,value,tb,tb_offset=None):
1546 def wrapped(self,etype,value,tb,tb_offset=None):
1549 """wrap CustomTB handler, to protect IPython from user code
1547 """wrap CustomTB handler, to protect IPython from user code
1550
1548
1551 This makes it harder (but not impossible) for custom exception
1549 This makes it harder (but not impossible) for custom exception
1552 handlers to crash IPython.
1550 handlers to crash IPython.
1553 """
1551 """
1554 try:
1552 try:
1555 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1553 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1556 return validate_stb(stb)
1554 return validate_stb(stb)
1557 except:
1555 except:
1558 # clear custom handler immediately
1556 # clear custom handler immediately
1559 self.set_custom_exc((), None)
1557 self.set_custom_exc((), None)
1560 print >> io.stderr, "Custom TB Handler failed, unregistering"
1558 print >> io.stderr, "Custom TB Handler failed, unregistering"
1561 # show the exception in handler first
1559 # show the exception in handler first
1562 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1560 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1563 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1561 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1564 print >> io.stdout, "The original exception:"
1562 print >> io.stdout, "The original exception:"
1565 stb = self.InteractiveTB.structured_traceback(
1563 stb = self.InteractiveTB.structured_traceback(
1566 (etype,value,tb), tb_offset=tb_offset
1564 (etype,value,tb), tb_offset=tb_offset
1567 )
1565 )
1568 return stb
1566 return stb
1569
1567
1570 self.CustomTB = types.MethodType(wrapped,self)
1568 self.CustomTB = types.MethodType(wrapped,self)
1571 self.custom_exceptions = exc_tuple
1569 self.custom_exceptions = exc_tuple
1572
1570
1573 def excepthook(self, etype, value, tb):
1571 def excepthook(self, etype, value, tb):
1574 """One more defense for GUI apps that call sys.excepthook.
1572 """One more defense for GUI apps that call sys.excepthook.
1575
1573
1576 GUI frameworks like wxPython trap exceptions and call
1574 GUI frameworks like wxPython trap exceptions and call
1577 sys.excepthook themselves. I guess this is a feature that
1575 sys.excepthook themselves. I guess this is a feature that
1578 enables them to keep running after exceptions that would
1576 enables them to keep running after exceptions that would
1579 otherwise kill their mainloop. This is a bother for IPython
1577 otherwise kill their mainloop. This is a bother for IPython
1580 which excepts to catch all of the program exceptions with a try:
1578 which excepts to catch all of the program exceptions with a try:
1581 except: statement.
1579 except: statement.
1582
1580
1583 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1581 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1584 any app directly invokes sys.excepthook, it will look to the user like
1582 any app directly invokes sys.excepthook, it will look to the user like
1585 IPython crashed. In order to work around this, we can disable the
1583 IPython crashed. In order to work around this, we can disable the
1586 CrashHandler and replace it with this excepthook instead, which prints a
1584 CrashHandler and replace it with this excepthook instead, which prints a
1587 regular traceback using our InteractiveTB. In this fashion, apps which
1585 regular traceback using our InteractiveTB. In this fashion, apps which
1588 call sys.excepthook will generate a regular-looking exception from
1586 call sys.excepthook will generate a regular-looking exception from
1589 IPython, and the CrashHandler will only be triggered by real IPython
1587 IPython, and the CrashHandler will only be triggered by real IPython
1590 crashes.
1588 crashes.
1591
1589
1592 This hook should be used sparingly, only in places which are not likely
1590 This hook should be used sparingly, only in places which are not likely
1593 to be true IPython errors.
1591 to be true IPython errors.
1594 """
1592 """
1595 self.showtraceback((etype,value,tb),tb_offset=0)
1593 self.showtraceback((etype,value,tb),tb_offset=0)
1596
1594
1597 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1595 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1598 exception_only=False):
1596 exception_only=False):
1599 """Display the exception that just occurred.
1597 """Display the exception that just occurred.
1600
1598
1601 If nothing is known about the exception, this is the method which
1599 If nothing is known about the exception, this is the method which
1602 should be used throughout the code for presenting user tracebacks,
1600 should be used throughout the code for presenting user tracebacks,
1603 rather than directly invoking the InteractiveTB object.
1601 rather than directly invoking the InteractiveTB object.
1604
1602
1605 A specific showsyntaxerror() also exists, but this method can take
1603 A specific showsyntaxerror() also exists, but this method can take
1606 care of calling it if needed, so unless you are explicitly catching a
1604 care of calling it if needed, so unless you are explicitly catching a
1607 SyntaxError exception, don't try to analyze the stack manually and
1605 SyntaxError exception, don't try to analyze the stack manually and
1608 simply call this method."""
1606 simply call this method."""
1609
1607
1610 try:
1608 try:
1611 if exc_tuple is None:
1609 if exc_tuple is None:
1612 etype, value, tb = sys.exc_info()
1610 etype, value, tb = sys.exc_info()
1613 else:
1611 else:
1614 etype, value, tb = exc_tuple
1612 etype, value, tb = exc_tuple
1615
1613
1616 if etype is None:
1614 if etype is None:
1617 if hasattr(sys, 'last_type'):
1615 if hasattr(sys, 'last_type'):
1618 etype, value, tb = sys.last_type, sys.last_value, \
1616 etype, value, tb = sys.last_type, sys.last_value, \
1619 sys.last_traceback
1617 sys.last_traceback
1620 else:
1618 else:
1621 self.write_err('No traceback available to show.\n')
1619 self.write_err('No traceback available to show.\n')
1622 return
1620 return
1623
1621
1624 if etype is SyntaxError:
1622 if etype is SyntaxError:
1625 # Though this won't be called by syntax errors in the input
1623 # Though this won't be called by syntax errors in the input
1626 # line, there may be SyntaxError cases with imported code.
1624 # line, there may be SyntaxError cases with imported code.
1627 self.showsyntaxerror(filename)
1625 self.showsyntaxerror(filename)
1628 elif etype is UsageError:
1626 elif etype is UsageError:
1629 self.write_err("UsageError: %s" % value)
1627 self.write_err("UsageError: %s" % value)
1630 else:
1628 else:
1631 # WARNING: these variables are somewhat deprecated and not
1629 # WARNING: these variables are somewhat deprecated and not
1632 # necessarily safe to use in a threaded environment, but tools
1630 # necessarily safe to use in a threaded environment, but tools
1633 # like pdb depend on their existence, so let's set them. If we
1631 # like pdb depend on their existence, so let's set them. If we
1634 # find problems in the field, we'll need to revisit their use.
1632 # find problems in the field, we'll need to revisit their use.
1635 sys.last_type = etype
1633 sys.last_type = etype
1636 sys.last_value = value
1634 sys.last_value = value
1637 sys.last_traceback = tb
1635 sys.last_traceback = tb
1638 if etype in self.custom_exceptions:
1636 if etype in self.custom_exceptions:
1639 stb = self.CustomTB(etype, value, tb, tb_offset)
1637 stb = self.CustomTB(etype, value, tb, tb_offset)
1640 else:
1638 else:
1641 if exception_only:
1639 if exception_only:
1642 stb = ['An exception has occurred, use %tb to see '
1640 stb = ['An exception has occurred, use %tb to see '
1643 'the full traceback.\n']
1641 'the full traceback.\n']
1644 stb.extend(self.InteractiveTB.get_exception_only(etype,
1642 stb.extend(self.InteractiveTB.get_exception_only(etype,
1645 value))
1643 value))
1646 else:
1644 else:
1647 stb = self.InteractiveTB.structured_traceback(etype,
1645 stb = self.InteractiveTB.structured_traceback(etype,
1648 value, tb, tb_offset=tb_offset)
1646 value, tb, tb_offset=tb_offset)
1649
1647
1650 self._showtraceback(etype, value, stb)
1648 self._showtraceback(etype, value, stb)
1651 if self.call_pdb:
1649 if self.call_pdb:
1652 # drop into debugger
1650 # drop into debugger
1653 self.debugger(force=True)
1651 self.debugger(force=True)
1654 return
1652 return
1655
1653
1656 # Actually show the traceback
1654 # Actually show the traceback
1657 self._showtraceback(etype, value, stb)
1655 self._showtraceback(etype, value, stb)
1658
1656
1659 except KeyboardInterrupt:
1657 except KeyboardInterrupt:
1660 self.write_err("\nKeyboardInterrupt\n")
1658 self.write_err("\nKeyboardInterrupt\n")
1661
1659
1662 def _showtraceback(self, etype, evalue, stb):
1660 def _showtraceback(self, etype, evalue, stb):
1663 """Actually show a traceback.
1661 """Actually show a traceback.
1664
1662
1665 Subclasses may override this method to put the traceback on a different
1663 Subclasses may override this method to put the traceback on a different
1666 place, like a side channel.
1664 place, like a side channel.
1667 """
1665 """
1668 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1666 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1669
1667
1670 def showsyntaxerror(self, filename=None):
1668 def showsyntaxerror(self, filename=None):
1671 """Display the syntax error that just occurred.
1669 """Display the syntax error that just occurred.
1672
1670
1673 This doesn't display a stack trace because there isn't one.
1671 This doesn't display a stack trace because there isn't one.
1674
1672
1675 If a filename is given, it is stuffed in the exception instead
1673 If a filename is given, it is stuffed in the exception instead
1676 of what was there before (because Python's parser always uses
1674 of what was there before (because Python's parser always uses
1677 "<string>" when reading from a string).
1675 "<string>" when reading from a string).
1678 """
1676 """
1679 etype, value, last_traceback = sys.exc_info()
1677 etype, value, last_traceback = sys.exc_info()
1680
1678
1681 # See note about these variables in showtraceback() above
1679 # See note about these variables in showtraceback() above
1682 sys.last_type = etype
1680 sys.last_type = etype
1683 sys.last_value = value
1681 sys.last_value = value
1684 sys.last_traceback = last_traceback
1682 sys.last_traceback = last_traceback
1685
1683
1686 if filename and etype is SyntaxError:
1684 if filename and etype is SyntaxError:
1687 # Work hard to stuff the correct filename in the exception
1685 # Work hard to stuff the correct filename in the exception
1688 try:
1686 try:
1689 msg, (dummy_filename, lineno, offset, line) = value
1687 msg, (dummy_filename, lineno, offset, line) = value
1690 except:
1688 except:
1691 # Not the format we expect; leave it alone
1689 # Not the format we expect; leave it alone
1692 pass
1690 pass
1693 else:
1691 else:
1694 # Stuff in the right filename
1692 # Stuff in the right filename
1695 try:
1693 try:
1696 # Assume SyntaxError is a class exception
1694 # Assume SyntaxError is a class exception
1697 value = SyntaxError(msg, (filename, lineno, offset, line))
1695 value = SyntaxError(msg, (filename, lineno, offset, line))
1698 except:
1696 except:
1699 # If that failed, assume SyntaxError is a string
1697 # If that failed, assume SyntaxError is a string
1700 value = msg, (filename, lineno, offset, line)
1698 value = msg, (filename, lineno, offset, line)
1701 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1699 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1702 self._showtraceback(etype, value, stb)
1700 self._showtraceback(etype, value, stb)
1703
1701
1704 # This is overridden in TerminalInteractiveShell to show a message about
1702 # This is overridden in TerminalInteractiveShell to show a message about
1705 # the %paste magic.
1703 # the %paste magic.
1706 def showindentationerror(self):
1704 def showindentationerror(self):
1707 """Called by run_cell when there's an IndentationError in code entered
1705 """Called by run_cell when there's an IndentationError in code entered
1708 at the prompt.
1706 at the prompt.
1709
1707
1710 This is overridden in TerminalInteractiveShell to show a message about
1708 This is overridden in TerminalInteractiveShell to show a message about
1711 the %paste magic."""
1709 the %paste magic."""
1712 self.showsyntaxerror()
1710 self.showsyntaxerror()
1713
1711
1714 #-------------------------------------------------------------------------
1712 #-------------------------------------------------------------------------
1715 # Things related to readline
1713 # Things related to readline
1716 #-------------------------------------------------------------------------
1714 #-------------------------------------------------------------------------
1717
1715
1718 def init_readline(self):
1716 def init_readline(self):
1719 """Command history completion/saving/reloading."""
1717 """Command history completion/saving/reloading."""
1720
1718
1721 if self.readline_use:
1719 if self.readline_use:
1722 import IPython.utils.rlineimpl as readline
1720 import IPython.utils.rlineimpl as readline
1723
1721
1724 self.rl_next_input = None
1722 self.rl_next_input = None
1725 self.rl_do_indent = False
1723 self.rl_do_indent = False
1726
1724
1727 if not self.readline_use or not readline.have_readline:
1725 if not self.readline_use or not readline.have_readline:
1728 self.has_readline = False
1726 self.has_readline = False
1729 self.readline = None
1727 self.readline = None
1730 # Set a number of methods that depend on readline to be no-op
1728 # Set a number of methods that depend on readline to be no-op
1731 self.readline_no_record = no_op_context
1729 self.readline_no_record = no_op_context
1732 self.set_readline_completer = no_op
1730 self.set_readline_completer = no_op
1733 self.set_custom_completer = no_op
1731 self.set_custom_completer = no_op
1734 self.set_completer_frame = no_op
1732 self.set_completer_frame = no_op
1735 if self.readline_use:
1733 if self.readline_use:
1736 warn('Readline services not available or not loaded.')
1734 warn('Readline services not available or not loaded.')
1737 else:
1735 else:
1738 self.has_readline = True
1736 self.has_readline = True
1739 self.readline = readline
1737 self.readline = readline
1740 sys.modules['readline'] = readline
1738 sys.modules['readline'] = readline
1741
1739
1742 # Platform-specific configuration
1740 # Platform-specific configuration
1743 if os.name == 'nt':
1741 if os.name == 'nt':
1744 # FIXME - check with Frederick to see if we can harmonize
1742 # FIXME - check with Frederick to see if we can harmonize
1745 # naming conventions with pyreadline to avoid this
1743 # naming conventions with pyreadline to avoid this
1746 # platform-dependent check
1744 # platform-dependent check
1747 self.readline_startup_hook = readline.set_pre_input_hook
1745 self.readline_startup_hook = readline.set_pre_input_hook
1748 else:
1746 else:
1749 self.readline_startup_hook = readline.set_startup_hook
1747 self.readline_startup_hook = readline.set_startup_hook
1750
1748
1751 # Load user's initrc file (readline config)
1749 # Load user's initrc file (readline config)
1752 # Or if libedit is used, load editrc.
1750 # Or if libedit is used, load editrc.
1753 inputrc_name = os.environ.get('INPUTRC')
1751 inputrc_name = os.environ.get('INPUTRC')
1754 if inputrc_name is None:
1752 if inputrc_name is None:
1755 home_dir = get_home_dir()
1753 home_dir = get_home_dir()
1756 if home_dir is not None:
1754 if home_dir is not None:
1757 inputrc_name = '.inputrc'
1755 inputrc_name = '.inputrc'
1758 if readline.uses_libedit:
1756 if readline.uses_libedit:
1759 inputrc_name = '.editrc'
1757 inputrc_name = '.editrc'
1760 inputrc_name = os.path.join(home_dir, inputrc_name)
1758 inputrc_name = os.path.join(home_dir, inputrc_name)
1761 if os.path.isfile(inputrc_name):
1759 if os.path.isfile(inputrc_name):
1762 try:
1760 try:
1763 readline.read_init_file(inputrc_name)
1761 readline.read_init_file(inputrc_name)
1764 except:
1762 except:
1765 warn('Problems reading readline initialization file <%s>'
1763 warn('Problems reading readline initialization file <%s>'
1766 % inputrc_name)
1764 % inputrc_name)
1767
1765
1768 # Configure readline according to user's prefs
1766 # Configure readline according to user's prefs
1769 # This is only done if GNU readline is being used. If libedit
1767 # This is only done if GNU readline is being used. If libedit
1770 # is being used (as on Leopard) the readline config is
1768 # is being used (as on Leopard) the readline config is
1771 # not run as the syntax for libedit is different.
1769 # not run as the syntax for libedit is different.
1772 if not readline.uses_libedit:
1770 if not readline.uses_libedit:
1773 for rlcommand in self.readline_parse_and_bind:
1771 for rlcommand in self.readline_parse_and_bind:
1774 #print "loading rl:",rlcommand # dbg
1772 #print "loading rl:",rlcommand # dbg
1775 readline.parse_and_bind(rlcommand)
1773 readline.parse_and_bind(rlcommand)
1776
1774
1777 # Remove some chars from the delimiters list. If we encounter
1775 # Remove some chars from the delimiters list. If we encounter
1778 # unicode chars, discard them.
1776 # unicode chars, discard them.
1779 delims = readline.get_completer_delims()
1777 delims = readline.get_completer_delims()
1780 if not py3compat.PY3:
1778 if not py3compat.PY3:
1781 delims = delims.encode("ascii", "ignore")
1779 delims = delims.encode("ascii", "ignore")
1782 for d in self.readline_remove_delims:
1780 for d in self.readline_remove_delims:
1783 delims = delims.replace(d, "")
1781 delims = delims.replace(d, "")
1784 delims = delims.replace(ESC_MAGIC, '')
1782 delims = delims.replace(ESC_MAGIC, '')
1785 readline.set_completer_delims(delims)
1783 readline.set_completer_delims(delims)
1786 # otherwise we end up with a monster history after a while:
1784 # otherwise we end up with a monster history after a while:
1787 readline.set_history_length(self.history_length)
1785 readline.set_history_length(self.history_length)
1788
1786
1789 self.refill_readline_hist()
1787 self.refill_readline_hist()
1790 self.readline_no_record = ReadlineNoRecord(self)
1788 self.readline_no_record = ReadlineNoRecord(self)
1791
1789
1792 # Configure auto-indent for all platforms
1790 # Configure auto-indent for all platforms
1793 self.set_autoindent(self.autoindent)
1791 self.set_autoindent(self.autoindent)
1794
1792
1795 def refill_readline_hist(self):
1793 def refill_readline_hist(self):
1796 # Load the last 1000 lines from history
1794 # Load the last 1000 lines from history
1797 self.readline.clear_history()
1795 self.readline.clear_history()
1798 stdin_encoding = sys.stdin.encoding or "utf-8"
1796 stdin_encoding = sys.stdin.encoding or "utf-8"
1799 for _, _, cell in self.history_manager.get_tail(1000,
1797 for _, _, cell in self.history_manager.get_tail(1000,
1800 include_latest=True):
1798 include_latest=True):
1801 if cell.strip(): # Ignore blank lines
1799 if cell.strip(): # Ignore blank lines
1802 if self.multiline_history:
1800 if self.multiline_history:
1803 self.readline.add_history(py3compat.unicode_to_str(cell.rstrip(),
1801 self.readline.add_history(py3compat.unicode_to_str(cell.rstrip(),
1804 stdin_encoding))
1802 stdin_encoding))
1805 else:
1803 else:
1806 for line in cell.splitlines():
1804 for line in cell.splitlines():
1807 self.readline.add_history(py3compat.unicode_to_str(line,
1805 self.readline.add_history(py3compat.unicode_to_str(line,
1808 stdin_encoding))
1806 stdin_encoding))
1809
1807
1810 def set_next_input(self, s):
1808 def set_next_input(self, s):
1811 """ Sets the 'default' input string for the next command line.
1809 """ Sets the 'default' input string for the next command line.
1812
1810
1813 Requires readline.
1811 Requires readline.
1814
1812
1815 Example:
1813 Example:
1816
1814
1817 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1815 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1818 [D:\ipython]|2> Hello Word_ # cursor is here
1816 [D:\ipython]|2> Hello Word_ # cursor is here
1819 """
1817 """
1820 if isinstance(s, unicode):
1818 if isinstance(s, unicode):
1821 s = s.encode(self.stdin_encoding, 'replace')
1819 s = s.encode(self.stdin_encoding, 'replace')
1822 self.rl_next_input = s
1820 self.rl_next_input = s
1823
1821
1824 # Maybe move this to the terminal subclass?
1822 # Maybe move this to the terminal subclass?
1825 def pre_readline(self):
1823 def pre_readline(self):
1826 """readline hook to be used at the start of each line.
1824 """readline hook to be used at the start of each line.
1827
1825
1828 Currently it handles auto-indent only."""
1826 Currently it handles auto-indent only."""
1829
1827
1830 if self.rl_do_indent:
1828 if self.rl_do_indent:
1831 self.readline.insert_text(self._indent_current_str())
1829 self.readline.insert_text(self._indent_current_str())
1832 if self.rl_next_input is not None:
1830 if self.rl_next_input is not None:
1833 self.readline.insert_text(self.rl_next_input)
1831 self.readline.insert_text(self.rl_next_input)
1834 self.rl_next_input = None
1832 self.rl_next_input = None
1835
1833
1836 def _indent_current_str(self):
1834 def _indent_current_str(self):
1837 """return the current level of indentation as a string"""
1835 """return the current level of indentation as a string"""
1838 return self.input_splitter.indent_spaces * ' '
1836 return self.input_splitter.indent_spaces * ' '
1839
1837
1840 #-------------------------------------------------------------------------
1838 #-------------------------------------------------------------------------
1841 # Things related to text completion
1839 # Things related to text completion
1842 #-------------------------------------------------------------------------
1840 #-------------------------------------------------------------------------
1843
1841
1844 def init_completer(self):
1842 def init_completer(self):
1845 """Initialize the completion machinery.
1843 """Initialize the completion machinery.
1846
1844
1847 This creates completion machinery that can be used by client code,
1845 This creates completion machinery that can be used by client code,
1848 either interactively in-process (typically triggered by the readline
1846 either interactively in-process (typically triggered by the readline
1849 library), programatically (such as in test suites) or out-of-prcess
1847 library), programatically (such as in test suites) or out-of-prcess
1850 (typically over the network by remote frontends).
1848 (typically over the network by remote frontends).
1851 """
1849 """
1852 from IPython.core.completer import IPCompleter
1850 from IPython.core.completer import IPCompleter
1853 from IPython.core.completerlib import (module_completer,
1851 from IPython.core.completerlib import (module_completer,
1854 magic_run_completer, cd_completer)
1852 magic_run_completer, cd_completer)
1855
1853
1856 self.Completer = IPCompleter(shell=self,
1854 self.Completer = IPCompleter(shell=self,
1857 namespace=self.user_ns,
1855 namespace=self.user_ns,
1858 global_namespace=self.user_global_ns,
1856 global_namespace=self.user_global_ns,
1859 omit__names=self.readline_omit__names,
1860 alias_table=self.alias_manager.alias_table,
1857 alias_table=self.alias_manager.alias_table,
1861 use_readline=self.has_readline,
1858 use_readline=self.has_readline,
1862 config=self.config,
1859 config=self.config,
1863 )
1860 )
1864 self.configurables.append(self.Completer)
1861 self.configurables.append(self.Completer)
1865
1862
1866 # Add custom completers to the basic ones built into IPCompleter
1863 # Add custom completers to the basic ones built into IPCompleter
1867 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1864 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1868 self.strdispatchers['complete_command'] = sdisp
1865 self.strdispatchers['complete_command'] = sdisp
1869 self.Completer.custom_completers = sdisp
1866 self.Completer.custom_completers = sdisp
1870
1867
1871 self.set_hook('complete_command', module_completer, str_key = 'import')
1868 self.set_hook('complete_command', module_completer, str_key = 'import')
1872 self.set_hook('complete_command', module_completer, str_key = 'from')
1869 self.set_hook('complete_command', module_completer, str_key = 'from')
1873 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1870 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1874 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1871 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1875
1872
1876 # Only configure readline if we truly are using readline. IPython can
1873 # Only configure readline if we truly are using readline. IPython can
1877 # do tab-completion over the network, in GUIs, etc, where readline
1874 # do tab-completion over the network, in GUIs, etc, where readline
1878 # itself may be absent
1875 # itself may be absent
1879 if self.has_readline:
1876 if self.has_readline:
1880 self.set_readline_completer()
1877 self.set_readline_completer()
1881
1878
1882 def complete(self, text, line=None, cursor_pos=None):
1879 def complete(self, text, line=None, cursor_pos=None):
1883 """Return the completed text and a list of completions.
1880 """Return the completed text and a list of completions.
1884
1881
1885 Parameters
1882 Parameters
1886 ----------
1883 ----------
1887
1884
1888 text : string
1885 text : string
1889 A string of text to be completed on. It can be given as empty and
1886 A string of text to be completed on. It can be given as empty and
1890 instead a line/position pair are given. In this case, the
1887 instead a line/position pair are given. In this case, the
1891 completer itself will split the line like readline does.
1888 completer itself will split the line like readline does.
1892
1889
1893 line : string, optional
1890 line : string, optional
1894 The complete line that text is part of.
1891 The complete line that text is part of.
1895
1892
1896 cursor_pos : int, optional
1893 cursor_pos : int, optional
1897 The position of the cursor on the input line.
1894 The position of the cursor on the input line.
1898
1895
1899 Returns
1896 Returns
1900 -------
1897 -------
1901 text : string
1898 text : string
1902 The actual text that was completed.
1899 The actual text that was completed.
1903
1900
1904 matches : list
1901 matches : list
1905 A sorted list with all possible completions.
1902 A sorted list with all possible completions.
1906
1903
1907 The optional arguments allow the completion to take more context into
1904 The optional arguments allow the completion to take more context into
1908 account, and are part of the low-level completion API.
1905 account, and are part of the low-level completion API.
1909
1906
1910 This is a wrapper around the completion mechanism, similar to what
1907 This is a wrapper around the completion mechanism, similar to what
1911 readline does at the command line when the TAB key is hit. By
1908 readline does at the command line when the TAB key is hit. By
1912 exposing it as a method, it can be used by other non-readline
1909 exposing it as a method, it can be used by other non-readline
1913 environments (such as GUIs) for text completion.
1910 environments (such as GUIs) for text completion.
1914
1911
1915 Simple usage example:
1912 Simple usage example:
1916
1913
1917 In [1]: x = 'hello'
1914 In [1]: x = 'hello'
1918
1915
1919 In [2]: _ip.complete('x.l')
1916 In [2]: _ip.complete('x.l')
1920 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1917 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1921 """
1918 """
1922
1919
1923 # Inject names into __builtin__ so we can complete on the added names.
1920 # Inject names into __builtin__ so we can complete on the added names.
1924 with self.builtin_trap:
1921 with self.builtin_trap:
1925 return self.Completer.complete(text, line, cursor_pos)
1922 return self.Completer.complete(text, line, cursor_pos)
1926
1923
1927 def set_custom_completer(self, completer, pos=0):
1924 def set_custom_completer(self, completer, pos=0):
1928 """Adds a new custom completer function.
1925 """Adds a new custom completer function.
1929
1926
1930 The position argument (defaults to 0) is the index in the completers
1927 The position argument (defaults to 0) is the index in the completers
1931 list where you want the completer to be inserted."""
1928 list where you want the completer to be inserted."""
1932
1929
1933 newcomp = types.MethodType(completer,self.Completer)
1930 newcomp = types.MethodType(completer,self.Completer)
1934 self.Completer.matchers.insert(pos,newcomp)
1931 self.Completer.matchers.insert(pos,newcomp)
1935
1932
1936 def set_readline_completer(self):
1933 def set_readline_completer(self):
1937 """Reset readline's completer to be our own."""
1934 """Reset readline's completer to be our own."""
1938 self.readline.set_completer(self.Completer.rlcomplete)
1935 self.readline.set_completer(self.Completer.rlcomplete)
1939
1936
1940 def set_completer_frame(self, frame=None):
1937 def set_completer_frame(self, frame=None):
1941 """Set the frame of the completer."""
1938 """Set the frame of the completer."""
1942 if frame:
1939 if frame:
1943 self.Completer.namespace = frame.f_locals
1940 self.Completer.namespace = frame.f_locals
1944 self.Completer.global_namespace = frame.f_globals
1941 self.Completer.global_namespace = frame.f_globals
1945 else:
1942 else:
1946 self.Completer.namespace = self.user_ns
1943 self.Completer.namespace = self.user_ns
1947 self.Completer.global_namespace = self.user_global_ns
1944 self.Completer.global_namespace = self.user_global_ns
1948
1945
1949 #-------------------------------------------------------------------------
1946 #-------------------------------------------------------------------------
1950 # Things related to magics
1947 # Things related to magics
1951 #-------------------------------------------------------------------------
1948 #-------------------------------------------------------------------------
1952
1949
1953 def init_magics(self):
1950 def init_magics(self):
1954 # FIXME: Move the color initialization to the DisplayHook, which
1951 # FIXME: Move the color initialization to the DisplayHook, which
1955 # should be split into a prompt manager and displayhook. We probably
1952 # should be split into a prompt manager and displayhook. We probably
1956 # even need a centralize colors management object.
1953 # even need a centralize colors management object.
1957 self.magic_colors(self.colors)
1954 self.magic_colors(self.colors)
1958 # History was moved to a separate module
1955 # History was moved to a separate module
1959 from . import history
1956 from . import history
1960 history.init_ipython(self)
1957 history.init_ipython(self)
1961
1958
1962 def magic(self, arg_s, next_input=None):
1959 def magic(self, arg_s, next_input=None):
1963 """Call a magic function by name.
1960 """Call a magic function by name.
1964
1961
1965 Input: a string containing the name of the magic function to call and
1962 Input: a string containing the name of the magic function to call and
1966 any additional arguments to be passed to the magic.
1963 any additional arguments to be passed to the magic.
1967
1964
1968 magic('name -opt foo bar') is equivalent to typing at the ipython
1965 magic('name -opt foo bar') is equivalent to typing at the ipython
1969 prompt:
1966 prompt:
1970
1967
1971 In[1]: %name -opt foo bar
1968 In[1]: %name -opt foo bar
1972
1969
1973 To call a magic without arguments, simply use magic('name').
1970 To call a magic without arguments, simply use magic('name').
1974
1971
1975 This provides a proper Python function to call IPython's magics in any
1972 This provides a proper Python function to call IPython's magics in any
1976 valid Python code you can type at the interpreter, including loops and
1973 valid Python code you can type at the interpreter, including loops and
1977 compound statements.
1974 compound statements.
1978 """
1975 """
1979 # Allow setting the next input - this is used if the user does `a=abs?`.
1976 # Allow setting the next input - this is used if the user does `a=abs?`.
1980 # We do this first so that magic functions can override it.
1977 # We do this first so that magic functions can override it.
1981 if next_input:
1978 if next_input:
1982 self.set_next_input(next_input)
1979 self.set_next_input(next_input)
1983
1980
1984 args = arg_s.split(' ',1)
1981 args = arg_s.split(' ',1)
1985 magic_name = args[0]
1982 magic_name = args[0]
1986 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1983 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1987
1984
1988 try:
1985 try:
1989 magic_args = args[1]
1986 magic_args = args[1]
1990 except IndexError:
1987 except IndexError:
1991 magic_args = ''
1988 magic_args = ''
1992 fn = getattr(self,'magic_'+magic_name,None)
1989 fn = getattr(self,'magic_'+magic_name,None)
1993 if fn is None:
1990 if fn is None:
1994 error("Magic function `%s` not found." % magic_name)
1991 error("Magic function `%s` not found." % magic_name)
1995 else:
1992 else:
1996 magic_args = self.var_expand(magic_args,1)
1993 magic_args = self.var_expand(magic_args,1)
1997 # Grab local namespace if we need it:
1994 # Grab local namespace if we need it:
1998 if getattr(fn, "needs_local_scope", False):
1995 if getattr(fn, "needs_local_scope", False):
1999 self._magic_locals = sys._getframe(1).f_locals
1996 self._magic_locals = sys._getframe(1).f_locals
2000 with self.builtin_trap:
1997 with self.builtin_trap:
2001 result = fn(magic_args)
1998 result = fn(magic_args)
2002 # Ensure we're not keeping object references around:
1999 # Ensure we're not keeping object references around:
2003 self._magic_locals = {}
2000 self._magic_locals = {}
2004 return result
2001 return result
2005
2002
2006 def define_magic(self, magicname, func):
2003 def define_magic(self, magicname, func):
2007 """Expose own function as magic function for ipython
2004 """Expose own function as magic function for ipython
2008
2005
2009 def foo_impl(self,parameter_s=''):
2006 def foo_impl(self,parameter_s=''):
2010 'My very own magic!. (Use docstrings, IPython reads them).'
2007 'My very own magic!. (Use docstrings, IPython reads them).'
2011 print 'Magic function. Passed parameter is between < >:'
2008 print 'Magic function. Passed parameter is between < >:'
2012 print '<%s>' % parameter_s
2009 print '<%s>' % parameter_s
2013 print 'The self object is:',self
2010 print 'The self object is:',self
2014
2011
2015 self.define_magic('foo',foo_impl)
2012 self.define_magic('foo',foo_impl)
2016 """
2013 """
2017 im = types.MethodType(func,self)
2014 im = types.MethodType(func,self)
2018 old = getattr(self, "magic_" + magicname, None)
2015 old = getattr(self, "magic_" + magicname, None)
2019 setattr(self, "magic_" + magicname, im)
2016 setattr(self, "magic_" + magicname, im)
2020 return old
2017 return old
2021
2018
2022 #-------------------------------------------------------------------------
2019 #-------------------------------------------------------------------------
2023 # Things related to macros
2020 # Things related to macros
2024 #-------------------------------------------------------------------------
2021 #-------------------------------------------------------------------------
2025
2022
2026 def define_macro(self, name, themacro):
2023 def define_macro(self, name, themacro):
2027 """Define a new macro
2024 """Define a new macro
2028
2025
2029 Parameters
2026 Parameters
2030 ----------
2027 ----------
2031 name : str
2028 name : str
2032 The name of the macro.
2029 The name of the macro.
2033 themacro : str or Macro
2030 themacro : str or Macro
2034 The action to do upon invoking the macro. If a string, a new
2031 The action to do upon invoking the macro. If a string, a new
2035 Macro object is created by passing the string to it.
2032 Macro object is created by passing the string to it.
2036 """
2033 """
2037
2034
2038 from IPython.core import macro
2035 from IPython.core import macro
2039
2036
2040 if isinstance(themacro, basestring):
2037 if isinstance(themacro, basestring):
2041 themacro = macro.Macro(themacro)
2038 themacro = macro.Macro(themacro)
2042 if not isinstance(themacro, macro.Macro):
2039 if not isinstance(themacro, macro.Macro):
2043 raise ValueError('A macro must be a string or a Macro instance.')
2040 raise ValueError('A macro must be a string or a Macro instance.')
2044 self.user_ns[name] = themacro
2041 self.user_ns[name] = themacro
2045
2042
2046 #-------------------------------------------------------------------------
2043 #-------------------------------------------------------------------------
2047 # Things related to the running of system commands
2044 # Things related to the running of system commands
2048 #-------------------------------------------------------------------------
2045 #-------------------------------------------------------------------------
2049
2046
2050 def system_piped(self, cmd):
2047 def system_piped(self, cmd):
2051 """Call the given cmd in a subprocess, piping stdout/err
2048 """Call the given cmd in a subprocess, piping stdout/err
2052
2049
2053 Parameters
2050 Parameters
2054 ----------
2051 ----------
2055 cmd : str
2052 cmd : str
2056 Command to execute (can not end in '&', as background processes are
2053 Command to execute (can not end in '&', as background processes are
2057 not supported. Should not be a command that expects input
2054 not supported. Should not be a command that expects input
2058 other than simple text.
2055 other than simple text.
2059 """
2056 """
2060 if cmd.rstrip().endswith('&'):
2057 if cmd.rstrip().endswith('&'):
2061 # this is *far* from a rigorous test
2058 # this is *far* from a rigorous test
2062 # We do not support backgrounding processes because we either use
2059 # We do not support backgrounding processes because we either use
2063 # pexpect or pipes to read from. Users can always just call
2060 # pexpect or pipes to read from. Users can always just call
2064 # os.system() or use ip.system=ip.system_raw
2061 # os.system() or use ip.system=ip.system_raw
2065 # if they really want a background process.
2062 # if they really want a background process.
2066 raise OSError("Background processes not supported.")
2063 raise OSError("Background processes not supported.")
2067
2064
2068 # we explicitly do NOT return the subprocess status code, because
2065 # we explicitly do NOT return the subprocess status code, because
2069 # a non-None value would trigger :func:`sys.displayhook` calls.
2066 # a non-None value would trigger :func:`sys.displayhook` calls.
2070 # Instead, we store the exit_code in user_ns.
2067 # Instead, we store the exit_code in user_ns.
2071 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2068 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2072
2069
2073 def system_raw(self, cmd):
2070 def system_raw(self, cmd):
2074 """Call the given cmd in a subprocess using os.system
2071 """Call the given cmd in a subprocess using os.system
2075
2072
2076 Parameters
2073 Parameters
2077 ----------
2074 ----------
2078 cmd : str
2075 cmd : str
2079 Command to execute.
2076 Command to execute.
2080 """
2077 """
2081 # We explicitly do NOT return the subprocess status code, because
2078 # We explicitly do NOT return the subprocess status code, because
2082 # a non-None value would trigger :func:`sys.displayhook` calls.
2079 # a non-None value would trigger :func:`sys.displayhook` calls.
2083 # Instead, we store the exit_code in user_ns.
2080 # Instead, we store the exit_code in user_ns.
2084 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
2081 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
2085
2082
2086 # use piped system by default, because it is better behaved
2083 # use piped system by default, because it is better behaved
2087 system = system_piped
2084 system = system_piped
2088
2085
2089 def getoutput(self, cmd, split=True):
2086 def getoutput(self, cmd, split=True):
2090 """Get output (possibly including stderr) from a subprocess.
2087 """Get output (possibly including stderr) from a subprocess.
2091
2088
2092 Parameters
2089 Parameters
2093 ----------
2090 ----------
2094 cmd : str
2091 cmd : str
2095 Command to execute (can not end in '&', as background processes are
2092 Command to execute (can not end in '&', as background processes are
2096 not supported.
2093 not supported.
2097 split : bool, optional
2094 split : bool, optional
2098
2095
2099 If True, split the output into an IPython SList. Otherwise, an
2096 If True, split the output into an IPython SList. Otherwise, an
2100 IPython LSString is returned. These are objects similar to normal
2097 IPython LSString is returned. These are objects similar to normal
2101 lists and strings, with a few convenience attributes for easier
2098 lists and strings, with a few convenience attributes for easier
2102 manipulation of line-based output. You can use '?' on them for
2099 manipulation of line-based output. You can use '?' on them for
2103 details.
2100 details.
2104 """
2101 """
2105 if cmd.rstrip().endswith('&'):
2102 if cmd.rstrip().endswith('&'):
2106 # this is *far* from a rigorous test
2103 # this is *far* from a rigorous test
2107 raise OSError("Background processes not supported.")
2104 raise OSError("Background processes not supported.")
2108 out = getoutput(self.var_expand(cmd, depth=2))
2105 out = getoutput(self.var_expand(cmd, depth=2))
2109 if split:
2106 if split:
2110 out = SList(out.splitlines())
2107 out = SList(out.splitlines())
2111 else:
2108 else:
2112 out = LSString(out)
2109 out = LSString(out)
2113 return out
2110 return out
2114
2111
2115 #-------------------------------------------------------------------------
2112 #-------------------------------------------------------------------------
2116 # Things related to aliases
2113 # Things related to aliases
2117 #-------------------------------------------------------------------------
2114 #-------------------------------------------------------------------------
2118
2115
2119 def init_alias(self):
2116 def init_alias(self):
2120 self.alias_manager = AliasManager(shell=self, config=self.config)
2117 self.alias_manager = AliasManager(shell=self, config=self.config)
2121 self.configurables.append(self.alias_manager)
2118 self.configurables.append(self.alias_manager)
2122 self.ns_table['alias'] = self.alias_manager.alias_table,
2119 self.ns_table['alias'] = self.alias_manager.alias_table,
2123
2120
2124 #-------------------------------------------------------------------------
2121 #-------------------------------------------------------------------------
2125 # Things related to extensions and plugins
2122 # Things related to extensions and plugins
2126 #-------------------------------------------------------------------------
2123 #-------------------------------------------------------------------------
2127
2124
2128 def init_extension_manager(self):
2125 def init_extension_manager(self):
2129 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2126 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2130 self.configurables.append(self.extension_manager)
2127 self.configurables.append(self.extension_manager)
2131
2128
2132 def init_plugin_manager(self):
2129 def init_plugin_manager(self):
2133 self.plugin_manager = PluginManager(config=self.config)
2130 self.plugin_manager = PluginManager(config=self.config)
2134 self.configurables.append(self.plugin_manager)
2131 self.configurables.append(self.plugin_manager)
2135
2132
2136
2133
2137 #-------------------------------------------------------------------------
2134 #-------------------------------------------------------------------------
2138 # Things related to payloads
2135 # Things related to payloads
2139 #-------------------------------------------------------------------------
2136 #-------------------------------------------------------------------------
2140
2137
2141 def init_payload(self):
2138 def init_payload(self):
2142 self.payload_manager = PayloadManager(config=self.config)
2139 self.payload_manager = PayloadManager(config=self.config)
2143 self.configurables.append(self.payload_manager)
2140 self.configurables.append(self.payload_manager)
2144
2141
2145 #-------------------------------------------------------------------------
2142 #-------------------------------------------------------------------------
2146 # Things related to the prefilter
2143 # Things related to the prefilter
2147 #-------------------------------------------------------------------------
2144 #-------------------------------------------------------------------------
2148
2145
2149 def init_prefilter(self):
2146 def init_prefilter(self):
2150 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2147 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2151 self.configurables.append(self.prefilter_manager)
2148 self.configurables.append(self.prefilter_manager)
2152 # Ultimately this will be refactored in the new interpreter code, but
2149 # Ultimately this will be refactored in the new interpreter code, but
2153 # for now, we should expose the main prefilter method (there's legacy
2150 # for now, we should expose the main prefilter method (there's legacy
2154 # code out there that may rely on this).
2151 # code out there that may rely on this).
2155 self.prefilter = self.prefilter_manager.prefilter_lines
2152 self.prefilter = self.prefilter_manager.prefilter_lines
2156
2153
2157 def auto_rewrite_input(self, cmd):
2154 def auto_rewrite_input(self, cmd):
2158 """Print to the screen the rewritten form of the user's command.
2155 """Print to the screen the rewritten form of the user's command.
2159
2156
2160 This shows visual feedback by rewriting input lines that cause
2157 This shows visual feedback by rewriting input lines that cause
2161 automatic calling to kick in, like::
2158 automatic calling to kick in, like::
2162
2159
2163 /f x
2160 /f x
2164
2161
2165 into::
2162 into::
2166
2163
2167 ------> f(x)
2164 ------> f(x)
2168
2165
2169 after the user's input prompt. This helps the user understand that the
2166 after the user's input prompt. This helps the user understand that the
2170 input line was transformed automatically by IPython.
2167 input line was transformed automatically by IPython.
2171 """
2168 """
2172 rw = self.displayhook.prompt1.auto_rewrite() + cmd
2169 rw = self.displayhook.prompt1.auto_rewrite() + cmd
2173
2170
2174 try:
2171 try:
2175 # plain ascii works better w/ pyreadline, on some machines, so
2172 # plain ascii works better w/ pyreadline, on some machines, so
2176 # we use it and only print uncolored rewrite if we have unicode
2173 # we use it and only print uncolored rewrite if we have unicode
2177 rw = str(rw)
2174 rw = str(rw)
2178 print >> io.stdout, rw
2175 print >> io.stdout, rw
2179 except UnicodeEncodeError:
2176 except UnicodeEncodeError:
2180 print "------> " + cmd
2177 print "------> " + cmd
2181
2178
2182 #-------------------------------------------------------------------------
2179 #-------------------------------------------------------------------------
2183 # Things related to extracting values/expressions from kernel and user_ns
2180 # Things related to extracting values/expressions from kernel and user_ns
2184 #-------------------------------------------------------------------------
2181 #-------------------------------------------------------------------------
2185
2182
2186 def _simple_error(self):
2183 def _simple_error(self):
2187 etype, value = sys.exc_info()[:2]
2184 etype, value = sys.exc_info()[:2]
2188 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2185 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2189
2186
2190 def user_variables(self, names):
2187 def user_variables(self, names):
2191 """Get a list of variable names from the user's namespace.
2188 """Get a list of variable names from the user's namespace.
2192
2189
2193 Parameters
2190 Parameters
2194 ----------
2191 ----------
2195 names : list of strings
2192 names : list of strings
2196 A list of names of variables to be read from the user namespace.
2193 A list of names of variables to be read from the user namespace.
2197
2194
2198 Returns
2195 Returns
2199 -------
2196 -------
2200 A dict, keyed by the input names and with the repr() of each value.
2197 A dict, keyed by the input names and with the repr() of each value.
2201 """
2198 """
2202 out = {}
2199 out = {}
2203 user_ns = self.user_ns
2200 user_ns = self.user_ns
2204 for varname in names:
2201 for varname in names:
2205 try:
2202 try:
2206 value = repr(user_ns[varname])
2203 value = repr(user_ns[varname])
2207 except:
2204 except:
2208 value = self._simple_error()
2205 value = self._simple_error()
2209 out[varname] = value
2206 out[varname] = value
2210 return out
2207 return out
2211
2208
2212 def user_expressions(self, expressions):
2209 def user_expressions(self, expressions):
2213 """Evaluate a dict of expressions in the user's namespace.
2210 """Evaluate a dict of expressions in the user's namespace.
2214
2211
2215 Parameters
2212 Parameters
2216 ----------
2213 ----------
2217 expressions : dict
2214 expressions : dict
2218 A dict with string keys and string values. The expression values
2215 A dict with string keys and string values. The expression values
2219 should be valid Python expressions, each of which will be evaluated
2216 should be valid Python expressions, each of which will be evaluated
2220 in the user namespace.
2217 in the user namespace.
2221
2218
2222 Returns
2219 Returns
2223 -------
2220 -------
2224 A dict, keyed like the input expressions dict, with the repr() of each
2221 A dict, keyed like the input expressions dict, with the repr() of each
2225 value.
2222 value.
2226 """
2223 """
2227 out = {}
2224 out = {}
2228 user_ns = self.user_ns
2225 user_ns = self.user_ns
2229 global_ns = self.user_global_ns
2226 global_ns = self.user_global_ns
2230 for key, expr in expressions.iteritems():
2227 for key, expr in expressions.iteritems():
2231 try:
2228 try:
2232 value = repr(eval(expr, global_ns, user_ns))
2229 value = repr(eval(expr, global_ns, user_ns))
2233 except:
2230 except:
2234 value = self._simple_error()
2231 value = self._simple_error()
2235 out[key] = value
2232 out[key] = value
2236 return out
2233 return out
2237
2234
2238 #-------------------------------------------------------------------------
2235 #-------------------------------------------------------------------------
2239 # Things related to the running of code
2236 # Things related to the running of code
2240 #-------------------------------------------------------------------------
2237 #-------------------------------------------------------------------------
2241
2238
2242 def ex(self, cmd):
2239 def ex(self, cmd):
2243 """Execute a normal python statement in user namespace."""
2240 """Execute a normal python statement in user namespace."""
2244 with self.builtin_trap:
2241 with self.builtin_trap:
2245 exec cmd in self.user_global_ns, self.user_ns
2242 exec cmd in self.user_global_ns, self.user_ns
2246
2243
2247 def ev(self, expr):
2244 def ev(self, expr):
2248 """Evaluate python expression expr in user namespace.
2245 """Evaluate python expression expr in user namespace.
2249
2246
2250 Returns the result of evaluation
2247 Returns the result of evaluation
2251 """
2248 """
2252 with self.builtin_trap:
2249 with self.builtin_trap:
2253 return eval(expr, self.user_global_ns, self.user_ns)
2250 return eval(expr, self.user_global_ns, self.user_ns)
2254
2251
2255 def safe_execfile(self, fname, *where, **kw):
2252 def safe_execfile(self, fname, *where, **kw):
2256 """A safe version of the builtin execfile().
2253 """A safe version of the builtin execfile().
2257
2254
2258 This version will never throw an exception, but instead print
2255 This version will never throw an exception, but instead print
2259 helpful error messages to the screen. This only works on pure
2256 helpful error messages to the screen. This only works on pure
2260 Python files with the .py extension.
2257 Python files with the .py extension.
2261
2258
2262 Parameters
2259 Parameters
2263 ----------
2260 ----------
2264 fname : string
2261 fname : string
2265 The name of the file to be executed.
2262 The name of the file to be executed.
2266 where : tuple
2263 where : tuple
2267 One or two namespaces, passed to execfile() as (globals,locals).
2264 One or two namespaces, passed to execfile() as (globals,locals).
2268 If only one is given, it is passed as both.
2265 If only one is given, it is passed as both.
2269 exit_ignore : bool (False)
2266 exit_ignore : bool (False)
2270 If True, then silence SystemExit for non-zero status (it is always
2267 If True, then silence SystemExit for non-zero status (it is always
2271 silenced for zero status, as it is so common).
2268 silenced for zero status, as it is so common).
2272 raise_exceptions : bool (False)
2269 raise_exceptions : bool (False)
2273 If True raise exceptions everywhere. Meant for testing.
2270 If True raise exceptions everywhere. Meant for testing.
2274
2271
2275 """
2272 """
2276 kw.setdefault('exit_ignore', False)
2273 kw.setdefault('exit_ignore', False)
2277 kw.setdefault('raise_exceptions', False)
2274 kw.setdefault('raise_exceptions', False)
2278
2275
2279 fname = os.path.abspath(os.path.expanduser(fname))
2276 fname = os.path.abspath(os.path.expanduser(fname))
2280
2277
2281 # Make sure we can open the file
2278 # Make sure we can open the file
2282 try:
2279 try:
2283 with open(fname) as thefile:
2280 with open(fname) as thefile:
2284 pass
2281 pass
2285 except:
2282 except:
2286 warn('Could not open file <%s> for safe execution.' % fname)
2283 warn('Could not open file <%s> for safe execution.' % fname)
2287 return
2284 return
2288
2285
2289 # Find things also in current directory. This is needed to mimic the
2286 # Find things also in current directory. This is needed to mimic the
2290 # behavior of running a script from the system command line, where
2287 # behavior of running a script from the system command line, where
2291 # Python inserts the script's directory into sys.path
2288 # Python inserts the script's directory into sys.path
2292 dname = os.path.dirname(fname)
2289 dname = os.path.dirname(fname)
2293
2290
2294 with prepended_to_syspath(dname):
2291 with prepended_to_syspath(dname):
2295 try:
2292 try:
2296 py3compat.execfile(fname,*where)
2293 py3compat.execfile(fname,*where)
2297 except SystemExit, status:
2294 except SystemExit, status:
2298 # If the call was made with 0 or None exit status (sys.exit(0)
2295 # If the call was made with 0 or None exit status (sys.exit(0)
2299 # or sys.exit() ), don't bother showing a traceback, as both of
2296 # or sys.exit() ), don't bother showing a traceback, as both of
2300 # these are considered normal by the OS:
2297 # these are considered normal by the OS:
2301 # > python -c'import sys;sys.exit(0)'; echo $?
2298 # > python -c'import sys;sys.exit(0)'; echo $?
2302 # 0
2299 # 0
2303 # > python -c'import sys;sys.exit()'; echo $?
2300 # > python -c'import sys;sys.exit()'; echo $?
2304 # 0
2301 # 0
2305 # For other exit status, we show the exception unless
2302 # For other exit status, we show the exception unless
2306 # explicitly silenced, but only in short form.
2303 # explicitly silenced, but only in short form.
2307 if kw['raise_exceptions']:
2304 if kw['raise_exceptions']:
2308 raise
2305 raise
2309 if status.code not in (0, None) and not kw['exit_ignore']:
2306 if status.code not in (0, None) and not kw['exit_ignore']:
2310 self.showtraceback(exception_only=True)
2307 self.showtraceback(exception_only=True)
2311 except:
2308 except:
2312 if kw['raise_exceptions']:
2309 if kw['raise_exceptions']:
2313 raise
2310 raise
2314 self.showtraceback()
2311 self.showtraceback()
2315
2312
2316 def safe_execfile_ipy(self, fname):
2313 def safe_execfile_ipy(self, fname):
2317 """Like safe_execfile, but for .ipy files with IPython syntax.
2314 """Like safe_execfile, but for .ipy files with IPython syntax.
2318
2315
2319 Parameters
2316 Parameters
2320 ----------
2317 ----------
2321 fname : str
2318 fname : str
2322 The name of the file to execute. The filename must have a
2319 The name of the file to execute. The filename must have a
2323 .ipy extension.
2320 .ipy extension.
2324 """
2321 """
2325 fname = os.path.abspath(os.path.expanduser(fname))
2322 fname = os.path.abspath(os.path.expanduser(fname))
2326
2323
2327 # Make sure we can open the file
2324 # Make sure we can open the file
2328 try:
2325 try:
2329 with open(fname) as thefile:
2326 with open(fname) as thefile:
2330 pass
2327 pass
2331 except:
2328 except:
2332 warn('Could not open file <%s> for safe execution.' % fname)
2329 warn('Could not open file <%s> for safe execution.' % fname)
2333 return
2330 return
2334
2331
2335 # Find things also in current directory. This is needed to mimic the
2332 # Find things also in current directory. This is needed to mimic the
2336 # behavior of running a script from the system command line, where
2333 # behavior of running a script from the system command line, where
2337 # Python inserts the script's directory into sys.path
2334 # Python inserts the script's directory into sys.path
2338 dname = os.path.dirname(fname)
2335 dname = os.path.dirname(fname)
2339
2336
2340 with prepended_to_syspath(dname):
2337 with prepended_to_syspath(dname):
2341 try:
2338 try:
2342 with open(fname) as thefile:
2339 with open(fname) as thefile:
2343 # self.run_cell currently captures all exceptions
2340 # self.run_cell currently captures all exceptions
2344 # raised in user code. It would be nice if there were
2341 # raised in user code. It would be nice if there were
2345 # versions of runlines, execfile that did raise, so
2342 # versions of runlines, execfile that did raise, so
2346 # we could catch the errors.
2343 # we could catch the errors.
2347 self.run_cell(thefile.read(), store_history=False)
2344 self.run_cell(thefile.read(), store_history=False)
2348 except:
2345 except:
2349 self.showtraceback()
2346 self.showtraceback()
2350 warn('Unknown failure executing file: <%s>' % fname)
2347 warn('Unknown failure executing file: <%s>' % fname)
2351
2348
2352 def run_cell(self, raw_cell, store_history=False):
2349 def run_cell(self, raw_cell, store_history=False):
2353 """Run a complete IPython cell.
2350 """Run a complete IPython cell.
2354
2351
2355 Parameters
2352 Parameters
2356 ----------
2353 ----------
2357 raw_cell : str
2354 raw_cell : str
2358 The code (including IPython code such as %magic functions) to run.
2355 The code (including IPython code such as %magic functions) to run.
2359 store_history : bool
2356 store_history : bool
2360 If True, the raw and translated cell will be stored in IPython's
2357 If True, the raw and translated cell will be stored in IPython's
2361 history. For user code calling back into IPython's machinery, this
2358 history. For user code calling back into IPython's machinery, this
2362 should be set to False.
2359 should be set to False.
2363 """
2360 """
2364 if (not raw_cell) or raw_cell.isspace():
2361 if (not raw_cell) or raw_cell.isspace():
2365 return
2362 return
2366
2363
2367 for line in raw_cell.splitlines():
2364 for line in raw_cell.splitlines():
2368 self.input_splitter.push(line)
2365 self.input_splitter.push(line)
2369 cell = self.input_splitter.source_reset()
2366 cell = self.input_splitter.source_reset()
2370
2367
2371 with self.builtin_trap:
2368 with self.builtin_trap:
2372 prefilter_failed = False
2369 prefilter_failed = False
2373 if len(cell.splitlines()) == 1:
2370 if len(cell.splitlines()) == 1:
2374 try:
2371 try:
2375 # use prefilter_lines to handle trailing newlines
2372 # use prefilter_lines to handle trailing newlines
2376 # restore trailing newline for ast.parse
2373 # restore trailing newline for ast.parse
2377 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2374 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2378 except AliasError as e:
2375 except AliasError as e:
2379 error(e)
2376 error(e)
2380 prefilter_failed = True
2377 prefilter_failed = True
2381 except Exception:
2378 except Exception:
2382 # don't allow prefilter errors to crash IPython
2379 # don't allow prefilter errors to crash IPython
2383 self.showtraceback()
2380 self.showtraceback()
2384 prefilter_failed = True
2381 prefilter_failed = True
2385
2382
2386 # Store raw and processed history
2383 # Store raw and processed history
2387 if store_history:
2384 if store_history:
2388 self.history_manager.store_inputs(self.execution_count,
2385 self.history_manager.store_inputs(self.execution_count,
2389 cell, raw_cell)
2386 cell, raw_cell)
2390
2387
2391 self.logger.log(cell, raw_cell)
2388 self.logger.log(cell, raw_cell)
2392
2389
2393 if not prefilter_failed:
2390 if not prefilter_failed:
2394 # don't run if prefilter failed
2391 # don't run if prefilter failed
2395 cell_name = self.compile.cache(cell, self.execution_count)
2392 cell_name = self.compile.cache(cell, self.execution_count)
2396
2393
2397 with self.display_trap:
2394 with self.display_trap:
2398 try:
2395 try:
2399 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2396 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2400 except IndentationError:
2397 except IndentationError:
2401 self.showindentationerror()
2398 self.showindentationerror()
2402 self.execution_count += 1
2399 self.execution_count += 1
2403 return None
2400 return None
2404 except (OverflowError, SyntaxError, ValueError, TypeError,
2401 except (OverflowError, SyntaxError, ValueError, TypeError,
2405 MemoryError):
2402 MemoryError):
2406 self.showsyntaxerror()
2403 self.showsyntaxerror()
2407 self.execution_count += 1
2404 self.execution_count += 1
2408 return None
2405 return None
2409
2406
2410 self.run_ast_nodes(code_ast.body, cell_name,
2407 self.run_ast_nodes(code_ast.body, cell_name,
2411 interactivity="last_expr")
2408 interactivity="last_expr")
2412
2409
2413 # Execute any registered post-execution functions.
2410 # Execute any registered post-execution functions.
2414 for func, status in self._post_execute.iteritems():
2411 for func, status in self._post_execute.iteritems():
2415 if not status:
2412 if not status:
2416 continue
2413 continue
2417 try:
2414 try:
2418 func()
2415 func()
2419 except:
2416 except:
2420 self.showtraceback()
2417 self.showtraceback()
2421 # Deactivate failing function
2418 # Deactivate failing function
2422 self._post_execute[func] = False
2419 self._post_execute[func] = False
2423
2420
2424 if store_history:
2421 if store_history:
2425 # Write output to the database. Does nothing unless
2422 # Write output to the database. Does nothing unless
2426 # history output logging is enabled.
2423 # history output logging is enabled.
2427 self.history_manager.store_output(self.execution_count)
2424 self.history_manager.store_output(self.execution_count)
2428 # Each cell is a *single* input, regardless of how many lines it has
2425 # Each cell is a *single* input, regardless of how many lines it has
2429 self.execution_count += 1
2426 self.execution_count += 1
2430
2427
2431 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2428 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2432 """Run a sequence of AST nodes. The execution mode depends on the
2429 """Run a sequence of AST nodes. The execution mode depends on the
2433 interactivity parameter.
2430 interactivity parameter.
2434
2431
2435 Parameters
2432 Parameters
2436 ----------
2433 ----------
2437 nodelist : list
2434 nodelist : list
2438 A sequence of AST nodes to run.
2435 A sequence of AST nodes to run.
2439 cell_name : str
2436 cell_name : str
2440 Will be passed to the compiler as the filename of the cell. Typically
2437 Will be passed to the compiler as the filename of the cell. Typically
2441 the value returned by ip.compile.cache(cell).
2438 the value returned by ip.compile.cache(cell).
2442 interactivity : str
2439 interactivity : str
2443 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2440 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2444 run interactively (displaying output from expressions). 'last_expr'
2441 run interactively (displaying output from expressions). 'last_expr'
2445 will run the last node interactively only if it is an expression (i.e.
2442 will run the last node interactively only if it is an expression (i.e.
2446 expressions in loops or other blocks are not displayed. Other values
2443 expressions in loops or other blocks are not displayed. Other values
2447 for this parameter will raise a ValueError.
2444 for this parameter will raise a ValueError.
2448 """
2445 """
2449 if not nodelist:
2446 if not nodelist:
2450 return
2447 return
2451
2448
2452 if interactivity == 'last_expr':
2449 if interactivity == 'last_expr':
2453 if isinstance(nodelist[-1], ast.Expr):
2450 if isinstance(nodelist[-1], ast.Expr):
2454 interactivity = "last"
2451 interactivity = "last"
2455 else:
2452 else:
2456 interactivity = "none"
2453 interactivity = "none"
2457
2454
2458 if interactivity == 'none':
2455 if interactivity == 'none':
2459 to_run_exec, to_run_interactive = nodelist, []
2456 to_run_exec, to_run_interactive = nodelist, []
2460 elif interactivity == 'last':
2457 elif interactivity == 'last':
2461 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2458 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2462 elif interactivity == 'all':
2459 elif interactivity == 'all':
2463 to_run_exec, to_run_interactive = [], nodelist
2460 to_run_exec, to_run_interactive = [], nodelist
2464 else:
2461 else:
2465 raise ValueError("Interactivity was %r" % interactivity)
2462 raise ValueError("Interactivity was %r" % interactivity)
2466
2463
2467 exec_count = self.execution_count
2464 exec_count = self.execution_count
2468
2465
2469 try:
2466 try:
2470 for i, node in enumerate(to_run_exec):
2467 for i, node in enumerate(to_run_exec):
2471 mod = ast.Module([node])
2468 mod = ast.Module([node])
2472 code = self.compile(mod, cell_name, "exec")
2469 code = self.compile(mod, cell_name, "exec")
2473 if self.run_code(code):
2470 if self.run_code(code):
2474 return True
2471 return True
2475
2472
2476 for i, node in enumerate(to_run_interactive):
2473 for i, node in enumerate(to_run_interactive):
2477 mod = ast.Interactive([node])
2474 mod = ast.Interactive([node])
2478 code = self.compile(mod, cell_name, "single")
2475 code = self.compile(mod, cell_name, "single")
2479 if self.run_code(code):
2476 if self.run_code(code):
2480 return True
2477 return True
2481 except:
2478 except:
2482 # It's possible to have exceptions raised here, typically by
2479 # It's possible to have exceptions raised here, typically by
2483 # compilation of odd code (such as a naked 'return' outside a
2480 # compilation of odd code (such as a naked 'return' outside a
2484 # function) that did parse but isn't valid. Typically the exception
2481 # function) that did parse but isn't valid. Typically the exception
2485 # is a SyntaxError, but it's safest just to catch anything and show
2482 # is a SyntaxError, but it's safest just to catch anything and show
2486 # the user a traceback.
2483 # the user a traceback.
2487
2484
2488 # We do only one try/except outside the loop to minimize the impact
2485 # We do only one try/except outside the loop to minimize the impact
2489 # on runtime, and also because if any node in the node list is
2486 # on runtime, and also because if any node in the node list is
2490 # broken, we should stop execution completely.
2487 # broken, we should stop execution completely.
2491 self.showtraceback()
2488 self.showtraceback()
2492
2489
2493 return False
2490 return False
2494
2491
2495 def run_code(self, code_obj):
2492 def run_code(self, code_obj):
2496 """Execute a code object.
2493 """Execute a code object.
2497
2494
2498 When an exception occurs, self.showtraceback() is called to display a
2495 When an exception occurs, self.showtraceback() is called to display a
2499 traceback.
2496 traceback.
2500
2497
2501 Parameters
2498 Parameters
2502 ----------
2499 ----------
2503 code_obj : code object
2500 code_obj : code object
2504 A compiled code object, to be executed
2501 A compiled code object, to be executed
2505 post_execute : bool [default: True]
2502 post_execute : bool [default: True]
2506 whether to call post_execute hooks after this particular execution.
2503 whether to call post_execute hooks after this particular execution.
2507
2504
2508 Returns
2505 Returns
2509 -------
2506 -------
2510 False : successful execution.
2507 False : successful execution.
2511 True : an error occurred.
2508 True : an error occurred.
2512 """
2509 """
2513
2510
2514 # Set our own excepthook in case the user code tries to call it
2511 # Set our own excepthook in case the user code tries to call it
2515 # directly, so that the IPython crash handler doesn't get triggered
2512 # directly, so that the IPython crash handler doesn't get triggered
2516 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2513 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2517
2514
2518 # we save the original sys.excepthook in the instance, in case config
2515 # we save the original sys.excepthook in the instance, in case config
2519 # code (such as magics) needs access to it.
2516 # code (such as magics) needs access to it.
2520 self.sys_excepthook = old_excepthook
2517 self.sys_excepthook = old_excepthook
2521 outflag = 1 # happens in more places, so it's easier as default
2518 outflag = 1 # happens in more places, so it's easier as default
2522 try:
2519 try:
2523 try:
2520 try:
2524 self.hooks.pre_run_code_hook()
2521 self.hooks.pre_run_code_hook()
2525 #rprint('Running code', repr(code_obj)) # dbg
2522 #rprint('Running code', repr(code_obj)) # dbg
2526 exec code_obj in self.user_global_ns, self.user_ns
2523 exec code_obj in self.user_global_ns, self.user_ns
2527 finally:
2524 finally:
2528 # Reset our crash handler in place
2525 # Reset our crash handler in place
2529 sys.excepthook = old_excepthook
2526 sys.excepthook = old_excepthook
2530 except SystemExit:
2527 except SystemExit:
2531 self.showtraceback(exception_only=True)
2528 self.showtraceback(exception_only=True)
2532 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2529 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2533 except self.custom_exceptions:
2530 except self.custom_exceptions:
2534 etype,value,tb = sys.exc_info()
2531 etype,value,tb = sys.exc_info()
2535 self.CustomTB(etype,value,tb)
2532 self.CustomTB(etype,value,tb)
2536 except:
2533 except:
2537 self.showtraceback()
2534 self.showtraceback()
2538 else:
2535 else:
2539 outflag = 0
2536 outflag = 0
2540 if softspace(sys.stdout, 0):
2537 if softspace(sys.stdout, 0):
2541 print
2538 print
2542
2539
2543 return outflag
2540 return outflag
2544
2541
2545 # For backwards compatibility
2542 # For backwards compatibility
2546 runcode = run_code
2543 runcode = run_code
2547
2544
2548 #-------------------------------------------------------------------------
2545 #-------------------------------------------------------------------------
2549 # Things related to GUI support and pylab
2546 # Things related to GUI support and pylab
2550 #-------------------------------------------------------------------------
2547 #-------------------------------------------------------------------------
2551
2548
2552 def enable_pylab(self, gui=None, import_all=True):
2549 def enable_pylab(self, gui=None, import_all=True):
2553 raise NotImplementedError('Implement enable_pylab in a subclass')
2550 raise NotImplementedError('Implement enable_pylab in a subclass')
2554
2551
2555 #-------------------------------------------------------------------------
2552 #-------------------------------------------------------------------------
2556 # Utilities
2553 # Utilities
2557 #-------------------------------------------------------------------------
2554 #-------------------------------------------------------------------------
2558
2555
2559 def var_expand(self,cmd,depth=0):
2556 def var_expand(self,cmd,depth=0):
2560 """Expand python variables in a string.
2557 """Expand python variables in a string.
2561
2558
2562 The depth argument indicates how many frames above the caller should
2559 The depth argument indicates how many frames above the caller should
2563 be walked to look for the local namespace where to expand variables.
2560 be walked to look for the local namespace where to expand variables.
2564
2561
2565 The global namespace for expansion is always the user's interactive
2562 The global namespace for expansion is always the user's interactive
2566 namespace.
2563 namespace.
2567 """
2564 """
2568 res = ItplNS(cmd, self.user_ns, # globals
2565 res = ItplNS(cmd, self.user_ns, # globals
2569 # Skip our own frame in searching for locals:
2566 # Skip our own frame in searching for locals:
2570 sys._getframe(depth+1).f_locals # locals
2567 sys._getframe(depth+1).f_locals # locals
2571 )
2568 )
2572 return py3compat.str_to_unicode(str(res), res.codec)
2569 return py3compat.str_to_unicode(str(res), res.codec)
2573
2570
2574 def mktempfile(self, data=None, prefix='ipython_edit_'):
2571 def mktempfile(self, data=None, prefix='ipython_edit_'):
2575 """Make a new tempfile and return its filename.
2572 """Make a new tempfile and return its filename.
2576
2573
2577 This makes a call to tempfile.mktemp, but it registers the created
2574 This makes a call to tempfile.mktemp, but it registers the created
2578 filename internally so ipython cleans it up at exit time.
2575 filename internally so ipython cleans it up at exit time.
2579
2576
2580 Optional inputs:
2577 Optional inputs:
2581
2578
2582 - data(None): if data is given, it gets written out to the temp file
2579 - data(None): if data is given, it gets written out to the temp file
2583 immediately, and the file is closed again."""
2580 immediately, and the file is closed again."""
2584
2581
2585 filename = tempfile.mktemp('.py', prefix)
2582 filename = tempfile.mktemp('.py', prefix)
2586 self.tempfiles.append(filename)
2583 self.tempfiles.append(filename)
2587
2584
2588 if data:
2585 if data:
2589 tmp_file = open(filename,'w')
2586 tmp_file = open(filename,'w')
2590 tmp_file.write(data)
2587 tmp_file.write(data)
2591 tmp_file.close()
2588 tmp_file.close()
2592 return filename
2589 return filename
2593
2590
2594 # TODO: This should be removed when Term is refactored.
2591 # TODO: This should be removed when Term is refactored.
2595 def write(self,data):
2592 def write(self,data):
2596 """Write a string to the default output"""
2593 """Write a string to the default output"""
2597 io.stdout.write(data)
2594 io.stdout.write(data)
2598
2595
2599 # TODO: This should be removed when Term is refactored.
2596 # TODO: This should be removed when Term is refactored.
2600 def write_err(self,data):
2597 def write_err(self,data):
2601 """Write a string to the default error output"""
2598 """Write a string to the default error output"""
2602 io.stderr.write(data)
2599 io.stderr.write(data)
2603
2600
2604 def ask_yes_no(self,prompt,default=True):
2601 def ask_yes_no(self,prompt,default=True):
2605 if self.quiet:
2602 if self.quiet:
2606 return True
2603 return True
2607 return ask_yes_no(prompt,default)
2604 return ask_yes_no(prompt,default)
2608
2605
2609 def show_usage(self):
2606 def show_usage(self):
2610 """Show a usage message"""
2607 """Show a usage message"""
2611 page.page(IPython.core.usage.interactive_usage)
2608 page.page(IPython.core.usage.interactive_usage)
2612
2609
2613 def find_user_code(self, target, raw=True):
2610 def find_user_code(self, target, raw=True):
2614 """Get a code string from history, file, or a string or macro.
2611 """Get a code string from history, file, or a string or macro.
2615
2612
2616 This is mainly used by magic functions.
2613 This is mainly used by magic functions.
2617
2614
2618 Parameters
2615 Parameters
2619 ----------
2616 ----------
2620 target : str
2617 target : str
2621 A string specifying code to retrieve. This will be tried respectively
2618 A string specifying code to retrieve. This will be tried respectively
2622 as: ranges of input history (see %history for syntax), a filename, or
2619 as: ranges of input history (see %history for syntax), a filename, or
2623 an expression evaluating to a string or Macro in the user namespace.
2620 an expression evaluating to a string or Macro in the user namespace.
2624 raw : bool
2621 raw : bool
2625 If true (default), retrieve raw history. Has no effect on the other
2622 If true (default), retrieve raw history. Has no effect on the other
2626 retrieval mechanisms.
2623 retrieval mechanisms.
2627
2624
2628 Returns
2625 Returns
2629 -------
2626 -------
2630 A string of code.
2627 A string of code.
2631
2628
2632 ValueError is raised if nothing is found, and TypeError if it evaluates
2629 ValueError is raised if nothing is found, and TypeError if it evaluates
2633 to an object of another type. In each case, .args[0] is a printable
2630 to an object of another type. In each case, .args[0] is a printable
2634 message.
2631 message.
2635 """
2632 """
2636 code = self.extract_input_lines(target, raw=raw) # Grab history
2633 code = self.extract_input_lines(target, raw=raw) # Grab history
2637 if code:
2634 if code:
2638 return code
2635 return code
2639 if os.path.isfile(target): # Read file
2636 if os.path.isfile(target): # Read file
2640 return open(target, "r").read()
2637 return open(target, "r").read()
2641
2638
2642 try: # User namespace
2639 try: # User namespace
2643 codeobj = eval(target, self.user_ns)
2640 codeobj = eval(target, self.user_ns)
2644 except Exception:
2641 except Exception:
2645 raise ValueError(("'%s' was not found in history, as a file, nor in"
2642 raise ValueError(("'%s' was not found in history, as a file, nor in"
2646 " the user namespace.") % target)
2643 " the user namespace.") % target)
2647 if isinstance(codeobj, basestring):
2644 if isinstance(codeobj, basestring):
2648 return codeobj
2645 return codeobj
2649 elif isinstance(codeobj, Macro):
2646 elif isinstance(codeobj, Macro):
2650 return codeobj.value
2647 return codeobj.value
2651
2648
2652 raise TypeError("%s is neither a string nor a macro." % target,
2649 raise TypeError("%s is neither a string nor a macro." % target,
2653 codeobj)
2650 codeobj)
2654
2651
2655 #-------------------------------------------------------------------------
2652 #-------------------------------------------------------------------------
2656 # Things related to IPython exiting
2653 # Things related to IPython exiting
2657 #-------------------------------------------------------------------------
2654 #-------------------------------------------------------------------------
2658 def atexit_operations(self):
2655 def atexit_operations(self):
2659 """This will be executed at the time of exit.
2656 """This will be executed at the time of exit.
2660
2657
2661 Cleanup operations and saving of persistent data that is done
2658 Cleanup operations and saving of persistent data that is done
2662 unconditionally by IPython should be performed here.
2659 unconditionally by IPython should be performed here.
2663
2660
2664 For things that may depend on startup flags or platform specifics (such
2661 For things that may depend on startup flags or platform specifics (such
2665 as having readline or not), register a separate atexit function in the
2662 as having readline or not), register a separate atexit function in the
2666 code that has the appropriate information, rather than trying to
2663 code that has the appropriate information, rather than trying to
2667 clutter
2664 clutter
2668 """
2665 """
2669 # Close the history session (this stores the end time and line count)
2666 # Close the history session (this stores the end time and line count)
2670 # this must be *before* the tempfile cleanup, in case of temporary
2667 # this must be *before* the tempfile cleanup, in case of temporary
2671 # history db
2668 # history db
2672 self.history_manager.end_session()
2669 self.history_manager.end_session()
2673
2670
2674 # Cleanup all tempfiles left around
2671 # Cleanup all tempfiles left around
2675 for tfile in self.tempfiles:
2672 for tfile in self.tempfiles:
2676 try:
2673 try:
2677 os.unlink(tfile)
2674 os.unlink(tfile)
2678 except OSError:
2675 except OSError:
2679 pass
2676 pass
2680
2677
2681 # Clear all user namespaces to release all references cleanly.
2678 # Clear all user namespaces to release all references cleanly.
2682 self.reset(new_session=False)
2679 self.reset(new_session=False)
2683
2680
2684 # Run user hooks
2681 # Run user hooks
2685 self.hooks.shutdown_hook()
2682 self.hooks.shutdown_hook()
2686
2683
2687 def cleanup(self):
2684 def cleanup(self):
2688 self.restore_sys_module_state()
2685 self.restore_sys_module_state()
2689
2686
2690
2687
2691 class InteractiveShellABC(object):
2688 class InteractiveShellABC(object):
2692 """An abstract base class for InteractiveShell."""
2689 """An abstract base class for InteractiveShell."""
2693 __metaclass__ = abc.ABCMeta
2690 __metaclass__ = abc.ABCMeta
2694
2691
2695 InteractiveShellABC.register(InteractiveShell)
2692 InteractiveShellABC.register(InteractiveShell)
@@ -1,3713 +1,3726 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__ as builtin_mod
18 import __builtin__ as builtin_mod
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import imp
22 import imp
23 import os
23 import os
24 import sys
24 import sys
25 import shutil
25 import shutil
26 import re
26 import re
27 import time
27 import time
28 import textwrap
28 import textwrap
29 from StringIO import StringIO
29 from StringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pformat
31 from pprint import pformat
32 from xmlrpclib import ServerProxy
32 from xmlrpclib import ServerProxy
33
33
34 # cProfile was added in Python2.5
34 # cProfile was added in Python2.5
35 try:
35 try:
36 import cProfile as profile
36 import cProfile as profile
37 import pstats
37 import pstats
38 except ImportError:
38 except ImportError:
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 import IPython
45 import IPython
46 from IPython.core import debugger, oinspect
46 from IPython.core import debugger, oinspect
47 from IPython.core.error import TryNext
47 from IPython.core.error import TryNext
48 from IPython.core.error import UsageError
48 from IPython.core.error import UsageError
49 from IPython.core.fakemodule import FakeModule
49 from IPython.core.fakemodule import FakeModule
50 from IPython.core.profiledir import ProfileDir
50 from IPython.core.profiledir import ProfileDir
51 from IPython.core.macro import Macro
51 from IPython.core.macro import Macro
52 from IPython.core import magic_arguments, page
52 from IPython.core import magic_arguments, page
53 from IPython.core.prefilter import ESC_MAGIC
53 from IPython.core.prefilter import ESC_MAGIC
54 from IPython.lib.pylabtools import mpl_runner
54 from IPython.lib.pylabtools import mpl_runner
55 from IPython.testing.skipdoctest import skip_doctest
55 from IPython.testing.skipdoctest import skip_doctest
56 from IPython.utils import py3compat
56 from IPython.utils import py3compat
57 from IPython.utils.io import file_read, nlprint
57 from IPython.utils.io import file_read, nlprint
58 from IPython.utils.module_paths import find_mod
58 from IPython.utils.module_paths import find_mod
59 from IPython.utils.path import get_py_filename, unquote_filename
59 from IPython.utils.path import get_py_filename, unquote_filename
60 from IPython.utils.process import arg_split, abbrev_cwd
60 from IPython.utils.process import arg_split, abbrev_cwd
61 from IPython.utils.terminal import set_term_title
61 from IPython.utils.terminal import set_term_title
62 from IPython.utils.text import LSString, SList, format_screen
62 from IPython.utils.text import LSString, SList, format_screen
63 from IPython.utils.timing import clock, clock2
63 from IPython.utils.timing import clock, clock2
64 from IPython.utils.warn import warn, error
64 from IPython.utils.warn import warn, error
65 from IPython.utils.ipstruct import Struct
65 from IPython.utils.ipstruct import Struct
66 from IPython.config.application import Application
66 from IPython.config.application import Application
67
67
68 #-----------------------------------------------------------------------------
68 #-----------------------------------------------------------------------------
69 # Utility functions
69 # Utility functions
70 #-----------------------------------------------------------------------------
70 #-----------------------------------------------------------------------------
71
71
72 def on_off(tag):
72 def on_off(tag):
73 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
73 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
74 return ['OFF','ON'][tag]
74 return ['OFF','ON'][tag]
75
75
76 class Bunch: pass
76 class Bunch: pass
77
77
78 def compress_dhist(dh):
78 def compress_dhist(dh):
79 head, tail = dh[:-10], dh[-10:]
79 head, tail = dh[:-10], dh[-10:]
80
80
81 newhead = []
81 newhead = []
82 done = set()
82 done = set()
83 for h in head:
83 for h in head:
84 if h in done:
84 if h in done:
85 continue
85 continue
86 newhead.append(h)
86 newhead.append(h)
87 done.add(h)
87 done.add(h)
88
88
89 return newhead + tail
89 return newhead + tail
90
90
91 def needs_local_scope(func):
91 def needs_local_scope(func):
92 """Decorator to mark magic functions which need to local scope to run."""
92 """Decorator to mark magic functions which need to local scope to run."""
93 func.needs_local_scope = True
93 func.needs_local_scope = True
94 return func
94 return func
95
95
96
96
97 # Used for exception handling in magic_edit
97 # Used for exception handling in magic_edit
98 class MacroToEdit(ValueError): pass
98 class MacroToEdit(ValueError): pass
99
99
100 #***************************************************************************
100 #***************************************************************************
101 # Main class implementing Magic functionality
101 # Main class implementing Magic functionality
102
102
103 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
103 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
104 # on construction of the main InteractiveShell object. Something odd is going
104 # on construction of the main InteractiveShell object. Something odd is going
105 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
105 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
106 # eventually this needs to be clarified.
106 # eventually this needs to be clarified.
107 # BG: This is because InteractiveShell inherits from this, but is itself a
107 # BG: This is because InteractiveShell inherits from this, but is itself a
108 # Configurable. This messes up the MRO in some way. The fix is that we need to
108 # Configurable. This messes up the MRO in some way. The fix is that we need to
109 # make Magic a configurable that InteractiveShell does not subclass.
109 # make Magic a configurable that InteractiveShell does not subclass.
110
110
111 class Magic:
111 class Magic:
112 """Magic functions for InteractiveShell.
112 """Magic functions for InteractiveShell.
113
113
114 Shell functions which can be reached as %function_name. All magic
114 Shell functions which can be reached as %function_name. All magic
115 functions should accept a string, which they can parse for their own
115 functions should accept a string, which they can parse for their own
116 needs. This can make some functions easier to type, eg `%cd ../`
116 needs. This can make some functions easier to type, eg `%cd ../`
117 vs. `%cd("../")`
117 vs. `%cd("../")`
118
118
119 ALL definitions MUST begin with the prefix magic_. The user won't need it
119 ALL definitions MUST begin with the prefix magic_. The user won't need it
120 at the command line, but it is is needed in the definition. """
120 at the command line, but it is is needed in the definition. """
121
121
122 # class globals
122 # class globals
123 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
123 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
124 'Automagic is ON, % prefix NOT needed for magic functions.']
124 'Automagic is ON, % prefix NOT needed for magic functions.']
125
125
126
126
127 configurables = None
127 configurables = None
128 #......................................................................
128 #......................................................................
129 # some utility functions
129 # some utility functions
130
130
131 def __init__(self,shell):
131 def __init__(self,shell):
132
132
133 self.options_table = {}
133 self.options_table = {}
134 if profile is None:
134 if profile is None:
135 self.magic_prun = self.profile_missing_notice
135 self.magic_prun = self.profile_missing_notice
136 self.shell = shell
136 self.shell = shell
137 if self.configurables is None:
137 if self.configurables is None:
138 self.configurables = []
138 self.configurables = []
139
139
140 # namespace for holding state we may need
140 # namespace for holding state we may need
141 self._magic_state = Bunch()
141 self._magic_state = Bunch()
142
142
143 def profile_missing_notice(self, *args, **kwargs):
143 def profile_missing_notice(self, *args, **kwargs):
144 error("""\
144 error("""\
145 The profile module could not be found. It has been removed from the standard
145 The profile module could not be found. It has been removed from the standard
146 python packages because of its non-free license. To use profiling, install the
146 python packages because of its non-free license. To use profiling, install the
147 python-profiler package from non-free.""")
147 python-profiler package from non-free.""")
148
148
149 def default_option(self,fn,optstr):
149 def default_option(self,fn,optstr):
150 """Make an entry in the options_table for fn, with value optstr"""
150 """Make an entry in the options_table for fn, with value optstr"""
151
151
152 if fn not in self.lsmagic():
152 if fn not in self.lsmagic():
153 error("%s is not a magic function" % fn)
153 error("%s is not a magic function" % fn)
154 self.options_table[fn] = optstr
154 self.options_table[fn] = optstr
155
155
156 def lsmagic(self):
156 def lsmagic(self):
157 """Return a list of currently available magic functions.
157 """Return a list of currently available magic functions.
158
158
159 Gives a list of the bare names after mangling (['ls','cd', ...], not
159 Gives a list of the bare names after mangling (['ls','cd', ...], not
160 ['magic_ls','magic_cd',...]"""
160 ['magic_ls','magic_cd',...]"""
161
161
162 # FIXME. This needs a cleanup, in the way the magics list is built.
162 # FIXME. This needs a cleanup, in the way the magics list is built.
163
163
164 # magics in class definition
164 # magics in class definition
165 class_magic = lambda fn: fn.startswith('magic_') and \
165 class_magic = lambda fn: fn.startswith('magic_') and \
166 callable(Magic.__dict__[fn])
166 callable(Magic.__dict__[fn])
167 # in instance namespace (run-time user additions)
167 # in instance namespace (run-time user additions)
168 inst_magic = lambda fn: fn.startswith('magic_') and \
168 inst_magic = lambda fn: fn.startswith('magic_') and \
169 callable(self.__dict__[fn])
169 callable(self.__dict__[fn])
170 # and bound magics by user (so they can access self):
170 # and bound magics by user (so they can access self):
171 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
171 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
172 callable(self.__class__.__dict__[fn])
172 callable(self.__class__.__dict__[fn])
173 magics = filter(class_magic,Magic.__dict__.keys()) + \
173 magics = filter(class_magic,Magic.__dict__.keys()) + \
174 filter(inst_magic,self.__dict__.keys()) + \
174 filter(inst_magic,self.__dict__.keys()) + \
175 filter(inst_bound_magic,self.__class__.__dict__.keys())
175 filter(inst_bound_magic,self.__class__.__dict__.keys())
176 out = []
176 out = []
177 for fn in set(magics):
177 for fn in set(magics):
178 out.append(fn.replace('magic_','',1))
178 out.append(fn.replace('magic_','',1))
179 out.sort()
179 out.sort()
180 return out
180 return out
181
181
182 def extract_input_lines(self, range_str, raw=False):
182 def extract_input_lines(self, range_str, raw=False):
183 """Return as a string a set of input history slices.
183 """Return as a string a set of input history slices.
184
184
185 Inputs:
185 Inputs:
186
186
187 - range_str: the set of slices is given as a string, like
187 - range_str: the set of slices is given as a string, like
188 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
188 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
189 which get their arguments as strings. The number before the / is the
189 which get their arguments as strings. The number before the / is the
190 session number: ~n goes n back from the current session.
190 session number: ~n goes n back from the current session.
191
191
192 Optional inputs:
192 Optional inputs:
193
193
194 - raw(False): by default, the processed input is used. If this is
194 - raw(False): by default, the processed input is used. If this is
195 true, the raw input history is used instead.
195 true, the raw input history is used instead.
196
196
197 Note that slices can be called with two notations:
197 Note that slices can be called with two notations:
198
198
199 N:M -> standard python form, means including items N...(M-1).
199 N:M -> standard python form, means including items N...(M-1).
200
200
201 N-M -> include items N..M (closed endpoint)."""
201 N-M -> include items N..M (closed endpoint)."""
202 lines = self.shell.history_manager.\
202 lines = self.shell.history_manager.\
203 get_range_by_str(range_str, raw=raw)
203 get_range_by_str(range_str, raw=raw)
204 return "\n".join(x for _, _, x in lines)
204 return "\n".join(x for _, _, x in lines)
205
205
206 def arg_err(self,func):
206 def arg_err(self,func):
207 """Print docstring if incorrect arguments were passed"""
207 """Print docstring if incorrect arguments were passed"""
208 print 'Error in arguments:'
208 print 'Error in arguments:'
209 print oinspect.getdoc(func)
209 print oinspect.getdoc(func)
210
210
211 def format_latex(self,strng):
211 def format_latex(self,strng):
212 """Format a string for latex inclusion."""
212 """Format a string for latex inclusion."""
213
213
214 # Characters that need to be escaped for latex:
214 # Characters that need to be escaped for latex:
215 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
215 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
216 # Magic command names as headers:
216 # Magic command names as headers:
217 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
217 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
218 re.MULTILINE)
218 re.MULTILINE)
219 # Magic commands
219 # Magic commands
220 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
220 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
221 re.MULTILINE)
221 re.MULTILINE)
222 # Paragraph continue
222 # Paragraph continue
223 par_re = re.compile(r'\\$',re.MULTILINE)
223 par_re = re.compile(r'\\$',re.MULTILINE)
224
224
225 # The "\n" symbol
225 # The "\n" symbol
226 newline_re = re.compile(r'\\n')
226 newline_re = re.compile(r'\\n')
227
227
228 # Now build the string for output:
228 # Now build the string for output:
229 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
229 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
230 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
230 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
231 strng)
231 strng)
232 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
232 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
233 strng = par_re.sub(r'\\\\',strng)
233 strng = par_re.sub(r'\\\\',strng)
234 strng = escape_re.sub(r'\\\1',strng)
234 strng = escape_re.sub(r'\\\1',strng)
235 strng = newline_re.sub(r'\\textbackslash{}n',strng)
235 strng = newline_re.sub(r'\\textbackslash{}n',strng)
236 return strng
236 return strng
237
237
238 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
238 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
239 """Parse options passed to an argument string.
239 """Parse options passed to an argument string.
240
240
241 The interface is similar to that of getopt(), but it returns back a
241 The interface is similar to that of getopt(), but it returns back a
242 Struct with the options as keys and the stripped argument string still
242 Struct with the options as keys and the stripped argument string still
243 as a string.
243 as a string.
244
244
245 arg_str is quoted as a true sys.argv vector by using shlex.split.
245 arg_str is quoted as a true sys.argv vector by using shlex.split.
246 This allows us to easily expand variables, glob files, quote
246 This allows us to easily expand variables, glob files, quote
247 arguments, etc.
247 arguments, etc.
248
248
249 Options:
249 Options:
250 -mode: default 'string'. If given as 'list', the argument string is
250 -mode: default 'string'. If given as 'list', the argument string is
251 returned as a list (split on whitespace) instead of a string.
251 returned as a list (split on whitespace) instead of a string.
252
252
253 -list_all: put all option values in lists. Normally only options
253 -list_all: put all option values in lists. Normally only options
254 appearing more than once are put in a list.
254 appearing more than once are put in a list.
255
255
256 -posix (True): whether to split the input line in POSIX mode or not,
256 -posix (True): whether to split the input line in POSIX mode or not,
257 as per the conventions outlined in the shlex module from the
257 as per the conventions outlined in the shlex module from the
258 standard library."""
258 standard library."""
259
259
260 # inject default options at the beginning of the input line
260 # inject default options at the beginning of the input line
261 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
261 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
262 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
262 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
263
263
264 mode = kw.get('mode','string')
264 mode = kw.get('mode','string')
265 if mode not in ['string','list']:
265 if mode not in ['string','list']:
266 raise ValueError,'incorrect mode given: %s' % mode
266 raise ValueError,'incorrect mode given: %s' % mode
267 # Get options
267 # Get options
268 list_all = kw.get('list_all',0)
268 list_all = kw.get('list_all',0)
269 posix = kw.get('posix', os.name == 'posix')
269 posix = kw.get('posix', os.name == 'posix')
270
270
271 # Check if we have more than one argument to warrant extra processing:
271 # Check if we have more than one argument to warrant extra processing:
272 odict = {} # Dictionary with options
272 odict = {} # Dictionary with options
273 args = arg_str.split()
273 args = arg_str.split()
274 if len(args) >= 1:
274 if len(args) >= 1:
275 # If the list of inputs only has 0 or 1 thing in it, there's no
275 # If the list of inputs only has 0 or 1 thing in it, there's no
276 # need to look for options
276 # need to look for options
277 argv = arg_split(arg_str,posix)
277 argv = arg_split(arg_str,posix)
278 # Do regular option processing
278 # Do regular option processing
279 try:
279 try:
280 opts,args = getopt(argv,opt_str,*long_opts)
280 opts,args = getopt(argv,opt_str,*long_opts)
281 except GetoptError,e:
281 except GetoptError,e:
282 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
282 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
283 " ".join(long_opts)))
283 " ".join(long_opts)))
284 for o,a in opts:
284 for o,a in opts:
285 if o.startswith('--'):
285 if o.startswith('--'):
286 o = o[2:]
286 o = o[2:]
287 else:
287 else:
288 o = o[1:]
288 o = o[1:]
289 try:
289 try:
290 odict[o].append(a)
290 odict[o].append(a)
291 except AttributeError:
291 except AttributeError:
292 odict[o] = [odict[o],a]
292 odict[o] = [odict[o],a]
293 except KeyError:
293 except KeyError:
294 if list_all:
294 if list_all:
295 odict[o] = [a]
295 odict[o] = [a]
296 else:
296 else:
297 odict[o] = a
297 odict[o] = a
298
298
299 # Prepare opts,args for return
299 # Prepare opts,args for return
300 opts = Struct(odict)
300 opts = Struct(odict)
301 if mode == 'string':
301 if mode == 'string':
302 args = ' '.join(args)
302 args = ' '.join(args)
303
303
304 return opts,args
304 return opts,args
305
305
306 #......................................................................
306 #......................................................................
307 # And now the actual magic functions
307 # And now the actual magic functions
308
308
309 # Functions for IPython shell work (vars,funcs, config, etc)
309 # Functions for IPython shell work (vars,funcs, config, etc)
310 def magic_lsmagic(self, parameter_s = ''):
310 def magic_lsmagic(self, parameter_s = ''):
311 """List currently available magic functions."""
311 """List currently available magic functions."""
312 mesc = ESC_MAGIC
312 mesc = ESC_MAGIC
313 print 'Available magic functions:\n'+mesc+\
313 print 'Available magic functions:\n'+mesc+\
314 (' '+mesc).join(self.lsmagic())
314 (' '+mesc).join(self.lsmagic())
315 print '\n' + Magic.auto_status[self.shell.automagic]
315 print '\n' + Magic.auto_status[self.shell.automagic]
316 return None
316 return None
317
317
318 def magic_magic(self, parameter_s = ''):
318 def magic_magic(self, parameter_s = ''):
319 """Print information about the magic function system.
319 """Print information about the magic function system.
320
320
321 Supported formats: -latex, -brief, -rest
321 Supported formats: -latex, -brief, -rest
322 """
322 """
323
323
324 mode = ''
324 mode = ''
325 try:
325 try:
326 if parameter_s.split()[0] == '-latex':
326 if parameter_s.split()[0] == '-latex':
327 mode = 'latex'
327 mode = 'latex'
328 if parameter_s.split()[0] == '-brief':
328 if parameter_s.split()[0] == '-brief':
329 mode = 'brief'
329 mode = 'brief'
330 if parameter_s.split()[0] == '-rest':
330 if parameter_s.split()[0] == '-rest':
331 mode = 'rest'
331 mode = 'rest'
332 rest_docs = []
332 rest_docs = []
333 except:
333 except:
334 pass
334 pass
335
335
336 magic_docs = []
336 magic_docs = []
337 for fname in self.lsmagic():
337 for fname in self.lsmagic():
338 mname = 'magic_' + fname
338 mname = 'magic_' + fname
339 for space in (Magic,self,self.__class__):
339 for space in (Magic,self,self.__class__):
340 try:
340 try:
341 fn = space.__dict__[mname]
341 fn = space.__dict__[mname]
342 except KeyError:
342 except KeyError:
343 pass
343 pass
344 else:
344 else:
345 break
345 break
346 if mode == 'brief':
346 if mode == 'brief':
347 # only first line
347 # only first line
348 if fn.__doc__:
348 if fn.__doc__:
349 fndoc = fn.__doc__.split('\n',1)[0]
349 fndoc = fn.__doc__.split('\n',1)[0]
350 else:
350 else:
351 fndoc = 'No documentation'
351 fndoc = 'No documentation'
352 else:
352 else:
353 if fn.__doc__:
353 if fn.__doc__:
354 fndoc = fn.__doc__.rstrip()
354 fndoc = fn.__doc__.rstrip()
355 else:
355 else:
356 fndoc = 'No documentation'
356 fndoc = 'No documentation'
357
357
358
358
359 if mode == 'rest':
359 if mode == 'rest':
360 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
360 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
361 fname,fndoc))
361 fname,fndoc))
362
362
363 else:
363 else:
364 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
364 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
365 fname,fndoc))
365 fname,fndoc))
366
366
367 magic_docs = ''.join(magic_docs)
367 magic_docs = ''.join(magic_docs)
368
368
369 if mode == 'rest':
369 if mode == 'rest':
370 return "".join(rest_docs)
370 return "".join(rest_docs)
371
371
372 if mode == 'latex':
372 if mode == 'latex':
373 print self.format_latex(magic_docs)
373 print self.format_latex(magic_docs)
374 return
374 return
375 else:
375 else:
376 magic_docs = format_screen(magic_docs)
376 magic_docs = format_screen(magic_docs)
377 if mode == 'brief':
377 if mode == 'brief':
378 return magic_docs
378 return magic_docs
379
379
380 outmsg = """
380 outmsg = """
381 IPython's 'magic' functions
381 IPython's 'magic' functions
382 ===========================
382 ===========================
383
383
384 The magic function system provides a series of functions which allow you to
384 The magic function system provides a series of functions which allow you to
385 control the behavior of IPython itself, plus a lot of system-type
385 control the behavior of IPython itself, plus a lot of system-type
386 features. All these functions are prefixed with a % character, but parameters
386 features. All these functions are prefixed with a % character, but parameters
387 are given without parentheses or quotes.
387 are given without parentheses or quotes.
388
388
389 NOTE: If you have 'automagic' enabled (via the command line option or with the
389 NOTE: If you have 'automagic' enabled (via the command line option or with the
390 %automagic function), you don't need to type in the % explicitly. By default,
390 %automagic function), you don't need to type in the % explicitly. By default,
391 IPython ships with automagic on, so you should only rarely need the % escape.
391 IPython ships with automagic on, so you should only rarely need the % escape.
392
392
393 Example: typing '%cd mydir' (without the quotes) changes you working directory
393 Example: typing '%cd mydir' (without the quotes) changes you working directory
394 to 'mydir', if it exists.
394 to 'mydir', if it exists.
395
395
396 For a list of the available magic functions, use %lsmagic. For a description
396 For a list of the available magic functions, use %lsmagic. For a description
397 of any of them, type %magic_name?, e.g. '%cd?'.
397 of any of them, type %magic_name?, e.g. '%cd?'.
398
398
399 Currently the magic system has the following functions:\n"""
399 Currently the magic system has the following functions:\n"""
400
400
401 mesc = ESC_MAGIC
401 mesc = ESC_MAGIC
402 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
402 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
403 "\n\n%s%s\n\n%s" % (outmsg,
403 "\n\n%s%s\n\n%s" % (outmsg,
404 magic_docs,mesc,mesc,
404 magic_docs,mesc,mesc,
405 (' '+mesc).join(self.lsmagic()),
405 (' '+mesc).join(self.lsmagic()),
406 Magic.auto_status[self.shell.automagic] ) )
406 Magic.auto_status[self.shell.automagic] ) )
407 page.page(outmsg)
407 page.page(outmsg)
408
408
409 def magic_automagic(self, parameter_s = ''):
409 def magic_automagic(self, parameter_s = ''):
410 """Make magic functions callable without having to type the initial %.
410 """Make magic functions callable without having to type the initial %.
411
411
412 Without argumentsl toggles on/off (when off, you must call it as
412 Without argumentsl toggles on/off (when off, you must call it as
413 %automagic, of course). With arguments it sets the value, and you can
413 %automagic, of course). With arguments it sets the value, and you can
414 use any of (case insensitive):
414 use any of (case insensitive):
415
415
416 - on,1,True: to activate
416 - on,1,True: to activate
417
417
418 - off,0,False: to deactivate.
418 - off,0,False: to deactivate.
419
419
420 Note that magic functions have lowest priority, so if there's a
420 Note that magic functions have lowest priority, so if there's a
421 variable whose name collides with that of a magic fn, automagic won't
421 variable whose name collides with that of a magic fn, automagic won't
422 work for that function (you get the variable instead). However, if you
422 work for that function (you get the variable instead). However, if you
423 delete the variable (del var), the previously shadowed magic function
423 delete the variable (del var), the previously shadowed magic function
424 becomes visible to automagic again."""
424 becomes visible to automagic again."""
425
425
426 arg = parameter_s.lower()
426 arg = parameter_s.lower()
427 if parameter_s in ('on','1','true'):
427 if parameter_s in ('on','1','true'):
428 self.shell.automagic = True
428 self.shell.automagic = True
429 elif parameter_s in ('off','0','false'):
429 elif parameter_s in ('off','0','false'):
430 self.shell.automagic = False
430 self.shell.automagic = False
431 else:
431 else:
432 self.shell.automagic = not self.shell.automagic
432 self.shell.automagic = not self.shell.automagic
433 print '\n' + Magic.auto_status[self.shell.automagic]
433 print '\n' + Magic.auto_status[self.shell.automagic]
434
434
435 @skip_doctest
435 @skip_doctest
436 def magic_autocall(self, parameter_s = ''):
436 def magic_autocall(self, parameter_s = ''):
437 """Make functions callable without having to type parentheses.
437 """Make functions callable without having to type parentheses.
438
438
439 Usage:
439 Usage:
440
440
441 %autocall [mode]
441 %autocall [mode]
442
442
443 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
443 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
444 value is toggled on and off (remembering the previous state).
444 value is toggled on and off (remembering the previous state).
445
445
446 In more detail, these values mean:
446 In more detail, these values mean:
447
447
448 0 -> fully disabled
448 0 -> fully disabled
449
449
450 1 -> active, but do not apply if there are no arguments on the line.
450 1 -> active, but do not apply if there are no arguments on the line.
451
451
452 In this mode, you get:
452 In this mode, you get:
453
453
454 In [1]: callable
454 In [1]: callable
455 Out[1]: <built-in function callable>
455 Out[1]: <built-in function callable>
456
456
457 In [2]: callable 'hello'
457 In [2]: callable 'hello'
458 ------> callable('hello')
458 ------> callable('hello')
459 Out[2]: False
459 Out[2]: False
460
460
461 2 -> Active always. Even if no arguments are present, the callable
461 2 -> Active always. Even if no arguments are present, the callable
462 object is called:
462 object is called:
463
463
464 In [2]: float
464 In [2]: float
465 ------> float()
465 ------> float()
466 Out[2]: 0.0
466 Out[2]: 0.0
467
467
468 Note that even with autocall off, you can still use '/' at the start of
468 Note that even with autocall off, you can still use '/' at the start of
469 a line to treat the first argument on the command line as a function
469 a line to treat the first argument on the command line as a function
470 and add parentheses to it:
470 and add parentheses to it:
471
471
472 In [8]: /str 43
472 In [8]: /str 43
473 ------> str(43)
473 ------> str(43)
474 Out[8]: '43'
474 Out[8]: '43'
475
475
476 # all-random (note for auto-testing)
476 # all-random (note for auto-testing)
477 """
477 """
478
478
479 if parameter_s:
479 if parameter_s:
480 arg = int(parameter_s)
480 arg = int(parameter_s)
481 else:
481 else:
482 arg = 'toggle'
482 arg = 'toggle'
483
483
484 if not arg in (0,1,2,'toggle'):
484 if not arg in (0,1,2,'toggle'):
485 error('Valid modes: (0->Off, 1->Smart, 2->Full')
485 error('Valid modes: (0->Off, 1->Smart, 2->Full')
486 return
486 return
487
487
488 if arg in (0,1,2):
488 if arg in (0,1,2):
489 self.shell.autocall = arg
489 self.shell.autocall = arg
490 else: # toggle
490 else: # toggle
491 if self.shell.autocall:
491 if self.shell.autocall:
492 self._magic_state.autocall_save = self.shell.autocall
492 self._magic_state.autocall_save = self.shell.autocall
493 self.shell.autocall = 0
493 self.shell.autocall = 0
494 else:
494 else:
495 try:
495 try:
496 self.shell.autocall = self._magic_state.autocall_save
496 self.shell.autocall = self._magic_state.autocall_save
497 except AttributeError:
497 except AttributeError:
498 self.shell.autocall = self._magic_state.autocall_save = 1
498 self.shell.autocall = self._magic_state.autocall_save = 1
499
499
500 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
500 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
501
501
502
502
503 def magic_page(self, parameter_s=''):
503 def magic_page(self, parameter_s=''):
504 """Pretty print the object and display it through a pager.
504 """Pretty print the object and display it through a pager.
505
505
506 %page [options] OBJECT
506 %page [options] OBJECT
507
507
508 If no object is given, use _ (last output).
508 If no object is given, use _ (last output).
509
509
510 Options:
510 Options:
511
511
512 -r: page str(object), don't pretty-print it."""
512 -r: page str(object), don't pretty-print it."""
513
513
514 # After a function contributed by Olivier Aubert, slightly modified.
514 # After a function contributed by Olivier Aubert, slightly modified.
515
515
516 # Process options/args
516 # Process options/args
517 opts,args = self.parse_options(parameter_s,'r')
517 opts,args = self.parse_options(parameter_s,'r')
518 raw = 'r' in opts
518 raw = 'r' in opts
519
519
520 oname = args and args or '_'
520 oname = args and args or '_'
521 info = self._ofind(oname)
521 info = self._ofind(oname)
522 if info['found']:
522 if info['found']:
523 txt = (raw and str or pformat)( info['obj'] )
523 txt = (raw and str or pformat)( info['obj'] )
524 page.page(txt)
524 page.page(txt)
525 else:
525 else:
526 print 'Object `%s` not found' % oname
526 print 'Object `%s` not found' % oname
527
527
528 def magic_profile(self, parameter_s=''):
528 def magic_profile(self, parameter_s=''):
529 """Print your currently active IPython profile."""
529 """Print your currently active IPython profile."""
530 print self.shell.profile
530 print self.shell.profile
531
531
532 def magic_pinfo(self, parameter_s='', namespaces=None):
532 def magic_pinfo(self, parameter_s='', namespaces=None):
533 """Provide detailed information about an object.
533 """Provide detailed information about an object.
534
534
535 '%pinfo object' is just a synonym for object? or ?object."""
535 '%pinfo object' is just a synonym for object? or ?object."""
536
536
537 #print 'pinfo par: <%s>' % parameter_s # dbg
537 #print 'pinfo par: <%s>' % parameter_s # dbg
538
538
539
539
540 # detail_level: 0 -> obj? , 1 -> obj??
540 # detail_level: 0 -> obj? , 1 -> obj??
541 detail_level = 0
541 detail_level = 0
542 # We need to detect if we got called as 'pinfo pinfo foo', which can
542 # We need to detect if we got called as 'pinfo pinfo foo', which can
543 # happen if the user types 'pinfo foo?' at the cmd line.
543 # happen if the user types 'pinfo foo?' at the cmd line.
544 pinfo,qmark1,oname,qmark2 = \
544 pinfo,qmark1,oname,qmark2 = \
545 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
545 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
546 if pinfo or qmark1 or qmark2:
546 if pinfo or qmark1 or qmark2:
547 detail_level = 1
547 detail_level = 1
548 if "*" in oname:
548 if "*" in oname:
549 self.magic_psearch(oname)
549 self.magic_psearch(oname)
550 else:
550 else:
551 self.shell._inspect('pinfo', oname, detail_level=detail_level,
551 self.shell._inspect('pinfo', oname, detail_level=detail_level,
552 namespaces=namespaces)
552 namespaces=namespaces)
553
553
554 def magic_pinfo2(self, parameter_s='', namespaces=None):
554 def magic_pinfo2(self, parameter_s='', namespaces=None):
555 """Provide extra detailed information about an object.
555 """Provide extra detailed information about an object.
556
556
557 '%pinfo2 object' is just a synonym for object?? or ??object."""
557 '%pinfo2 object' is just a synonym for object?? or ??object."""
558 self.shell._inspect('pinfo', parameter_s, detail_level=1,
558 self.shell._inspect('pinfo', parameter_s, detail_level=1,
559 namespaces=namespaces)
559 namespaces=namespaces)
560
560
561 @skip_doctest
561 @skip_doctest
562 def magic_pdef(self, parameter_s='', namespaces=None):
562 def magic_pdef(self, parameter_s='', namespaces=None):
563 """Print the definition header for any callable object.
563 """Print the definition header for any callable object.
564
564
565 If the object is a class, print the constructor information.
565 If the object is a class, print the constructor information.
566
566
567 Examples
567 Examples
568 --------
568 --------
569 ::
569 ::
570
570
571 In [3]: %pdef urllib.urlopen
571 In [3]: %pdef urllib.urlopen
572 urllib.urlopen(url, data=None, proxies=None)
572 urllib.urlopen(url, data=None, proxies=None)
573 """
573 """
574 self._inspect('pdef',parameter_s, namespaces)
574 self._inspect('pdef',parameter_s, namespaces)
575
575
576 def magic_pdoc(self, parameter_s='', namespaces=None):
576 def magic_pdoc(self, parameter_s='', namespaces=None):
577 """Print the docstring for an object.
577 """Print the docstring for an object.
578
578
579 If the given object is a class, it will print both the class and the
579 If the given object is a class, it will print both the class and the
580 constructor docstrings."""
580 constructor docstrings."""
581 self._inspect('pdoc',parameter_s, namespaces)
581 self._inspect('pdoc',parameter_s, namespaces)
582
582
583 def magic_psource(self, parameter_s='', namespaces=None):
583 def magic_psource(self, parameter_s='', namespaces=None):
584 """Print (or run through pager) the source code for an object."""
584 """Print (or run through pager) the source code for an object."""
585 self._inspect('psource',parameter_s, namespaces)
585 self._inspect('psource',parameter_s, namespaces)
586
586
587 def magic_pfile(self, parameter_s=''):
587 def magic_pfile(self, parameter_s=''):
588 """Print (or run through pager) the file where an object is defined.
588 """Print (or run through pager) the file where an object is defined.
589
589
590 The file opens at the line where the object definition begins. IPython
590 The file opens at the line where the object definition begins. IPython
591 will honor the environment variable PAGER if set, and otherwise will
591 will honor the environment variable PAGER if set, and otherwise will
592 do its best to print the file in a convenient form.
592 do its best to print the file in a convenient form.
593
593
594 If the given argument is not an object currently defined, IPython will
594 If the given argument is not an object currently defined, IPython will
595 try to interpret it as a filename (automatically adding a .py extension
595 try to interpret it as a filename (automatically adding a .py extension
596 if needed). You can thus use %pfile as a syntax highlighting code
596 if needed). You can thus use %pfile as a syntax highlighting code
597 viewer."""
597 viewer."""
598
598
599 # first interpret argument as an object name
599 # first interpret argument as an object name
600 out = self._inspect('pfile',parameter_s)
600 out = self._inspect('pfile',parameter_s)
601 # if not, try the input as a filename
601 # if not, try the input as a filename
602 if out == 'not found':
602 if out == 'not found':
603 try:
603 try:
604 filename = get_py_filename(parameter_s)
604 filename = get_py_filename(parameter_s)
605 except IOError,msg:
605 except IOError,msg:
606 print msg
606 print msg
607 return
607 return
608 page.page(self.shell.inspector.format(file(filename).read()))
608 page.page(self.shell.inspector.format(file(filename).read()))
609
609
610 def magic_psearch(self, parameter_s=''):
610 def magic_psearch(self, parameter_s=''):
611 """Search for object in namespaces by wildcard.
611 """Search for object in namespaces by wildcard.
612
612
613 %psearch [options] PATTERN [OBJECT TYPE]
613 %psearch [options] PATTERN [OBJECT TYPE]
614
614
615 Note: ? can be used as a synonym for %psearch, at the beginning or at
615 Note: ? can be used as a synonym for %psearch, at the beginning or at
616 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
616 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
617 rest of the command line must be unchanged (options come first), so
617 rest of the command line must be unchanged (options come first), so
618 for example the following forms are equivalent
618 for example the following forms are equivalent
619
619
620 %psearch -i a* function
620 %psearch -i a* function
621 -i a* function?
621 -i a* function?
622 ?-i a* function
622 ?-i a* function
623
623
624 Arguments:
624 Arguments:
625
625
626 PATTERN
626 PATTERN
627
627
628 where PATTERN is a string containing * as a wildcard similar to its
628 where PATTERN is a string containing * as a wildcard similar to its
629 use in a shell. The pattern is matched in all namespaces on the
629 use in a shell. The pattern is matched in all namespaces on the
630 search path. By default objects starting with a single _ are not
630 search path. By default objects starting with a single _ are not
631 matched, many IPython generated objects have a single
631 matched, many IPython generated objects have a single
632 underscore. The default is case insensitive matching. Matching is
632 underscore. The default is case insensitive matching. Matching is
633 also done on the attributes of objects and not only on the objects
633 also done on the attributes of objects and not only on the objects
634 in a module.
634 in a module.
635
635
636 [OBJECT TYPE]
636 [OBJECT TYPE]
637
637
638 Is the name of a python type from the types module. The name is
638 Is the name of a python type from the types module. The name is
639 given in lowercase without the ending type, ex. StringType is
639 given in lowercase without the ending type, ex. StringType is
640 written string. By adding a type here only objects matching the
640 written string. By adding a type here only objects matching the
641 given type are matched. Using all here makes the pattern match all
641 given type are matched. Using all here makes the pattern match all
642 types (this is the default).
642 types (this is the default).
643
643
644 Options:
644 Options:
645
645
646 -a: makes the pattern match even objects whose names start with a
646 -a: makes the pattern match even objects whose names start with a
647 single underscore. These names are normally ommitted from the
647 single underscore. These names are normally ommitted from the
648 search.
648 search.
649
649
650 -i/-c: make the pattern case insensitive/sensitive. If neither of
650 -i/-c: make the pattern case insensitive/sensitive. If neither of
651 these options are given, the default is read from your configuration
651 these options are given, the default is read from your configuration
652 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
652 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
653 If this option is not specified in your configuration file, IPython's
653 If this option is not specified in your configuration file, IPython's
654 internal default is to do a case sensitive search.
654 internal default is to do a case sensitive search.
655
655
656 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
656 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
657 specifiy can be searched in any of the following namespaces:
657 specifiy can be searched in any of the following namespaces:
658 'builtin', 'user', 'user_global','internal', 'alias', where
658 'builtin', 'user', 'user_global','internal', 'alias', where
659 'builtin' and 'user' are the search defaults. Note that you should
659 'builtin' and 'user' are the search defaults. Note that you should
660 not use quotes when specifying namespaces.
660 not use quotes when specifying namespaces.
661
661
662 'Builtin' contains the python module builtin, 'user' contains all
662 'Builtin' contains the python module builtin, 'user' contains all
663 user data, 'alias' only contain the shell aliases and no python
663 user data, 'alias' only contain the shell aliases and no python
664 objects, 'internal' contains objects used by IPython. The
664 objects, 'internal' contains objects used by IPython. The
665 'user_global' namespace is only used by embedded IPython instances,
665 'user_global' namespace is only used by embedded IPython instances,
666 and it contains module-level globals. You can add namespaces to the
666 and it contains module-level globals. You can add namespaces to the
667 search with -s or exclude them with -e (these options can be given
667 search with -s or exclude them with -e (these options can be given
668 more than once).
668 more than once).
669
669
670 Examples:
670 Examples:
671
671
672 %psearch a* -> objects beginning with an a
672 %psearch a* -> objects beginning with an a
673 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
673 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
674 %psearch a* function -> all functions beginning with an a
674 %psearch a* function -> all functions beginning with an a
675 %psearch re.e* -> objects beginning with an e in module re
675 %psearch re.e* -> objects beginning with an e in module re
676 %psearch r*.e* -> objects that start with e in modules starting in r
676 %psearch r*.e* -> objects that start with e in modules starting in r
677 %psearch r*.* string -> all strings in modules beginning with r
677 %psearch r*.* string -> all strings in modules beginning with r
678
678
679 Case sensitve search:
679 Case sensitve search:
680
680
681 %psearch -c a* list all object beginning with lower case a
681 %psearch -c a* list all object beginning with lower case a
682
682
683 Show objects beginning with a single _:
683 Show objects beginning with a single _:
684
684
685 %psearch -a _* list objects beginning with a single underscore"""
685 %psearch -a _* list objects beginning with a single underscore"""
686 try:
686 try:
687 parameter_s.encode('ascii')
687 parameter_s.encode('ascii')
688 except UnicodeEncodeError:
688 except UnicodeEncodeError:
689 print 'Python identifiers can only contain ascii characters.'
689 print 'Python identifiers can only contain ascii characters.'
690 return
690 return
691
691
692 # default namespaces to be searched
692 # default namespaces to be searched
693 def_search = ['user','builtin']
693 def_search = ['user','builtin']
694
694
695 # Process options/args
695 # Process options/args
696 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
696 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
697 opt = opts.get
697 opt = opts.get
698 shell = self.shell
698 shell = self.shell
699 psearch = shell.inspector.psearch
699 psearch = shell.inspector.psearch
700
700
701 # select case options
701 # select case options
702 if opts.has_key('i'):
702 if opts.has_key('i'):
703 ignore_case = True
703 ignore_case = True
704 elif opts.has_key('c'):
704 elif opts.has_key('c'):
705 ignore_case = False
705 ignore_case = False
706 else:
706 else:
707 ignore_case = not shell.wildcards_case_sensitive
707 ignore_case = not shell.wildcards_case_sensitive
708
708
709 # Build list of namespaces to search from user options
709 # Build list of namespaces to search from user options
710 def_search.extend(opt('s',[]))
710 def_search.extend(opt('s',[]))
711 ns_exclude = ns_exclude=opt('e',[])
711 ns_exclude = ns_exclude=opt('e',[])
712 ns_search = [nm for nm in def_search if nm not in ns_exclude]
712 ns_search = [nm for nm in def_search if nm not in ns_exclude]
713
713
714 # Call the actual search
714 # Call the actual search
715 try:
715 try:
716 psearch(args,shell.ns_table,ns_search,
716 psearch(args,shell.ns_table,ns_search,
717 show_all=opt('a'),ignore_case=ignore_case)
717 show_all=opt('a'),ignore_case=ignore_case)
718 except:
718 except:
719 shell.showtraceback()
719 shell.showtraceback()
720
720
721 @skip_doctest
721 @skip_doctest
722 def magic_who_ls(self, parameter_s=''):
722 def magic_who_ls(self, parameter_s=''):
723 """Return a sorted list of all interactive variables.
723 """Return a sorted list of all interactive variables.
724
724
725 If arguments are given, only variables of types matching these
725 If arguments are given, only variables of types matching these
726 arguments are returned.
726 arguments are returned.
727
727
728 Examples
728 Examples
729 --------
729 --------
730
730
731 Define two variables and list them with who_ls::
731 Define two variables and list them with who_ls::
732
732
733 In [1]: alpha = 123
733 In [1]: alpha = 123
734
734
735 In [2]: beta = 'test'
735 In [2]: beta = 'test'
736
736
737 In [3]: %who_ls
737 In [3]: %who_ls
738 Out[3]: ['alpha', 'beta']
738 Out[3]: ['alpha', 'beta']
739
739
740 In [4]: %who_ls int
740 In [4]: %who_ls int
741 Out[4]: ['alpha']
741 Out[4]: ['alpha']
742
742
743 In [5]: %who_ls str
743 In [5]: %who_ls str
744 Out[5]: ['beta']
744 Out[5]: ['beta']
745 """
745 """
746
746
747 user_ns = self.shell.user_ns
747 user_ns = self.shell.user_ns
748 internal_ns = self.shell.internal_ns
748 internal_ns = self.shell.internal_ns
749 user_ns_hidden = self.shell.user_ns_hidden
749 user_ns_hidden = self.shell.user_ns_hidden
750 out = [ i for i in user_ns
750 out = [ i for i in user_ns
751 if not i.startswith('_') \
751 if not i.startswith('_') \
752 and not (i in internal_ns or i in user_ns_hidden) ]
752 and not (i in internal_ns or i in user_ns_hidden) ]
753
753
754 typelist = parameter_s.split()
754 typelist = parameter_s.split()
755 if typelist:
755 if typelist:
756 typeset = set(typelist)
756 typeset = set(typelist)
757 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
757 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
758
758
759 out.sort()
759 out.sort()
760 return out
760 return out
761
761
762 @skip_doctest
762 @skip_doctest
763 def magic_who(self, parameter_s=''):
763 def magic_who(self, parameter_s=''):
764 """Print all interactive variables, with some minimal formatting.
764 """Print all interactive variables, with some minimal formatting.
765
765
766 If any arguments are given, only variables whose type matches one of
766 If any arguments are given, only variables whose type matches one of
767 these are printed. For example:
767 these are printed. For example:
768
768
769 %who function str
769 %who function str
770
770
771 will only list functions and strings, excluding all other types of
771 will only list functions and strings, excluding all other types of
772 variables. To find the proper type names, simply use type(var) at a
772 variables. To find the proper type names, simply use type(var) at a
773 command line to see how python prints type names. For example:
773 command line to see how python prints type names. For example:
774
774
775 In [1]: type('hello')\\
775 In [1]: type('hello')\\
776 Out[1]: <type 'str'>
776 Out[1]: <type 'str'>
777
777
778 indicates that the type name for strings is 'str'.
778 indicates that the type name for strings is 'str'.
779
779
780 %who always excludes executed names loaded through your configuration
780 %who always excludes executed names loaded through your configuration
781 file and things which are internal to IPython.
781 file and things which are internal to IPython.
782
782
783 This is deliberate, as typically you may load many modules and the
783 This is deliberate, as typically you may load many modules and the
784 purpose of %who is to show you only what you've manually defined.
784 purpose of %who is to show you only what you've manually defined.
785
785
786 Examples
786 Examples
787 --------
787 --------
788
788
789 Define two variables and list them with who::
789 Define two variables and list them with who::
790
790
791 In [1]: alpha = 123
791 In [1]: alpha = 123
792
792
793 In [2]: beta = 'test'
793 In [2]: beta = 'test'
794
794
795 In [3]: %who
795 In [3]: %who
796 alpha beta
796 alpha beta
797
797
798 In [4]: %who int
798 In [4]: %who int
799 alpha
799 alpha
800
800
801 In [5]: %who str
801 In [5]: %who str
802 beta
802 beta
803 """
803 """
804
804
805 varlist = self.magic_who_ls(parameter_s)
805 varlist = self.magic_who_ls(parameter_s)
806 if not varlist:
806 if not varlist:
807 if parameter_s:
807 if parameter_s:
808 print 'No variables match your requested type.'
808 print 'No variables match your requested type.'
809 else:
809 else:
810 print 'Interactive namespace is empty.'
810 print 'Interactive namespace is empty.'
811 return
811 return
812
812
813 # if we have variables, move on...
813 # if we have variables, move on...
814 count = 0
814 count = 0
815 for i in varlist:
815 for i in varlist:
816 print i+'\t',
816 print i+'\t',
817 count += 1
817 count += 1
818 if count > 8:
818 if count > 8:
819 count = 0
819 count = 0
820 print
820 print
821 print
821 print
822
822
823 @skip_doctest
823 @skip_doctest
824 def magic_whos(self, parameter_s=''):
824 def magic_whos(self, parameter_s=''):
825 """Like %who, but gives some extra information about each variable.
825 """Like %who, but gives some extra information about each variable.
826
826
827 The same type filtering of %who can be applied here.
827 The same type filtering of %who can be applied here.
828
828
829 For all variables, the type is printed. Additionally it prints:
829 For all variables, the type is printed. Additionally it prints:
830
830
831 - For {},[],(): their length.
831 - For {},[],(): their length.
832
832
833 - For numpy arrays, a summary with shape, number of
833 - For numpy arrays, a summary with shape, number of
834 elements, typecode and size in memory.
834 elements, typecode and size in memory.
835
835
836 - Everything else: a string representation, snipping their middle if
836 - Everything else: a string representation, snipping their middle if
837 too long.
837 too long.
838
838
839 Examples
839 Examples
840 --------
840 --------
841
841
842 Define two variables and list them with whos::
842 Define two variables and list them with whos::
843
843
844 In [1]: alpha = 123
844 In [1]: alpha = 123
845
845
846 In [2]: beta = 'test'
846 In [2]: beta = 'test'
847
847
848 In [3]: %whos
848 In [3]: %whos
849 Variable Type Data/Info
849 Variable Type Data/Info
850 --------------------------------
850 --------------------------------
851 alpha int 123
851 alpha int 123
852 beta str test
852 beta str test
853 """
853 """
854
854
855 varnames = self.magic_who_ls(parameter_s)
855 varnames = self.magic_who_ls(parameter_s)
856 if not varnames:
856 if not varnames:
857 if parameter_s:
857 if parameter_s:
858 print 'No variables match your requested type.'
858 print 'No variables match your requested type.'
859 else:
859 else:
860 print 'Interactive namespace is empty.'
860 print 'Interactive namespace is empty.'
861 return
861 return
862
862
863 # if we have variables, move on...
863 # if we have variables, move on...
864
864
865 # for these types, show len() instead of data:
865 # for these types, show len() instead of data:
866 seq_types = ['dict', 'list', 'tuple']
866 seq_types = ['dict', 'list', 'tuple']
867
867
868 # for numpy arrays, display summary info
868 # for numpy arrays, display summary info
869 ndarray_type = None
869 ndarray_type = None
870 if 'numpy' in sys.modules:
870 if 'numpy' in sys.modules:
871 try:
871 try:
872 from numpy import ndarray
872 from numpy import ndarray
873 except ImportError:
873 except ImportError:
874 pass
874 pass
875 else:
875 else:
876 ndarray_type = ndarray.__name__
876 ndarray_type = ndarray.__name__
877
877
878 # Find all variable names and types so we can figure out column sizes
878 # Find all variable names and types so we can figure out column sizes
879 def get_vars(i):
879 def get_vars(i):
880 return self.shell.user_ns[i]
880 return self.shell.user_ns[i]
881
881
882 # some types are well known and can be shorter
882 # some types are well known and can be shorter
883 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
883 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
884 def type_name(v):
884 def type_name(v):
885 tn = type(v).__name__
885 tn = type(v).__name__
886 return abbrevs.get(tn,tn)
886 return abbrevs.get(tn,tn)
887
887
888 varlist = map(get_vars,varnames)
888 varlist = map(get_vars,varnames)
889
889
890 typelist = []
890 typelist = []
891 for vv in varlist:
891 for vv in varlist:
892 tt = type_name(vv)
892 tt = type_name(vv)
893
893
894 if tt=='instance':
894 if tt=='instance':
895 typelist.append( abbrevs.get(str(vv.__class__),
895 typelist.append( abbrevs.get(str(vv.__class__),
896 str(vv.__class__)))
896 str(vv.__class__)))
897 else:
897 else:
898 typelist.append(tt)
898 typelist.append(tt)
899
899
900 # column labels and # of spaces as separator
900 # column labels and # of spaces as separator
901 varlabel = 'Variable'
901 varlabel = 'Variable'
902 typelabel = 'Type'
902 typelabel = 'Type'
903 datalabel = 'Data/Info'
903 datalabel = 'Data/Info'
904 colsep = 3
904 colsep = 3
905 # variable format strings
905 # variable format strings
906 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
906 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
907 aformat = "%s: %s elems, type `%s`, %s bytes"
907 aformat = "%s: %s elems, type `%s`, %s bytes"
908 # find the size of the columns to format the output nicely
908 # find the size of the columns to format the output nicely
909 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
909 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
910 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
910 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
911 # table header
911 # table header
912 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
912 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
913 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
913 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
914 # and the table itself
914 # and the table itself
915 kb = 1024
915 kb = 1024
916 Mb = 1048576 # kb**2
916 Mb = 1048576 # kb**2
917 for vname,var,vtype in zip(varnames,varlist,typelist):
917 for vname,var,vtype in zip(varnames,varlist,typelist):
918 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
918 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
919 if vtype in seq_types:
919 if vtype in seq_types:
920 print "n="+str(len(var))
920 print "n="+str(len(var))
921 elif vtype == ndarray_type:
921 elif vtype == ndarray_type:
922 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
922 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
923 if vtype==ndarray_type:
923 if vtype==ndarray_type:
924 # numpy
924 # numpy
925 vsize = var.size
925 vsize = var.size
926 vbytes = vsize*var.itemsize
926 vbytes = vsize*var.itemsize
927 vdtype = var.dtype
927 vdtype = var.dtype
928 else:
928 else:
929 # Numeric
929 # Numeric
930 vsize = Numeric.size(var)
930 vsize = Numeric.size(var)
931 vbytes = vsize*var.itemsize()
931 vbytes = vsize*var.itemsize()
932 vdtype = var.typecode()
932 vdtype = var.typecode()
933
933
934 if vbytes < 100000:
934 if vbytes < 100000:
935 print aformat % (vshape,vsize,vdtype,vbytes)
935 print aformat % (vshape,vsize,vdtype,vbytes)
936 else:
936 else:
937 print aformat % (vshape,vsize,vdtype,vbytes),
937 print aformat % (vshape,vsize,vdtype,vbytes),
938 if vbytes < Mb:
938 if vbytes < Mb:
939 print '(%s kb)' % (vbytes/kb,)
939 print '(%s kb)' % (vbytes/kb,)
940 else:
940 else:
941 print '(%s Mb)' % (vbytes/Mb,)
941 print '(%s Mb)' % (vbytes/Mb,)
942 else:
942 else:
943 try:
943 try:
944 vstr = str(var)
944 vstr = str(var)
945 except UnicodeEncodeError:
945 except UnicodeEncodeError:
946 vstr = unicode(var).encode(sys.getdefaultencoding(),
946 vstr = unicode(var).encode(sys.getdefaultencoding(),
947 'backslashreplace')
947 'backslashreplace')
948 vstr = vstr.replace('\n','\\n')
948 vstr = vstr.replace('\n','\\n')
949 if len(vstr) < 50:
949 if len(vstr) < 50:
950 print vstr
950 print vstr
951 else:
951 else:
952 print vstr[:25] + "<...>" + vstr[-25:]
952 print vstr[:25] + "<...>" + vstr[-25:]
953
953
954 def magic_reset(self, parameter_s=''):
954 def magic_reset(self, parameter_s=''):
955 """Resets the namespace by removing all names defined by the user.
955 """Resets the namespace by removing all names defined by the user.
956
956
957 Parameters
957 Parameters
958 ----------
958 ----------
959 -f : force reset without asking for confirmation.
959 -f : force reset without asking for confirmation.
960
960
961 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
961 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
962 References to objects may be kept. By default (without this option),
962 References to objects may be kept. By default (without this option),
963 we do a 'hard' reset, giving you a new session and removing all
963 we do a 'hard' reset, giving you a new session and removing all
964 references to objects from the current session.
964 references to objects from the current session.
965
965
966 Examples
966 Examples
967 --------
967 --------
968 In [6]: a = 1
968 In [6]: a = 1
969
969
970 In [7]: a
970 In [7]: a
971 Out[7]: 1
971 Out[7]: 1
972
972
973 In [8]: 'a' in _ip.user_ns
973 In [8]: 'a' in _ip.user_ns
974 Out[8]: True
974 Out[8]: True
975
975
976 In [9]: %reset -f
976 In [9]: %reset -f
977
977
978 In [1]: 'a' in _ip.user_ns
978 In [1]: 'a' in _ip.user_ns
979 Out[1]: False
979 Out[1]: False
980 """
980 """
981 opts, args = self.parse_options(parameter_s,'sf')
981 opts, args = self.parse_options(parameter_s,'sf')
982 if 'f' in opts:
982 if 'f' in opts:
983 ans = True
983 ans = True
984 else:
984 else:
985 ans = self.shell.ask_yes_no(
985 ans = self.shell.ask_yes_no(
986 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
986 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
987 if not ans:
987 if not ans:
988 print 'Nothing done.'
988 print 'Nothing done.'
989 return
989 return
990
990
991 if 's' in opts: # Soft reset
991 if 's' in opts: # Soft reset
992 user_ns = self.shell.user_ns
992 user_ns = self.shell.user_ns
993 for i in self.magic_who_ls():
993 for i in self.magic_who_ls():
994 del(user_ns[i])
994 del(user_ns[i])
995
995
996 else: # Hard reset
996 else: # Hard reset
997 self.shell.reset(new_session = False)
997 self.shell.reset(new_session = False)
998
998
999
999
1000
1000
1001 def magic_reset_selective(self, parameter_s=''):
1001 def magic_reset_selective(self, parameter_s=''):
1002 """Resets the namespace by removing names defined by the user.
1002 """Resets the namespace by removing names defined by the user.
1003
1003
1004 Input/Output history are left around in case you need them.
1004 Input/Output history are left around in case you need them.
1005
1005
1006 %reset_selective [-f] regex
1006 %reset_selective [-f] regex
1007
1007
1008 No action is taken if regex is not included
1008 No action is taken if regex is not included
1009
1009
1010 Options
1010 Options
1011 -f : force reset without asking for confirmation.
1011 -f : force reset without asking for confirmation.
1012
1012
1013 Examples
1013 Examples
1014 --------
1014 --------
1015
1015
1016 We first fully reset the namespace so your output looks identical to
1016 We first fully reset the namespace so your output looks identical to
1017 this example for pedagogical reasons; in practice you do not need a
1017 this example for pedagogical reasons; in practice you do not need a
1018 full reset.
1018 full reset.
1019
1019
1020 In [1]: %reset -f
1020 In [1]: %reset -f
1021
1021
1022 Now, with a clean namespace we can make a few variables and use
1022 Now, with a clean namespace we can make a few variables and use
1023 %reset_selective to only delete names that match our regexp:
1023 %reset_selective to only delete names that match our regexp:
1024
1024
1025 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1025 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1026
1026
1027 In [3]: who_ls
1027 In [3]: who_ls
1028 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1028 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1029
1029
1030 In [4]: %reset_selective -f b[2-3]m
1030 In [4]: %reset_selective -f b[2-3]m
1031
1031
1032 In [5]: who_ls
1032 In [5]: who_ls
1033 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1033 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1034
1034
1035 In [6]: %reset_selective -f d
1035 In [6]: %reset_selective -f d
1036
1036
1037 In [7]: who_ls
1037 In [7]: who_ls
1038 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1038 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1039
1039
1040 In [8]: %reset_selective -f c
1040 In [8]: %reset_selective -f c
1041
1041
1042 In [9]: who_ls
1042 In [9]: who_ls
1043 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1043 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1044
1044
1045 In [10]: %reset_selective -f b
1045 In [10]: %reset_selective -f b
1046
1046
1047 In [11]: who_ls
1047 In [11]: who_ls
1048 Out[11]: ['a']
1048 Out[11]: ['a']
1049 """
1049 """
1050
1050
1051 opts, regex = self.parse_options(parameter_s,'f')
1051 opts, regex = self.parse_options(parameter_s,'f')
1052
1052
1053 if opts.has_key('f'):
1053 if opts.has_key('f'):
1054 ans = True
1054 ans = True
1055 else:
1055 else:
1056 ans = self.shell.ask_yes_no(
1056 ans = self.shell.ask_yes_no(
1057 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1057 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1058 if not ans:
1058 if not ans:
1059 print 'Nothing done.'
1059 print 'Nothing done.'
1060 return
1060 return
1061 user_ns = self.shell.user_ns
1061 user_ns = self.shell.user_ns
1062 if not regex:
1062 if not regex:
1063 print 'No regex pattern specified. Nothing done.'
1063 print 'No regex pattern specified. Nothing done.'
1064 return
1064 return
1065 else:
1065 else:
1066 try:
1066 try:
1067 m = re.compile(regex)
1067 m = re.compile(regex)
1068 except TypeError:
1068 except TypeError:
1069 raise TypeError('regex must be a string or compiled pattern')
1069 raise TypeError('regex must be a string or compiled pattern')
1070 for i in self.magic_who_ls():
1070 for i in self.magic_who_ls():
1071 if m.search(i):
1071 if m.search(i):
1072 del(user_ns[i])
1072 del(user_ns[i])
1073
1073
1074 def magic_xdel(self, parameter_s=''):
1074 def magic_xdel(self, parameter_s=''):
1075 """Delete a variable, trying to clear it from anywhere that
1075 """Delete a variable, trying to clear it from anywhere that
1076 IPython's machinery has references to it. By default, this uses
1076 IPython's machinery has references to it. By default, this uses
1077 the identity of the named object in the user namespace to remove
1077 the identity of the named object in the user namespace to remove
1078 references held under other names. The object is also removed
1078 references held under other names. The object is also removed
1079 from the output history.
1079 from the output history.
1080
1080
1081 Options
1081 Options
1082 -n : Delete the specified name from all namespaces, without
1082 -n : Delete the specified name from all namespaces, without
1083 checking their identity.
1083 checking their identity.
1084 """
1084 """
1085 opts, varname = self.parse_options(parameter_s,'n')
1085 opts, varname = self.parse_options(parameter_s,'n')
1086 try:
1086 try:
1087 self.shell.del_var(varname, ('n' in opts))
1087 self.shell.del_var(varname, ('n' in opts))
1088 except (NameError, ValueError) as e:
1088 except (NameError, ValueError) as e:
1089 print type(e).__name__ +": "+ str(e)
1089 print type(e).__name__ +": "+ str(e)
1090
1090
1091 def magic_logstart(self,parameter_s=''):
1091 def magic_logstart(self,parameter_s=''):
1092 """Start logging anywhere in a session.
1092 """Start logging anywhere in a session.
1093
1093
1094 %logstart [-o|-r|-t] [log_name [log_mode]]
1094 %logstart [-o|-r|-t] [log_name [log_mode]]
1095
1095
1096 If no name is given, it defaults to a file named 'ipython_log.py' in your
1096 If no name is given, it defaults to a file named 'ipython_log.py' in your
1097 current directory, in 'rotate' mode (see below).
1097 current directory, in 'rotate' mode (see below).
1098
1098
1099 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1099 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1100 history up to that point and then continues logging.
1100 history up to that point and then continues logging.
1101
1101
1102 %logstart takes a second optional parameter: logging mode. This can be one
1102 %logstart takes a second optional parameter: logging mode. This can be one
1103 of (note that the modes are given unquoted):\\
1103 of (note that the modes are given unquoted):\\
1104 append: well, that says it.\\
1104 append: well, that says it.\\
1105 backup: rename (if exists) to name~ and start name.\\
1105 backup: rename (if exists) to name~ and start name.\\
1106 global: single logfile in your home dir, appended to.\\
1106 global: single logfile in your home dir, appended to.\\
1107 over : overwrite existing log.\\
1107 over : overwrite existing log.\\
1108 rotate: create rotating logs name.1~, name.2~, etc.
1108 rotate: create rotating logs name.1~, name.2~, etc.
1109
1109
1110 Options:
1110 Options:
1111
1111
1112 -o: log also IPython's output. In this mode, all commands which
1112 -o: log also IPython's output. In this mode, all commands which
1113 generate an Out[NN] prompt are recorded to the logfile, right after
1113 generate an Out[NN] prompt are recorded to the logfile, right after
1114 their corresponding input line. The output lines are always
1114 their corresponding input line. The output lines are always
1115 prepended with a '#[Out]# ' marker, so that the log remains valid
1115 prepended with a '#[Out]# ' marker, so that the log remains valid
1116 Python code.
1116 Python code.
1117
1117
1118 Since this marker is always the same, filtering only the output from
1118 Since this marker is always the same, filtering only the output from
1119 a log is very easy, using for example a simple awk call:
1119 a log is very easy, using for example a simple awk call:
1120
1120
1121 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1121 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1122
1122
1123 -r: log 'raw' input. Normally, IPython's logs contain the processed
1123 -r: log 'raw' input. Normally, IPython's logs contain the processed
1124 input, so that user lines are logged in their final form, converted
1124 input, so that user lines are logged in their final form, converted
1125 into valid Python. For example, %Exit is logged as
1125 into valid Python. For example, %Exit is logged as
1126 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1126 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1127 exactly as typed, with no transformations applied.
1127 exactly as typed, with no transformations applied.
1128
1128
1129 -t: put timestamps before each input line logged (these are put in
1129 -t: put timestamps before each input line logged (these are put in
1130 comments)."""
1130 comments)."""
1131
1131
1132 opts,par = self.parse_options(parameter_s,'ort')
1132 opts,par = self.parse_options(parameter_s,'ort')
1133 log_output = 'o' in opts
1133 log_output = 'o' in opts
1134 log_raw_input = 'r' in opts
1134 log_raw_input = 'r' in opts
1135 timestamp = 't' in opts
1135 timestamp = 't' in opts
1136
1136
1137 logger = self.shell.logger
1137 logger = self.shell.logger
1138
1138
1139 # if no args are given, the defaults set in the logger constructor by
1139 # if no args are given, the defaults set in the logger constructor by
1140 # ipytohn remain valid
1140 # ipytohn remain valid
1141 if par:
1141 if par:
1142 try:
1142 try:
1143 logfname,logmode = par.split()
1143 logfname,logmode = par.split()
1144 except:
1144 except:
1145 logfname = par
1145 logfname = par
1146 logmode = 'backup'
1146 logmode = 'backup'
1147 else:
1147 else:
1148 logfname = logger.logfname
1148 logfname = logger.logfname
1149 logmode = logger.logmode
1149 logmode = logger.logmode
1150 # put logfname into rc struct as if it had been called on the command
1150 # put logfname into rc struct as if it had been called on the command
1151 # line, so it ends up saved in the log header Save it in case we need
1151 # line, so it ends up saved in the log header Save it in case we need
1152 # to restore it...
1152 # to restore it...
1153 old_logfile = self.shell.logfile
1153 old_logfile = self.shell.logfile
1154 if logfname:
1154 if logfname:
1155 logfname = os.path.expanduser(logfname)
1155 logfname = os.path.expanduser(logfname)
1156 self.shell.logfile = logfname
1156 self.shell.logfile = logfname
1157
1157
1158 loghead = '# IPython log file\n\n'
1158 loghead = '# IPython log file\n\n'
1159 try:
1159 try:
1160 started = logger.logstart(logfname,loghead,logmode,
1160 started = logger.logstart(logfname,loghead,logmode,
1161 log_output,timestamp,log_raw_input)
1161 log_output,timestamp,log_raw_input)
1162 except:
1162 except:
1163 self.shell.logfile = old_logfile
1163 self.shell.logfile = old_logfile
1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1165 else:
1165 else:
1166 # log input history up to this point, optionally interleaving
1166 # log input history up to this point, optionally interleaving
1167 # output if requested
1167 # output if requested
1168
1168
1169 if timestamp:
1169 if timestamp:
1170 # disable timestamping for the previous history, since we've
1170 # disable timestamping for the previous history, since we've
1171 # lost those already (no time machine here).
1171 # lost those already (no time machine here).
1172 logger.timestamp = False
1172 logger.timestamp = False
1173
1173
1174 if log_raw_input:
1174 if log_raw_input:
1175 input_hist = self.shell.history_manager.input_hist_raw
1175 input_hist = self.shell.history_manager.input_hist_raw
1176 else:
1176 else:
1177 input_hist = self.shell.history_manager.input_hist_parsed
1177 input_hist = self.shell.history_manager.input_hist_parsed
1178
1178
1179 if log_output:
1179 if log_output:
1180 log_write = logger.log_write
1180 log_write = logger.log_write
1181 output_hist = self.shell.history_manager.output_hist
1181 output_hist = self.shell.history_manager.output_hist
1182 for n in range(1,len(input_hist)-1):
1182 for n in range(1,len(input_hist)-1):
1183 log_write(input_hist[n].rstrip() + '\n')
1183 log_write(input_hist[n].rstrip() + '\n')
1184 if n in output_hist:
1184 if n in output_hist:
1185 log_write(repr(output_hist[n]),'output')
1185 log_write(repr(output_hist[n]),'output')
1186 else:
1186 else:
1187 logger.log_write('\n'.join(input_hist[1:]))
1187 logger.log_write('\n'.join(input_hist[1:]))
1188 logger.log_write('\n')
1188 logger.log_write('\n')
1189 if timestamp:
1189 if timestamp:
1190 # re-enable timestamping
1190 # re-enable timestamping
1191 logger.timestamp = True
1191 logger.timestamp = True
1192
1192
1193 print ('Activating auto-logging. '
1193 print ('Activating auto-logging. '
1194 'Current session state plus future input saved.')
1194 'Current session state plus future input saved.')
1195 logger.logstate()
1195 logger.logstate()
1196
1196
1197 def magic_logstop(self,parameter_s=''):
1197 def magic_logstop(self,parameter_s=''):
1198 """Fully stop logging and close log file.
1198 """Fully stop logging and close log file.
1199
1199
1200 In order to start logging again, a new %logstart call needs to be made,
1200 In order to start logging again, a new %logstart call needs to be made,
1201 possibly (though not necessarily) with a new filename, mode and other
1201 possibly (though not necessarily) with a new filename, mode and other
1202 options."""
1202 options."""
1203 self.logger.logstop()
1203 self.logger.logstop()
1204
1204
1205 def magic_logoff(self,parameter_s=''):
1205 def magic_logoff(self,parameter_s=''):
1206 """Temporarily stop logging.
1206 """Temporarily stop logging.
1207
1207
1208 You must have previously started logging."""
1208 You must have previously started logging."""
1209 self.shell.logger.switch_log(0)
1209 self.shell.logger.switch_log(0)
1210
1210
1211 def magic_logon(self,parameter_s=''):
1211 def magic_logon(self,parameter_s=''):
1212 """Restart logging.
1212 """Restart logging.
1213
1213
1214 This function is for restarting logging which you've temporarily
1214 This function is for restarting logging which you've temporarily
1215 stopped with %logoff. For starting logging for the first time, you
1215 stopped with %logoff. For starting logging for the first time, you
1216 must use the %logstart function, which allows you to specify an
1216 must use the %logstart function, which allows you to specify an
1217 optional log filename."""
1217 optional log filename."""
1218
1218
1219 self.shell.logger.switch_log(1)
1219 self.shell.logger.switch_log(1)
1220
1220
1221 def magic_logstate(self,parameter_s=''):
1221 def magic_logstate(self,parameter_s=''):
1222 """Print the status of the logging system."""
1222 """Print the status of the logging system."""
1223
1223
1224 self.shell.logger.logstate()
1224 self.shell.logger.logstate()
1225
1225
1226 def magic_pdb(self, parameter_s=''):
1226 def magic_pdb(self, parameter_s=''):
1227 """Control the automatic calling of the pdb interactive debugger.
1227 """Control the automatic calling of the pdb interactive debugger.
1228
1228
1229 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1229 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1230 argument it works as a toggle.
1230 argument it works as a toggle.
1231
1231
1232 When an exception is triggered, IPython can optionally call the
1232 When an exception is triggered, IPython can optionally call the
1233 interactive pdb debugger after the traceback printout. %pdb toggles
1233 interactive pdb debugger after the traceback printout. %pdb toggles
1234 this feature on and off.
1234 this feature on and off.
1235
1235
1236 The initial state of this feature is set in your configuration
1236 The initial state of this feature is set in your configuration
1237 file (the option is ``InteractiveShell.pdb``).
1237 file (the option is ``InteractiveShell.pdb``).
1238
1238
1239 If you want to just activate the debugger AFTER an exception has fired,
1239 If you want to just activate the debugger AFTER an exception has fired,
1240 without having to type '%pdb on' and rerunning your code, you can use
1240 without having to type '%pdb on' and rerunning your code, you can use
1241 the %debug magic."""
1241 the %debug magic."""
1242
1242
1243 par = parameter_s.strip().lower()
1243 par = parameter_s.strip().lower()
1244
1244
1245 if par:
1245 if par:
1246 try:
1246 try:
1247 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1247 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1248 except KeyError:
1248 except KeyError:
1249 print ('Incorrect argument. Use on/1, off/0, '
1249 print ('Incorrect argument. Use on/1, off/0, '
1250 'or nothing for a toggle.')
1250 'or nothing for a toggle.')
1251 return
1251 return
1252 else:
1252 else:
1253 # toggle
1253 # toggle
1254 new_pdb = not self.shell.call_pdb
1254 new_pdb = not self.shell.call_pdb
1255
1255
1256 # set on the shell
1256 # set on the shell
1257 self.shell.call_pdb = new_pdb
1257 self.shell.call_pdb = new_pdb
1258 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1258 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1259
1259
1260 def magic_debug(self, parameter_s=''):
1260 def magic_debug(self, parameter_s=''):
1261 """Activate the interactive debugger in post-mortem mode.
1261 """Activate the interactive debugger in post-mortem mode.
1262
1262
1263 If an exception has just occurred, this lets you inspect its stack
1263 If an exception has just occurred, this lets you inspect its stack
1264 frames interactively. Note that this will always work only on the last
1264 frames interactively. Note that this will always work only on the last
1265 traceback that occurred, so you must call this quickly after an
1265 traceback that occurred, so you must call this quickly after an
1266 exception that you wish to inspect has fired, because if another one
1266 exception that you wish to inspect has fired, because if another one
1267 occurs, it clobbers the previous one.
1267 occurs, it clobbers the previous one.
1268
1268
1269 If you want IPython to automatically do this on every exception, see
1269 If you want IPython to automatically do this on every exception, see
1270 the %pdb magic for more details.
1270 the %pdb magic for more details.
1271 """
1271 """
1272 self.shell.debugger(force=True)
1272 self.shell.debugger(force=True)
1273
1273
1274 @skip_doctest
1274 @skip_doctest
1275 def magic_prun(self, parameter_s ='',user_mode=1,
1275 def magic_prun(self, parameter_s ='',user_mode=1,
1276 opts=None,arg_lst=None,prog_ns=None):
1276 opts=None,arg_lst=None,prog_ns=None):
1277
1277
1278 """Run a statement through the python code profiler.
1278 """Run a statement through the python code profiler.
1279
1279
1280 Usage:
1280 Usage:
1281 %prun [options] statement
1281 %prun [options] statement
1282
1282
1283 The given statement (which doesn't require quote marks) is run via the
1283 The given statement (which doesn't require quote marks) is run via the
1284 python profiler in a manner similar to the profile.run() function.
1284 python profiler in a manner similar to the profile.run() function.
1285 Namespaces are internally managed to work correctly; profile.run
1285 Namespaces are internally managed to work correctly; profile.run
1286 cannot be used in IPython because it makes certain assumptions about
1286 cannot be used in IPython because it makes certain assumptions about
1287 namespaces which do not hold under IPython.
1287 namespaces which do not hold under IPython.
1288
1288
1289 Options:
1289 Options:
1290
1290
1291 -l <limit>: you can place restrictions on what or how much of the
1291 -l <limit>: you can place restrictions on what or how much of the
1292 profile gets printed. The limit value can be:
1292 profile gets printed. The limit value can be:
1293
1293
1294 * A string: only information for function names containing this string
1294 * A string: only information for function names containing this string
1295 is printed.
1295 is printed.
1296
1296
1297 * An integer: only these many lines are printed.
1297 * An integer: only these many lines are printed.
1298
1298
1299 * A float (between 0 and 1): this fraction of the report is printed
1299 * A float (between 0 and 1): this fraction of the report is printed
1300 (for example, use a limit of 0.4 to see the topmost 40% only).
1300 (for example, use a limit of 0.4 to see the topmost 40% only).
1301
1301
1302 You can combine several limits with repeated use of the option. For
1302 You can combine several limits with repeated use of the option. For
1303 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1303 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1304 information about class constructors.
1304 information about class constructors.
1305
1305
1306 -r: return the pstats.Stats object generated by the profiling. This
1306 -r: return the pstats.Stats object generated by the profiling. This
1307 object has all the information about the profile in it, and you can
1307 object has all the information about the profile in it, and you can
1308 later use it for further analysis or in other functions.
1308 later use it for further analysis or in other functions.
1309
1309
1310 -s <key>: sort profile by given key. You can provide more than one key
1310 -s <key>: sort profile by given key. You can provide more than one key
1311 by using the option several times: '-s key1 -s key2 -s key3...'. The
1311 by using the option several times: '-s key1 -s key2 -s key3...'. The
1312 default sorting key is 'time'.
1312 default sorting key is 'time'.
1313
1313
1314 The following is copied verbatim from the profile documentation
1314 The following is copied verbatim from the profile documentation
1315 referenced below:
1315 referenced below:
1316
1316
1317 When more than one key is provided, additional keys are used as
1317 When more than one key is provided, additional keys are used as
1318 secondary criteria when the there is equality in all keys selected
1318 secondary criteria when the there is equality in all keys selected
1319 before them.
1319 before them.
1320
1320
1321 Abbreviations can be used for any key names, as long as the
1321 Abbreviations can be used for any key names, as long as the
1322 abbreviation is unambiguous. The following are the keys currently
1322 abbreviation is unambiguous. The following are the keys currently
1323 defined:
1323 defined:
1324
1324
1325 Valid Arg Meaning
1325 Valid Arg Meaning
1326 "calls" call count
1326 "calls" call count
1327 "cumulative" cumulative time
1327 "cumulative" cumulative time
1328 "file" file name
1328 "file" file name
1329 "module" file name
1329 "module" file name
1330 "pcalls" primitive call count
1330 "pcalls" primitive call count
1331 "line" line number
1331 "line" line number
1332 "name" function name
1332 "name" function name
1333 "nfl" name/file/line
1333 "nfl" name/file/line
1334 "stdname" standard name
1334 "stdname" standard name
1335 "time" internal time
1335 "time" internal time
1336
1336
1337 Note that all sorts on statistics are in descending order (placing
1337 Note that all sorts on statistics are in descending order (placing
1338 most time consuming items first), where as name, file, and line number
1338 most time consuming items first), where as name, file, and line number
1339 searches are in ascending order (i.e., alphabetical). The subtle
1339 searches are in ascending order (i.e., alphabetical). The subtle
1340 distinction between "nfl" and "stdname" is that the standard name is a
1340 distinction between "nfl" and "stdname" is that the standard name is a
1341 sort of the name as printed, which means that the embedded line
1341 sort of the name as printed, which means that the embedded line
1342 numbers get compared in an odd way. For example, lines 3, 20, and 40
1342 numbers get compared in an odd way. For example, lines 3, 20, and 40
1343 would (if the file names were the same) appear in the string order
1343 would (if the file names were the same) appear in the string order
1344 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1344 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1345 line numbers. In fact, sort_stats("nfl") is the same as
1345 line numbers. In fact, sort_stats("nfl") is the same as
1346 sort_stats("name", "file", "line").
1346 sort_stats("name", "file", "line").
1347
1347
1348 -T <filename>: save profile results as shown on screen to a text
1348 -T <filename>: save profile results as shown on screen to a text
1349 file. The profile is still shown on screen.
1349 file. The profile is still shown on screen.
1350
1350
1351 -D <filename>: save (via dump_stats) profile statistics to given
1351 -D <filename>: save (via dump_stats) profile statistics to given
1352 filename. This data is in a format understod by the pstats module, and
1352 filename. This data is in a format understod by the pstats module, and
1353 is generated by a call to the dump_stats() method of profile
1353 is generated by a call to the dump_stats() method of profile
1354 objects. The profile is still shown on screen.
1354 objects. The profile is still shown on screen.
1355
1355
1356 If you want to run complete programs under the profiler's control, use
1356 If you want to run complete programs under the profiler's control, use
1357 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1357 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1358 contains profiler specific options as described here.
1358 contains profiler specific options as described here.
1359
1359
1360 You can read the complete documentation for the profile module with::
1360 You can read the complete documentation for the profile module with::
1361
1361
1362 In [1]: import profile; profile.help()
1362 In [1]: import profile; profile.help()
1363 """
1363 """
1364
1364
1365 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1365 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1366 # protect user quote marks
1366 # protect user quote marks
1367 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1367 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1368
1368
1369 if user_mode: # regular user call
1369 if user_mode: # regular user call
1370 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1370 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1371 list_all=1)
1371 list_all=1)
1372 namespace = self.shell.user_ns
1372 namespace = self.shell.user_ns
1373 else: # called to run a program by %run -p
1373 else: # called to run a program by %run -p
1374 try:
1374 try:
1375 filename = get_py_filename(arg_lst[0])
1375 filename = get_py_filename(arg_lst[0])
1376 except IOError as e:
1376 except IOError as e:
1377 try:
1377 try:
1378 msg = str(e)
1378 msg = str(e)
1379 except UnicodeError:
1379 except UnicodeError:
1380 msg = e.message
1380 msg = e.message
1381 error(msg)
1381 error(msg)
1382 return
1382 return
1383
1383
1384 arg_str = 'execfile(filename,prog_ns)'
1384 arg_str = 'execfile(filename,prog_ns)'
1385 namespace = locals()
1385 namespace = locals()
1386
1386
1387 opts.merge(opts_def)
1387 opts.merge(opts_def)
1388
1388
1389 prof = profile.Profile()
1389 prof = profile.Profile()
1390 try:
1390 try:
1391 prof = prof.runctx(arg_str,namespace,namespace)
1391 prof = prof.runctx(arg_str,namespace,namespace)
1392 sys_exit = ''
1392 sys_exit = ''
1393 except SystemExit:
1393 except SystemExit:
1394 sys_exit = """*** SystemExit exception caught in code being profiled."""
1394 sys_exit = """*** SystemExit exception caught in code being profiled."""
1395
1395
1396 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1396 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1397
1397
1398 lims = opts.l
1398 lims = opts.l
1399 if lims:
1399 if lims:
1400 lims = [] # rebuild lims with ints/floats/strings
1400 lims = [] # rebuild lims with ints/floats/strings
1401 for lim in opts.l:
1401 for lim in opts.l:
1402 try:
1402 try:
1403 lims.append(int(lim))
1403 lims.append(int(lim))
1404 except ValueError:
1404 except ValueError:
1405 try:
1405 try:
1406 lims.append(float(lim))
1406 lims.append(float(lim))
1407 except ValueError:
1407 except ValueError:
1408 lims.append(lim)
1408 lims.append(lim)
1409
1409
1410 # Trap output.
1410 # Trap output.
1411 stdout_trap = StringIO()
1411 stdout_trap = StringIO()
1412
1412
1413 if hasattr(stats,'stream'):
1413 if hasattr(stats,'stream'):
1414 # In newer versions of python, the stats object has a 'stream'
1414 # In newer versions of python, the stats object has a 'stream'
1415 # attribute to write into.
1415 # attribute to write into.
1416 stats.stream = stdout_trap
1416 stats.stream = stdout_trap
1417 stats.print_stats(*lims)
1417 stats.print_stats(*lims)
1418 else:
1418 else:
1419 # For older versions, we manually redirect stdout during printing
1419 # For older versions, we manually redirect stdout during printing
1420 sys_stdout = sys.stdout
1420 sys_stdout = sys.stdout
1421 try:
1421 try:
1422 sys.stdout = stdout_trap
1422 sys.stdout = stdout_trap
1423 stats.print_stats(*lims)
1423 stats.print_stats(*lims)
1424 finally:
1424 finally:
1425 sys.stdout = sys_stdout
1425 sys.stdout = sys_stdout
1426
1426
1427 output = stdout_trap.getvalue()
1427 output = stdout_trap.getvalue()
1428 output = output.rstrip()
1428 output = output.rstrip()
1429
1429
1430 page.page(output)
1430 page.page(output)
1431 print sys_exit,
1431 print sys_exit,
1432
1432
1433 dump_file = opts.D[0]
1433 dump_file = opts.D[0]
1434 text_file = opts.T[0]
1434 text_file = opts.T[0]
1435 if dump_file:
1435 if dump_file:
1436 dump_file = unquote_filename(dump_file)
1436 dump_file = unquote_filename(dump_file)
1437 prof.dump_stats(dump_file)
1437 prof.dump_stats(dump_file)
1438 print '\n*** Profile stats marshalled to file',\
1438 print '\n*** Profile stats marshalled to file',\
1439 `dump_file`+'.',sys_exit
1439 `dump_file`+'.',sys_exit
1440 if text_file:
1440 if text_file:
1441 text_file = unquote_filename(text_file)
1441 text_file = unquote_filename(text_file)
1442 pfile = file(text_file,'w')
1442 pfile = file(text_file,'w')
1443 pfile.write(output)
1443 pfile.write(output)
1444 pfile.close()
1444 pfile.close()
1445 print '\n*** Profile printout saved to text file',\
1445 print '\n*** Profile printout saved to text file',\
1446 `text_file`+'.',sys_exit
1446 `text_file`+'.',sys_exit
1447
1447
1448 if opts.has_key('r'):
1448 if opts.has_key('r'):
1449 return stats
1449 return stats
1450 else:
1450 else:
1451 return None
1451 return None
1452
1452
1453 @skip_doctest
1453 @skip_doctest
1454 def magic_run(self, parameter_s ='', runner=None,
1454 def magic_run(self, parameter_s ='', runner=None,
1455 file_finder=get_py_filename):
1455 file_finder=get_py_filename):
1456 """Run the named file inside IPython as a program.
1456 """Run the named file inside IPython as a program.
1457
1457
1458 Usage:\\
1458 Usage:\\
1459 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1459 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1460
1460
1461 Parameters after the filename are passed as command-line arguments to
1461 Parameters after the filename are passed as command-line arguments to
1462 the program (put in sys.argv). Then, control returns to IPython's
1462 the program (put in sys.argv). Then, control returns to IPython's
1463 prompt.
1463 prompt.
1464
1464
1465 This is similar to running at a system prompt:\\
1465 This is similar to running at a system prompt:\\
1466 $ python file args\\
1466 $ python file args\\
1467 but with the advantage of giving you IPython's tracebacks, and of
1467 but with the advantage of giving you IPython's tracebacks, and of
1468 loading all variables into your interactive namespace for further use
1468 loading all variables into your interactive namespace for further use
1469 (unless -p is used, see below).
1469 (unless -p is used, see below).
1470
1470
1471 The file is executed in a namespace initially consisting only of
1471 The file is executed in a namespace initially consisting only of
1472 __name__=='__main__' and sys.argv constructed as indicated. It thus
1472 __name__=='__main__' and sys.argv constructed as indicated. It thus
1473 sees its environment as if it were being run as a stand-alone program
1473 sees its environment as if it were being run as a stand-alone program
1474 (except for sharing global objects such as previously imported
1474 (except for sharing global objects such as previously imported
1475 modules). But after execution, the IPython interactive namespace gets
1475 modules). But after execution, the IPython interactive namespace gets
1476 updated with all variables defined in the program (except for __name__
1476 updated with all variables defined in the program (except for __name__
1477 and sys.argv). This allows for very convenient loading of code for
1477 and sys.argv). This allows for very convenient loading of code for
1478 interactive work, while giving each program a 'clean sheet' to run in.
1478 interactive work, while giving each program a 'clean sheet' to run in.
1479
1479
1480 Options:
1480 Options:
1481
1481
1482 -n: __name__ is NOT set to '__main__', but to the running file's name
1482 -n: __name__ is NOT set to '__main__', but to the running file's name
1483 without extension (as python does under import). This allows running
1483 without extension (as python does under import). This allows running
1484 scripts and reloading the definitions in them without calling code
1484 scripts and reloading the definitions in them without calling code
1485 protected by an ' if __name__ == "__main__" ' clause.
1485 protected by an ' if __name__ == "__main__" ' clause.
1486
1486
1487 -i: run the file in IPython's namespace instead of an empty one. This
1487 -i: run the file in IPython's namespace instead of an empty one. This
1488 is useful if you are experimenting with code written in a text editor
1488 is useful if you are experimenting with code written in a text editor
1489 which depends on variables defined interactively.
1489 which depends on variables defined interactively.
1490
1490
1491 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1491 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1492 being run. This is particularly useful if IPython is being used to
1492 being run. This is particularly useful if IPython is being used to
1493 run unittests, which always exit with a sys.exit() call. In such
1493 run unittests, which always exit with a sys.exit() call. In such
1494 cases you are interested in the output of the test results, not in
1494 cases you are interested in the output of the test results, not in
1495 seeing a traceback of the unittest module.
1495 seeing a traceback of the unittest module.
1496
1496
1497 -t: print timing information at the end of the run. IPython will give
1497 -t: print timing information at the end of the run. IPython will give
1498 you an estimated CPU time consumption for your script, which under
1498 you an estimated CPU time consumption for your script, which under
1499 Unix uses the resource module to avoid the wraparound problems of
1499 Unix uses the resource module to avoid the wraparound problems of
1500 time.clock(). Under Unix, an estimate of time spent on system tasks
1500 time.clock(). Under Unix, an estimate of time spent on system tasks
1501 is also given (for Windows platforms this is reported as 0.0).
1501 is also given (for Windows platforms this is reported as 0.0).
1502
1502
1503 If -t is given, an additional -N<N> option can be given, where <N>
1503 If -t is given, an additional -N<N> option can be given, where <N>
1504 must be an integer indicating how many times you want the script to
1504 must be an integer indicating how many times you want the script to
1505 run. The final timing report will include total and per run results.
1505 run. The final timing report will include total and per run results.
1506
1506
1507 For example (testing the script uniq_stable.py):
1507 For example (testing the script uniq_stable.py):
1508
1508
1509 In [1]: run -t uniq_stable
1509 In [1]: run -t uniq_stable
1510
1510
1511 IPython CPU timings (estimated):\\
1511 IPython CPU timings (estimated):\\
1512 User : 0.19597 s.\\
1512 User : 0.19597 s.\\
1513 System: 0.0 s.\\
1513 System: 0.0 s.\\
1514
1514
1515 In [2]: run -t -N5 uniq_stable
1515 In [2]: run -t -N5 uniq_stable
1516
1516
1517 IPython CPU timings (estimated):\\
1517 IPython CPU timings (estimated):\\
1518 Total runs performed: 5\\
1518 Total runs performed: 5\\
1519 Times : Total Per run\\
1519 Times : Total Per run\\
1520 User : 0.910862 s, 0.1821724 s.\\
1520 User : 0.910862 s, 0.1821724 s.\\
1521 System: 0.0 s, 0.0 s.
1521 System: 0.0 s, 0.0 s.
1522
1522
1523 -d: run your program under the control of pdb, the Python debugger.
1523 -d: run your program under the control of pdb, the Python debugger.
1524 This allows you to execute your program step by step, watch variables,
1524 This allows you to execute your program step by step, watch variables,
1525 etc. Internally, what IPython does is similar to calling:
1525 etc. Internally, what IPython does is similar to calling:
1526
1526
1527 pdb.run('execfile("YOURFILENAME")')
1527 pdb.run('execfile("YOURFILENAME")')
1528
1528
1529 with a breakpoint set on line 1 of your file. You can change the line
1529 with a breakpoint set on line 1 of your file. You can change the line
1530 number for this automatic breakpoint to be <N> by using the -bN option
1530 number for this automatic breakpoint to be <N> by using the -bN option
1531 (where N must be an integer). For example:
1531 (where N must be an integer). For example:
1532
1532
1533 %run -d -b40 myscript
1533 %run -d -b40 myscript
1534
1534
1535 will set the first breakpoint at line 40 in myscript.py. Note that
1535 will set the first breakpoint at line 40 in myscript.py. Note that
1536 the first breakpoint must be set on a line which actually does
1536 the first breakpoint must be set on a line which actually does
1537 something (not a comment or docstring) for it to stop execution.
1537 something (not a comment or docstring) for it to stop execution.
1538
1538
1539 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1539 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1540 first enter 'c' (without qoutes) to start execution up to the first
1540 first enter 'c' (without qoutes) to start execution up to the first
1541 breakpoint.
1541 breakpoint.
1542
1542
1543 Entering 'help' gives information about the use of the debugger. You
1543 Entering 'help' gives information about the use of the debugger. You
1544 can easily see pdb's full documentation with "import pdb;pdb.help()"
1544 can easily see pdb's full documentation with "import pdb;pdb.help()"
1545 at a prompt.
1545 at a prompt.
1546
1546
1547 -p: run program under the control of the Python profiler module (which
1547 -p: run program under the control of the Python profiler module (which
1548 prints a detailed report of execution times, function calls, etc).
1548 prints a detailed report of execution times, function calls, etc).
1549
1549
1550 You can pass other options after -p which affect the behavior of the
1550 You can pass other options after -p which affect the behavior of the
1551 profiler itself. See the docs for %prun for details.
1551 profiler itself. See the docs for %prun for details.
1552
1552
1553 In this mode, the program's variables do NOT propagate back to the
1553 In this mode, the program's variables do NOT propagate back to the
1554 IPython interactive namespace (because they remain in the namespace
1554 IPython interactive namespace (because they remain in the namespace
1555 where the profiler executes them).
1555 where the profiler executes them).
1556
1556
1557 Internally this triggers a call to %prun, see its documentation for
1557 Internally this triggers a call to %prun, see its documentation for
1558 details on the options available specifically for profiling.
1558 details on the options available specifically for profiling.
1559
1559
1560 There is one special usage for which the text above doesn't apply:
1560 There is one special usage for which the text above doesn't apply:
1561 if the filename ends with .ipy, the file is run as ipython script,
1561 if the filename ends with .ipy, the file is run as ipython script,
1562 just as if the commands were written on IPython prompt.
1562 just as if the commands were written on IPython prompt.
1563
1563
1564 -m: specify module name to load instead of script path. Similar to
1564 -m: specify module name to load instead of script path. Similar to
1565 the -m option for the python interpreter. Use this option last if you
1565 the -m option for the python interpreter. Use this option last if you
1566 want to combine with other %run options. Unlike the python interpreter
1566 want to combine with other %run options. Unlike the python interpreter
1567 only source modules are allowed no .pyc or .pyo files.
1567 only source modules are allowed no .pyc or .pyo files.
1568 For example:
1568 For example:
1569
1569
1570 %run -m example
1570 %run -m example
1571
1571
1572 will run the example module.
1572 will run the example module.
1573
1573
1574 """
1574 """
1575
1575
1576 # get arguments and set sys.argv for program to be run.
1576 # get arguments and set sys.argv for program to be run.
1577 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1577 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1578 mode='list', list_all=1)
1578 mode='list', list_all=1)
1579 if "m" in opts:
1579 if "m" in opts:
1580 modulename = opts["m"][0]
1580 modulename = opts["m"][0]
1581 modpath = find_mod(modulename)
1581 modpath = find_mod(modulename)
1582 if modpath is None:
1582 if modpath is None:
1583 warn('%r is not a valid modulename on sys.path'%modulename)
1583 warn('%r is not a valid modulename on sys.path'%modulename)
1584 return
1584 return
1585 arg_lst = [modpath] + arg_lst
1585 arg_lst = [modpath] + arg_lst
1586 try:
1586 try:
1587 filename = file_finder(arg_lst[0])
1587 filename = file_finder(arg_lst[0])
1588 except IndexError:
1588 except IndexError:
1589 warn('you must provide at least a filename.')
1589 warn('you must provide at least a filename.')
1590 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1590 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1591 return
1591 return
1592 except IOError as e:
1592 except IOError as e:
1593 try:
1593 try:
1594 msg = str(e)
1594 msg = str(e)
1595 except UnicodeError:
1595 except UnicodeError:
1596 msg = e.message
1596 msg = e.message
1597 error(msg)
1597 error(msg)
1598 return
1598 return
1599
1599
1600 if filename.lower().endswith('.ipy'):
1600 if filename.lower().endswith('.ipy'):
1601 self.shell.safe_execfile_ipy(filename)
1601 self.shell.safe_execfile_ipy(filename)
1602 return
1602 return
1603
1603
1604 # Control the response to exit() calls made by the script being run
1604 # Control the response to exit() calls made by the script being run
1605 exit_ignore = 'e' in opts
1605 exit_ignore = 'e' in opts
1606
1606
1607 # Make sure that the running script gets a proper sys.argv as if it
1607 # Make sure that the running script gets a proper sys.argv as if it
1608 # were run from a system shell.
1608 # were run from a system shell.
1609 save_argv = sys.argv # save it for later restoring
1609 save_argv = sys.argv # save it for later restoring
1610
1610
1611 # simulate shell expansion on arguments, at least tilde expansion
1611 # simulate shell expansion on arguments, at least tilde expansion
1612 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1612 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1613
1613
1614 sys.argv = [filename] + args # put in the proper filename
1614 sys.argv = [filename] + args # put in the proper filename
1615 # protect sys.argv from potential unicode strings on Python 2:
1615 # protect sys.argv from potential unicode strings on Python 2:
1616 if not py3compat.PY3:
1616 if not py3compat.PY3:
1617 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1617 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1618
1618
1619 if 'i' in opts:
1619 if 'i' in opts:
1620 # Run in user's interactive namespace
1620 # Run in user's interactive namespace
1621 prog_ns = self.shell.user_ns
1621 prog_ns = self.shell.user_ns
1622 __name__save = self.shell.user_ns['__name__']
1622 __name__save = self.shell.user_ns['__name__']
1623 prog_ns['__name__'] = '__main__'
1623 prog_ns['__name__'] = '__main__'
1624 main_mod = self.shell.new_main_mod(prog_ns)
1624 main_mod = self.shell.new_main_mod(prog_ns)
1625 else:
1625 else:
1626 # Run in a fresh, empty namespace
1626 # Run in a fresh, empty namespace
1627 if 'n' in opts:
1627 if 'n' in opts:
1628 name = os.path.splitext(os.path.basename(filename))[0]
1628 name = os.path.splitext(os.path.basename(filename))[0]
1629 else:
1629 else:
1630 name = '__main__'
1630 name = '__main__'
1631
1631
1632 main_mod = self.shell.new_main_mod()
1632 main_mod = self.shell.new_main_mod()
1633 prog_ns = main_mod.__dict__
1633 prog_ns = main_mod.__dict__
1634 prog_ns['__name__'] = name
1634 prog_ns['__name__'] = name
1635
1635
1636 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1636 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1637 # set the __file__ global in the script's namespace
1637 # set the __file__ global in the script's namespace
1638 prog_ns['__file__'] = filename
1638 prog_ns['__file__'] = filename
1639
1639
1640 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1640 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1641 # that, if we overwrite __main__, we replace it at the end
1641 # that, if we overwrite __main__, we replace it at the end
1642 main_mod_name = prog_ns['__name__']
1642 main_mod_name = prog_ns['__name__']
1643
1643
1644 if main_mod_name == '__main__':
1644 if main_mod_name == '__main__':
1645 restore_main = sys.modules['__main__']
1645 restore_main = sys.modules['__main__']
1646 else:
1646 else:
1647 restore_main = False
1647 restore_main = False
1648
1648
1649 # This needs to be undone at the end to prevent holding references to
1649 # This needs to be undone at the end to prevent holding references to
1650 # every single object ever created.
1650 # every single object ever created.
1651 sys.modules[main_mod_name] = main_mod
1651 sys.modules[main_mod_name] = main_mod
1652
1652
1653 try:
1653 try:
1654 stats = None
1654 stats = None
1655 with self.readline_no_record:
1655 with self.readline_no_record:
1656 if 'p' in opts:
1656 if 'p' in opts:
1657 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1657 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1658 else:
1658 else:
1659 if 'd' in opts:
1659 if 'd' in opts:
1660 deb = debugger.Pdb(self.shell.colors)
1660 deb = debugger.Pdb(self.shell.colors)
1661 # reset Breakpoint state, which is moronically kept
1661 # reset Breakpoint state, which is moronically kept
1662 # in a class
1662 # in a class
1663 bdb.Breakpoint.next = 1
1663 bdb.Breakpoint.next = 1
1664 bdb.Breakpoint.bplist = {}
1664 bdb.Breakpoint.bplist = {}
1665 bdb.Breakpoint.bpbynumber = [None]
1665 bdb.Breakpoint.bpbynumber = [None]
1666 # Set an initial breakpoint to stop execution
1666 # Set an initial breakpoint to stop execution
1667 maxtries = 10
1667 maxtries = 10
1668 bp = int(opts.get('b', [1])[0])
1668 bp = int(opts.get('b', [1])[0])
1669 checkline = deb.checkline(filename, bp)
1669 checkline = deb.checkline(filename, bp)
1670 if not checkline:
1670 if not checkline:
1671 for bp in range(bp + 1, bp + maxtries + 1):
1671 for bp in range(bp + 1, bp + maxtries + 1):
1672 if deb.checkline(filename, bp):
1672 if deb.checkline(filename, bp):
1673 break
1673 break
1674 else:
1674 else:
1675 msg = ("\nI failed to find a valid line to set "
1675 msg = ("\nI failed to find a valid line to set "
1676 "a breakpoint\n"
1676 "a breakpoint\n"
1677 "after trying up to line: %s.\n"
1677 "after trying up to line: %s.\n"
1678 "Please set a valid breakpoint manually "
1678 "Please set a valid breakpoint manually "
1679 "with the -b option." % bp)
1679 "with the -b option." % bp)
1680 error(msg)
1680 error(msg)
1681 return
1681 return
1682 # if we find a good linenumber, set the breakpoint
1682 # if we find a good linenumber, set the breakpoint
1683 deb.do_break('%s:%s' % (filename, bp))
1683 deb.do_break('%s:%s' % (filename, bp))
1684 # Start file run
1684 # Start file run
1685 print "NOTE: Enter 'c' at the",
1685 print "NOTE: Enter 'c' at the",
1686 print "%s prompt to start your script." % deb.prompt
1686 print "%s prompt to start your script." % deb.prompt
1687 try:
1687 try:
1688 deb.run('execfile("%s")' % filename, prog_ns)
1688 deb.run('execfile("%s")' % filename, prog_ns)
1689
1689
1690 except:
1690 except:
1691 etype, value, tb = sys.exc_info()
1691 etype, value, tb = sys.exc_info()
1692 # Skip three frames in the traceback: the %run one,
1692 # Skip three frames in the traceback: the %run one,
1693 # one inside bdb.py, and the command-line typed by the
1693 # one inside bdb.py, and the command-line typed by the
1694 # user (run by exec in pdb itself).
1694 # user (run by exec in pdb itself).
1695 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1695 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1696 else:
1696 else:
1697 if runner is None:
1697 if runner is None:
1698 runner = self.shell.safe_execfile
1698 runner = self.shell.safe_execfile
1699 if 't' in opts:
1699 if 't' in opts:
1700 # timed execution
1700 # timed execution
1701 try:
1701 try:
1702 nruns = int(opts['N'][0])
1702 nruns = int(opts['N'][0])
1703 if nruns < 1:
1703 if nruns < 1:
1704 error('Number of runs must be >=1')
1704 error('Number of runs must be >=1')
1705 return
1705 return
1706 except (KeyError):
1706 except (KeyError):
1707 nruns = 1
1707 nruns = 1
1708 twall0 = time.time()
1708 twall0 = time.time()
1709 if nruns == 1:
1709 if nruns == 1:
1710 t0 = clock2()
1710 t0 = clock2()
1711 runner(filename, prog_ns, prog_ns,
1711 runner(filename, prog_ns, prog_ns,
1712 exit_ignore=exit_ignore)
1712 exit_ignore=exit_ignore)
1713 t1 = clock2()
1713 t1 = clock2()
1714 t_usr = t1[0] - t0[0]
1714 t_usr = t1[0] - t0[0]
1715 t_sys = t1[1] - t0[1]
1715 t_sys = t1[1] - t0[1]
1716 print "\nIPython CPU timings (estimated):"
1716 print "\nIPython CPU timings (estimated):"
1717 print " User : %10.2f s." % t_usr
1717 print " User : %10.2f s." % t_usr
1718 print " System : %10.2f s." % t_sys
1718 print " System : %10.2f s." % t_sys
1719 else:
1719 else:
1720 runs = range(nruns)
1720 runs = range(nruns)
1721 t0 = clock2()
1721 t0 = clock2()
1722 for nr in runs:
1722 for nr in runs:
1723 runner(filename, prog_ns, prog_ns,
1723 runner(filename, prog_ns, prog_ns,
1724 exit_ignore=exit_ignore)
1724 exit_ignore=exit_ignore)
1725 t1 = clock2()
1725 t1 = clock2()
1726 t_usr = t1[0] - t0[0]
1726 t_usr = t1[0] - t0[0]
1727 t_sys = t1[1] - t0[1]
1727 t_sys = t1[1] - t0[1]
1728 print "\nIPython CPU timings (estimated):"
1728 print "\nIPython CPU timings (estimated):"
1729 print "Total runs performed:", nruns
1729 print "Total runs performed:", nruns
1730 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1730 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1731 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1731 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1732 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1732 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1733 twall1 = time.time()
1733 twall1 = time.time()
1734 print "Wall time: %10.2f s." % (twall1 - twall0)
1734 print "Wall time: %10.2f s." % (twall1 - twall0)
1735
1735
1736 else:
1736 else:
1737 # regular execution
1737 # regular execution
1738 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1738 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1739
1739
1740 if 'i' in opts:
1740 if 'i' in opts:
1741 self.shell.user_ns['__name__'] = __name__save
1741 self.shell.user_ns['__name__'] = __name__save
1742 else:
1742 else:
1743 # The shell MUST hold a reference to prog_ns so after %run
1743 # The shell MUST hold a reference to prog_ns so after %run
1744 # exits, the python deletion mechanism doesn't zero it out
1744 # exits, the python deletion mechanism doesn't zero it out
1745 # (leaving dangling references).
1745 # (leaving dangling references).
1746 self.shell.cache_main_mod(prog_ns, filename)
1746 self.shell.cache_main_mod(prog_ns, filename)
1747 # update IPython interactive namespace
1747 # update IPython interactive namespace
1748
1748
1749 # Some forms of read errors on the file may mean the
1749 # Some forms of read errors on the file may mean the
1750 # __name__ key was never set; using pop we don't have to
1750 # __name__ key was never set; using pop we don't have to
1751 # worry about a possible KeyError.
1751 # worry about a possible KeyError.
1752 prog_ns.pop('__name__', None)
1752 prog_ns.pop('__name__', None)
1753
1753
1754 self.shell.user_ns.update(prog_ns)
1754 self.shell.user_ns.update(prog_ns)
1755 finally:
1755 finally:
1756 # It's a bit of a mystery why, but __builtins__ can change from
1756 # It's a bit of a mystery why, but __builtins__ can change from
1757 # being a module to becoming a dict missing some key data after
1757 # being a module to becoming a dict missing some key data after
1758 # %run. As best I can see, this is NOT something IPython is doing
1758 # %run. As best I can see, this is NOT something IPython is doing
1759 # at all, and similar problems have been reported before:
1759 # at all, and similar problems have been reported before:
1760 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1760 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1761 # Since this seems to be done by the interpreter itself, the best
1761 # Since this seems to be done by the interpreter itself, the best
1762 # we can do is to at least restore __builtins__ for the user on
1762 # we can do is to at least restore __builtins__ for the user on
1763 # exit.
1763 # exit.
1764 self.shell.user_ns['__builtins__'] = builtin_mod
1764 self.shell.user_ns['__builtins__'] = builtin_mod
1765
1765
1766 # Ensure key global structures are restored
1766 # Ensure key global structures are restored
1767 sys.argv = save_argv
1767 sys.argv = save_argv
1768 if restore_main:
1768 if restore_main:
1769 sys.modules['__main__'] = restore_main
1769 sys.modules['__main__'] = restore_main
1770 else:
1770 else:
1771 # Remove from sys.modules the reference to main_mod we'd
1771 # Remove from sys.modules the reference to main_mod we'd
1772 # added. Otherwise it will trap references to objects
1772 # added. Otherwise it will trap references to objects
1773 # contained therein.
1773 # contained therein.
1774 del sys.modules[main_mod_name]
1774 del sys.modules[main_mod_name]
1775
1775
1776 return stats
1776 return stats
1777
1777
1778 @skip_doctest
1778 @skip_doctest
1779 def magic_timeit(self, parameter_s =''):
1779 def magic_timeit(self, parameter_s =''):
1780 """Time execution of a Python statement or expression
1780 """Time execution of a Python statement or expression
1781
1781
1782 Usage:\\
1782 Usage:\\
1783 %timeit [-n<N> -r<R> [-t|-c]] statement
1783 %timeit [-n<N> -r<R> [-t|-c]] statement
1784
1784
1785 Time execution of a Python statement or expression using the timeit
1785 Time execution of a Python statement or expression using the timeit
1786 module.
1786 module.
1787
1787
1788 Options:
1788 Options:
1789 -n<N>: execute the given statement <N> times in a loop. If this value
1789 -n<N>: execute the given statement <N> times in a loop. If this value
1790 is not given, a fitting value is chosen.
1790 is not given, a fitting value is chosen.
1791
1791
1792 -r<R>: repeat the loop iteration <R> times and take the best result.
1792 -r<R>: repeat the loop iteration <R> times and take the best result.
1793 Default: 3
1793 Default: 3
1794
1794
1795 -t: use time.time to measure the time, which is the default on Unix.
1795 -t: use time.time to measure the time, which is the default on Unix.
1796 This function measures wall time.
1796 This function measures wall time.
1797
1797
1798 -c: use time.clock to measure the time, which is the default on
1798 -c: use time.clock to measure the time, which is the default on
1799 Windows and measures wall time. On Unix, resource.getrusage is used
1799 Windows and measures wall time. On Unix, resource.getrusage is used
1800 instead and returns the CPU user time.
1800 instead and returns the CPU user time.
1801
1801
1802 -p<P>: use a precision of <P> digits to display the timing result.
1802 -p<P>: use a precision of <P> digits to display the timing result.
1803 Default: 3
1803 Default: 3
1804
1804
1805
1805
1806 Examples:
1806 Examples:
1807
1807
1808 In [1]: %timeit pass
1808 In [1]: %timeit pass
1809 10000000 loops, best of 3: 53.3 ns per loop
1809 10000000 loops, best of 3: 53.3 ns per loop
1810
1810
1811 In [2]: u = None
1811 In [2]: u = None
1812
1812
1813 In [3]: %timeit u is None
1813 In [3]: %timeit u is None
1814 10000000 loops, best of 3: 184 ns per loop
1814 10000000 loops, best of 3: 184 ns per loop
1815
1815
1816 In [4]: %timeit -r 4 u == None
1816 In [4]: %timeit -r 4 u == None
1817 1000000 loops, best of 4: 242 ns per loop
1817 1000000 loops, best of 4: 242 ns per loop
1818
1818
1819 In [5]: import time
1819 In [5]: import time
1820
1820
1821 In [6]: %timeit -n1 time.sleep(2)
1821 In [6]: %timeit -n1 time.sleep(2)
1822 1 loops, best of 3: 2 s per loop
1822 1 loops, best of 3: 2 s per loop
1823
1823
1824
1824
1825 The times reported by %timeit will be slightly higher than those
1825 The times reported by %timeit will be slightly higher than those
1826 reported by the timeit.py script when variables are accessed. This is
1826 reported by the timeit.py script when variables are accessed. This is
1827 due to the fact that %timeit executes the statement in the namespace
1827 due to the fact that %timeit executes the statement in the namespace
1828 of the shell, compared with timeit.py, which uses a single setup
1828 of the shell, compared with timeit.py, which uses a single setup
1829 statement to import function or create variables. Generally, the bias
1829 statement to import function or create variables. Generally, the bias
1830 does not matter as long as results from timeit.py are not mixed with
1830 does not matter as long as results from timeit.py are not mixed with
1831 those from %timeit."""
1831 those from %timeit."""
1832
1832
1833 import timeit
1833 import timeit
1834 import math
1834 import math
1835
1835
1836 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1836 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1837 # certain terminals. Until we figure out a robust way of
1837 # certain terminals. Until we figure out a robust way of
1838 # auto-detecting if the terminal can deal with it, use plain 'us' for
1838 # auto-detecting if the terminal can deal with it, use plain 'us' for
1839 # microseconds. I am really NOT happy about disabling the proper
1839 # microseconds. I am really NOT happy about disabling the proper
1840 # 'micro' prefix, but crashing is worse... If anyone knows what the
1840 # 'micro' prefix, but crashing is worse... If anyone knows what the
1841 # right solution for this is, I'm all ears...
1841 # right solution for this is, I'm all ears...
1842 #
1842 #
1843 # Note: using
1843 # Note: using
1844 #
1844 #
1845 # s = u'\xb5'
1845 # s = u'\xb5'
1846 # s.encode(sys.getdefaultencoding())
1846 # s.encode(sys.getdefaultencoding())
1847 #
1847 #
1848 # is not sufficient, as I've seen terminals where that fails but
1848 # is not sufficient, as I've seen terminals where that fails but
1849 # print s
1849 # print s
1850 #
1850 #
1851 # succeeds
1851 # succeeds
1852 #
1852 #
1853 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1853 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1854
1854
1855 #units = [u"s", u"ms",u'\xb5',"ns"]
1855 #units = [u"s", u"ms",u'\xb5',"ns"]
1856 units = [u"s", u"ms",u'us',"ns"]
1856 units = [u"s", u"ms",u'us',"ns"]
1857
1857
1858 scaling = [1, 1e3, 1e6, 1e9]
1858 scaling = [1, 1e3, 1e6, 1e9]
1859
1859
1860 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1860 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1861 posix=False)
1861 posix=False)
1862 if stmt == "":
1862 if stmt == "":
1863 return
1863 return
1864 timefunc = timeit.default_timer
1864 timefunc = timeit.default_timer
1865 number = int(getattr(opts, "n", 0))
1865 number = int(getattr(opts, "n", 0))
1866 repeat = int(getattr(opts, "r", timeit.default_repeat))
1866 repeat = int(getattr(opts, "r", timeit.default_repeat))
1867 precision = int(getattr(opts, "p", 3))
1867 precision = int(getattr(opts, "p", 3))
1868 if hasattr(opts, "t"):
1868 if hasattr(opts, "t"):
1869 timefunc = time.time
1869 timefunc = time.time
1870 if hasattr(opts, "c"):
1870 if hasattr(opts, "c"):
1871 timefunc = clock
1871 timefunc = clock
1872
1872
1873 timer = timeit.Timer(timer=timefunc)
1873 timer = timeit.Timer(timer=timefunc)
1874 # this code has tight coupling to the inner workings of timeit.Timer,
1874 # this code has tight coupling to the inner workings of timeit.Timer,
1875 # but is there a better way to achieve that the code stmt has access
1875 # but is there a better way to achieve that the code stmt has access
1876 # to the shell namespace?
1876 # to the shell namespace?
1877
1877
1878 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1878 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1879 'setup': "pass"}
1879 'setup': "pass"}
1880 # Track compilation time so it can be reported if too long
1880 # Track compilation time so it can be reported if too long
1881 # Minimum time above which compilation time will be reported
1881 # Minimum time above which compilation time will be reported
1882 tc_min = 0.1
1882 tc_min = 0.1
1883
1883
1884 t0 = clock()
1884 t0 = clock()
1885 code = compile(src, "<magic-timeit>", "exec")
1885 code = compile(src, "<magic-timeit>", "exec")
1886 tc = clock()-t0
1886 tc = clock()-t0
1887
1887
1888 ns = {}
1888 ns = {}
1889 exec code in self.shell.user_ns, ns
1889 exec code in self.shell.user_ns, ns
1890 timer.inner = ns["inner"]
1890 timer.inner = ns["inner"]
1891
1891
1892 if number == 0:
1892 if number == 0:
1893 # determine number so that 0.2 <= total time < 2.0
1893 # determine number so that 0.2 <= total time < 2.0
1894 number = 1
1894 number = 1
1895 for i in range(1, 10):
1895 for i in range(1, 10):
1896 if timer.timeit(number) >= 0.2:
1896 if timer.timeit(number) >= 0.2:
1897 break
1897 break
1898 number *= 10
1898 number *= 10
1899
1899
1900 best = min(timer.repeat(repeat, number)) / number
1900 best = min(timer.repeat(repeat, number)) / number
1901
1901
1902 if best > 0.0 and best < 1000.0:
1902 if best > 0.0 and best < 1000.0:
1903 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1903 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1904 elif best >= 1000.0:
1904 elif best >= 1000.0:
1905 order = 0
1905 order = 0
1906 else:
1906 else:
1907 order = 3
1907 order = 3
1908 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1908 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1909 precision,
1909 precision,
1910 best * scaling[order],
1910 best * scaling[order],
1911 units[order])
1911 units[order])
1912 if tc > tc_min:
1912 if tc > tc_min:
1913 print "Compiler time: %.2f s" % tc
1913 print "Compiler time: %.2f s" % tc
1914
1914
1915 @skip_doctest
1915 @skip_doctest
1916 @needs_local_scope
1916 @needs_local_scope
1917 def magic_time(self,parameter_s = ''):
1917 def magic_time(self,parameter_s = ''):
1918 """Time execution of a Python statement or expression.
1918 """Time execution of a Python statement or expression.
1919
1919
1920 The CPU and wall clock times are printed, and the value of the
1920 The CPU and wall clock times are printed, and the value of the
1921 expression (if any) is returned. Note that under Win32, system time
1921 expression (if any) is returned. Note that under Win32, system time
1922 is always reported as 0, since it can not be measured.
1922 is always reported as 0, since it can not be measured.
1923
1923
1924 This function provides very basic timing functionality. In Python
1924 This function provides very basic timing functionality. In Python
1925 2.3, the timeit module offers more control and sophistication, so this
1925 2.3, the timeit module offers more control and sophistication, so this
1926 could be rewritten to use it (patches welcome).
1926 could be rewritten to use it (patches welcome).
1927
1927
1928 Some examples:
1928 Some examples:
1929
1929
1930 In [1]: time 2**128
1930 In [1]: time 2**128
1931 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1931 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1932 Wall time: 0.00
1932 Wall time: 0.00
1933 Out[1]: 340282366920938463463374607431768211456L
1933 Out[1]: 340282366920938463463374607431768211456L
1934
1934
1935 In [2]: n = 1000000
1935 In [2]: n = 1000000
1936
1936
1937 In [3]: time sum(range(n))
1937 In [3]: time sum(range(n))
1938 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1938 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1939 Wall time: 1.37
1939 Wall time: 1.37
1940 Out[3]: 499999500000L
1940 Out[3]: 499999500000L
1941
1941
1942 In [4]: time print 'hello world'
1942 In [4]: time print 'hello world'
1943 hello world
1943 hello world
1944 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1944 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1945 Wall time: 0.00
1945 Wall time: 0.00
1946
1946
1947 Note that the time needed by Python to compile the given expression
1947 Note that the time needed by Python to compile the given expression
1948 will be reported if it is more than 0.1s. In this example, the
1948 will be reported if it is more than 0.1s. In this example, the
1949 actual exponentiation is done by Python at compilation time, so while
1949 actual exponentiation is done by Python at compilation time, so while
1950 the expression can take a noticeable amount of time to compute, that
1950 the expression can take a noticeable amount of time to compute, that
1951 time is purely due to the compilation:
1951 time is purely due to the compilation:
1952
1952
1953 In [5]: time 3**9999;
1953 In [5]: time 3**9999;
1954 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1954 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1955 Wall time: 0.00 s
1955 Wall time: 0.00 s
1956
1956
1957 In [6]: time 3**999999;
1957 In [6]: time 3**999999;
1958 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1958 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1959 Wall time: 0.00 s
1959 Wall time: 0.00 s
1960 Compiler : 0.78 s
1960 Compiler : 0.78 s
1961 """
1961 """
1962
1962
1963 # fail immediately if the given expression can't be compiled
1963 # fail immediately if the given expression can't be compiled
1964
1964
1965 expr = self.shell.prefilter(parameter_s,False)
1965 expr = self.shell.prefilter(parameter_s,False)
1966
1966
1967 # Minimum time above which compilation time will be reported
1967 # Minimum time above which compilation time will be reported
1968 tc_min = 0.1
1968 tc_min = 0.1
1969
1969
1970 try:
1970 try:
1971 mode = 'eval'
1971 mode = 'eval'
1972 t0 = clock()
1972 t0 = clock()
1973 code = compile(expr,'<timed eval>',mode)
1973 code = compile(expr,'<timed eval>',mode)
1974 tc = clock()-t0
1974 tc = clock()-t0
1975 except SyntaxError:
1975 except SyntaxError:
1976 mode = 'exec'
1976 mode = 'exec'
1977 t0 = clock()
1977 t0 = clock()
1978 code = compile(expr,'<timed exec>',mode)
1978 code = compile(expr,'<timed exec>',mode)
1979 tc = clock()-t0
1979 tc = clock()-t0
1980 # skew measurement as little as possible
1980 # skew measurement as little as possible
1981 glob = self.shell.user_ns
1981 glob = self.shell.user_ns
1982 locs = self._magic_locals
1982 locs = self._magic_locals
1983 clk = clock2
1983 clk = clock2
1984 wtime = time.time
1984 wtime = time.time
1985 # time execution
1985 # time execution
1986 wall_st = wtime()
1986 wall_st = wtime()
1987 if mode=='eval':
1987 if mode=='eval':
1988 st = clk()
1988 st = clk()
1989 out = eval(code, glob, locs)
1989 out = eval(code, glob, locs)
1990 end = clk()
1990 end = clk()
1991 else:
1991 else:
1992 st = clk()
1992 st = clk()
1993 exec code in glob, locs
1993 exec code in glob, locs
1994 end = clk()
1994 end = clk()
1995 out = None
1995 out = None
1996 wall_end = wtime()
1996 wall_end = wtime()
1997 # Compute actual times and report
1997 # Compute actual times and report
1998 wall_time = wall_end-wall_st
1998 wall_time = wall_end-wall_st
1999 cpu_user = end[0]-st[0]
1999 cpu_user = end[0]-st[0]
2000 cpu_sys = end[1]-st[1]
2000 cpu_sys = end[1]-st[1]
2001 cpu_tot = cpu_user+cpu_sys
2001 cpu_tot = cpu_user+cpu_sys
2002 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2002 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2003 (cpu_user,cpu_sys,cpu_tot)
2003 (cpu_user,cpu_sys,cpu_tot)
2004 print "Wall time: %.2f s" % wall_time
2004 print "Wall time: %.2f s" % wall_time
2005 if tc > tc_min:
2005 if tc > tc_min:
2006 print "Compiler : %.2f s" % tc
2006 print "Compiler : %.2f s" % tc
2007 return out
2007 return out
2008
2008
2009 @skip_doctest
2009 @skip_doctest
2010 def magic_macro(self,parameter_s = ''):
2010 def magic_macro(self,parameter_s = ''):
2011 """Define a macro for future re-execution. It accepts ranges of history,
2011 """Define a macro for future re-execution. It accepts ranges of history,
2012 filenames or string objects.
2012 filenames or string objects.
2013
2013
2014 Usage:\\
2014 Usage:\\
2015 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2015 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2016
2016
2017 Options:
2017 Options:
2018
2018
2019 -r: use 'raw' input. By default, the 'processed' history is used,
2019 -r: use 'raw' input. By default, the 'processed' history is used,
2020 so that magics are loaded in their transformed version to valid
2020 so that magics are loaded in their transformed version to valid
2021 Python. If this option is given, the raw input as typed as the
2021 Python. If this option is given, the raw input as typed as the
2022 command line is used instead.
2022 command line is used instead.
2023
2023
2024 This will define a global variable called `name` which is a string
2024 This will define a global variable called `name` which is a string
2025 made of joining the slices and lines you specify (n1,n2,... numbers
2025 made of joining the slices and lines you specify (n1,n2,... numbers
2026 above) from your input history into a single string. This variable
2026 above) from your input history into a single string. This variable
2027 acts like an automatic function which re-executes those lines as if
2027 acts like an automatic function which re-executes those lines as if
2028 you had typed them. You just type 'name' at the prompt and the code
2028 you had typed them. You just type 'name' at the prompt and the code
2029 executes.
2029 executes.
2030
2030
2031 The syntax for indicating input ranges is described in %history.
2031 The syntax for indicating input ranges is described in %history.
2032
2032
2033 Note: as a 'hidden' feature, you can also use traditional python slice
2033 Note: as a 'hidden' feature, you can also use traditional python slice
2034 notation, where N:M means numbers N through M-1.
2034 notation, where N:M means numbers N through M-1.
2035
2035
2036 For example, if your history contains (%hist prints it):
2036 For example, if your history contains (%hist prints it):
2037
2037
2038 44: x=1
2038 44: x=1
2039 45: y=3
2039 45: y=3
2040 46: z=x+y
2040 46: z=x+y
2041 47: print x
2041 47: print x
2042 48: a=5
2042 48: a=5
2043 49: print 'x',x,'y',y
2043 49: print 'x',x,'y',y
2044
2044
2045 you can create a macro with lines 44 through 47 (included) and line 49
2045 you can create a macro with lines 44 through 47 (included) and line 49
2046 called my_macro with:
2046 called my_macro with:
2047
2047
2048 In [55]: %macro my_macro 44-47 49
2048 In [55]: %macro my_macro 44-47 49
2049
2049
2050 Now, typing `my_macro` (without quotes) will re-execute all this code
2050 Now, typing `my_macro` (without quotes) will re-execute all this code
2051 in one pass.
2051 in one pass.
2052
2052
2053 You don't need to give the line-numbers in order, and any given line
2053 You don't need to give the line-numbers in order, and any given line
2054 number can appear multiple times. You can assemble macros with any
2054 number can appear multiple times. You can assemble macros with any
2055 lines from your input history in any order.
2055 lines from your input history in any order.
2056
2056
2057 The macro is a simple object which holds its value in an attribute,
2057 The macro is a simple object which holds its value in an attribute,
2058 but IPython's display system checks for macros and executes them as
2058 but IPython's display system checks for macros and executes them as
2059 code instead of printing them when you type their name.
2059 code instead of printing them when you type their name.
2060
2060
2061 You can view a macro's contents by explicitly printing it with:
2061 You can view a macro's contents by explicitly printing it with:
2062
2062
2063 'print macro_name'.
2063 'print macro_name'.
2064
2064
2065 """
2065 """
2066 opts,args = self.parse_options(parameter_s,'r',mode='list')
2066 opts,args = self.parse_options(parameter_s,'r',mode='list')
2067 if not args: # List existing macros
2067 if not args: # List existing macros
2068 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2068 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2069 isinstance(v, Macro))
2069 isinstance(v, Macro))
2070 if len(args) == 1:
2070 if len(args) == 1:
2071 raise UsageError(
2071 raise UsageError(
2072 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2072 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2073 name, codefrom = args[0], " ".join(args[1:])
2073 name, codefrom = args[0], " ".join(args[1:])
2074
2074
2075 #print 'rng',ranges # dbg
2075 #print 'rng',ranges # dbg
2076 try:
2076 try:
2077 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2077 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2078 except (ValueError, TypeError) as e:
2078 except (ValueError, TypeError) as e:
2079 print e.args[0]
2079 print e.args[0]
2080 return
2080 return
2081 macro = Macro(lines)
2081 macro = Macro(lines)
2082 self.shell.define_macro(name, macro)
2082 self.shell.define_macro(name, macro)
2083 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2083 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2084 print '=== Macro contents: ==='
2084 print '=== Macro contents: ==='
2085 print macro,
2085 print macro,
2086
2086
2087 def magic_save(self,parameter_s = ''):
2087 def magic_save(self,parameter_s = ''):
2088 """Save a set of lines or a macro to a given filename.
2088 """Save a set of lines or a macro to a given filename.
2089
2089
2090 Usage:\\
2090 Usage:\\
2091 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2091 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2092
2092
2093 Options:
2093 Options:
2094
2094
2095 -r: use 'raw' input. By default, the 'processed' history is used,
2095 -r: use 'raw' input. By default, the 'processed' history is used,
2096 so that magics are loaded in their transformed version to valid
2096 so that magics are loaded in their transformed version to valid
2097 Python. If this option is given, the raw input as typed as the
2097 Python. If this option is given, the raw input as typed as the
2098 command line is used instead.
2098 command line is used instead.
2099
2099
2100 This function uses the same syntax as %history for input ranges,
2100 This function uses the same syntax as %history for input ranges,
2101 then saves the lines to the filename you specify.
2101 then saves the lines to the filename you specify.
2102
2102
2103 It adds a '.py' extension to the file if you don't do so yourself, and
2103 It adds a '.py' extension to the file if you don't do so yourself, and
2104 it asks for confirmation before overwriting existing files."""
2104 it asks for confirmation before overwriting existing files."""
2105
2105
2106 opts,args = self.parse_options(parameter_s,'r',mode='list')
2106 opts,args = self.parse_options(parameter_s,'r',mode='list')
2107 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2107 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2108 if not fname.endswith('.py'):
2108 if not fname.endswith('.py'):
2109 fname += '.py'
2109 fname += '.py'
2110 if os.path.isfile(fname):
2110 if os.path.isfile(fname):
2111 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2111 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2112 if ans.lower() not in ['y','yes']:
2112 if ans.lower() not in ['y','yes']:
2113 print 'Operation cancelled.'
2113 print 'Operation cancelled.'
2114 return
2114 return
2115 try:
2115 try:
2116 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2116 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2117 except (TypeError, ValueError) as e:
2117 except (TypeError, ValueError) as e:
2118 print e.args[0]
2118 print e.args[0]
2119 return
2119 return
2120 with py3compat.open(fname,'w', encoding="utf-8") as f:
2120 with py3compat.open(fname,'w', encoding="utf-8") as f:
2121 f.write(u"# coding: utf-8\n")
2121 f.write(u"# coding: utf-8\n")
2122 f.write(py3compat.cast_unicode(cmds))
2122 f.write(py3compat.cast_unicode(cmds))
2123 print 'The following commands were written to file `%s`:' % fname
2123 print 'The following commands were written to file `%s`:' % fname
2124 print cmds
2124 print cmds
2125
2125
2126 def magic_pastebin(self, parameter_s = ''):
2126 def magic_pastebin(self, parameter_s = ''):
2127 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2127 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2128 try:
2128 try:
2129 code = self.shell.find_user_code(parameter_s)
2129 code = self.shell.find_user_code(parameter_s)
2130 except (ValueError, TypeError) as e:
2130 except (ValueError, TypeError) as e:
2131 print e.args[0]
2131 print e.args[0]
2132 return
2132 return
2133 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2133 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2134 id = pbserver.pastes.newPaste("python", code)
2134 id = pbserver.pastes.newPaste("python", code)
2135 return "http://paste.pocoo.org/show/" + id
2135 return "http://paste.pocoo.org/show/" + id
2136
2136
2137 def magic_loadpy(self, arg_s):
2137 def magic_loadpy(self, arg_s):
2138 """Load a .py python script into the GUI console.
2138 """Load a .py python script into the GUI console.
2139
2139
2140 This magic command can either take a local filename or a url::
2140 This magic command can either take a local filename or a url::
2141
2141
2142 %loadpy myscript.py
2142 %loadpy myscript.py
2143 %loadpy http://www.example.com/myscript.py
2143 %loadpy http://www.example.com/myscript.py
2144 """
2144 """
2145 arg_s = unquote_filename(arg_s)
2145 arg_s = unquote_filename(arg_s)
2146 if not arg_s.endswith('.py'):
2146 if not arg_s.endswith('.py'):
2147 raise ValueError('%%load only works with .py files: %s' % arg_s)
2147 raise ValueError('%%load only works with .py files: %s' % arg_s)
2148 if arg_s.startswith('http'):
2148 if arg_s.startswith('http'):
2149 import urllib2
2149 import urllib2
2150 response = urllib2.urlopen(arg_s)
2150 response = urllib2.urlopen(arg_s)
2151 content = response.read()
2151 content = response.read()
2152 else:
2152 else:
2153 with open(arg_s) as f:
2153 with open(arg_s) as f:
2154 content = f.read()
2154 content = f.read()
2155 self.set_next_input(content)
2155 self.set_next_input(content)
2156
2156
2157 def _find_edit_target(self, args, opts, last_call):
2157 def _find_edit_target(self, args, opts, last_call):
2158 """Utility method used by magic_edit to find what to edit."""
2158 """Utility method used by magic_edit to find what to edit."""
2159
2159
2160 def make_filename(arg):
2160 def make_filename(arg):
2161 "Make a filename from the given args"
2161 "Make a filename from the given args"
2162 arg = unquote_filename(arg)
2162 arg = unquote_filename(arg)
2163 try:
2163 try:
2164 filename = get_py_filename(arg)
2164 filename = get_py_filename(arg)
2165 except IOError:
2165 except IOError:
2166 # If it ends with .py but doesn't already exist, assume we want
2166 # If it ends with .py but doesn't already exist, assume we want
2167 # a new file.
2167 # a new file.
2168 if arg.endswith('.py'):
2168 if arg.endswith('.py'):
2169 filename = arg
2169 filename = arg
2170 else:
2170 else:
2171 filename = None
2171 filename = None
2172 return filename
2172 return filename
2173
2173
2174 # Set a few locals from the options for convenience:
2174 # Set a few locals from the options for convenience:
2175 opts_prev = 'p' in opts
2175 opts_prev = 'p' in opts
2176 opts_raw = 'r' in opts
2176 opts_raw = 'r' in opts
2177
2177
2178 # custom exceptions
2178 # custom exceptions
2179 class DataIsObject(Exception): pass
2179 class DataIsObject(Exception): pass
2180
2180
2181 # Default line number value
2181 # Default line number value
2182 lineno = opts.get('n',None)
2182 lineno = opts.get('n',None)
2183
2183
2184 if opts_prev:
2184 if opts_prev:
2185 args = '_%s' % last_call[0]
2185 args = '_%s' % last_call[0]
2186 if not self.shell.user_ns.has_key(args):
2186 if not self.shell.user_ns.has_key(args):
2187 args = last_call[1]
2187 args = last_call[1]
2188
2188
2189 # use last_call to remember the state of the previous call, but don't
2189 # use last_call to remember the state of the previous call, but don't
2190 # let it be clobbered by successive '-p' calls.
2190 # let it be clobbered by successive '-p' calls.
2191 try:
2191 try:
2192 last_call[0] = self.shell.displayhook.prompt_count
2192 last_call[0] = self.shell.displayhook.prompt_count
2193 if not opts_prev:
2193 if not opts_prev:
2194 last_call[1] = parameter_s
2194 last_call[1] = parameter_s
2195 except:
2195 except:
2196 pass
2196 pass
2197
2197
2198 # by default this is done with temp files, except when the given
2198 # by default this is done with temp files, except when the given
2199 # arg is a filename
2199 # arg is a filename
2200 use_temp = True
2200 use_temp = True
2201
2201
2202 data = ''
2202 data = ''
2203
2203
2204 # First, see if the arguments should be a filename.
2204 # First, see if the arguments should be a filename.
2205 filename = make_filename(args)
2205 filename = make_filename(args)
2206 if filename:
2206 if filename:
2207 use_temp = False
2207 use_temp = False
2208 elif args:
2208 elif args:
2209 # Mode where user specifies ranges of lines, like in %macro.
2209 # Mode where user specifies ranges of lines, like in %macro.
2210 data = self.extract_input_lines(args, opts_raw)
2210 data = self.extract_input_lines(args, opts_raw)
2211 if not data:
2211 if not data:
2212 try:
2212 try:
2213 # Load the parameter given as a variable. If not a string,
2213 # Load the parameter given as a variable. If not a string,
2214 # process it as an object instead (below)
2214 # process it as an object instead (below)
2215
2215
2216 #print '*** args',args,'type',type(args) # dbg
2216 #print '*** args',args,'type',type(args) # dbg
2217 data = eval(args, self.shell.user_ns)
2217 data = eval(args, self.shell.user_ns)
2218 if not isinstance(data, basestring):
2218 if not isinstance(data, basestring):
2219 raise DataIsObject
2219 raise DataIsObject
2220
2220
2221 except (NameError,SyntaxError):
2221 except (NameError,SyntaxError):
2222 # given argument is not a variable, try as a filename
2222 # given argument is not a variable, try as a filename
2223 filename = make_filename(args)
2223 filename = make_filename(args)
2224 if filename is None:
2224 if filename is None:
2225 warn("Argument given (%s) can't be found as a variable "
2225 warn("Argument given (%s) can't be found as a variable "
2226 "or as a filename." % args)
2226 "or as a filename." % args)
2227 return
2227 return
2228 use_temp = False
2228 use_temp = False
2229
2229
2230 except DataIsObject:
2230 except DataIsObject:
2231 # macros have a special edit function
2231 # macros have a special edit function
2232 if isinstance(data, Macro):
2232 if isinstance(data, Macro):
2233 raise MacroToEdit(data)
2233 raise MacroToEdit(data)
2234
2234
2235 # For objects, try to edit the file where they are defined
2235 # For objects, try to edit the file where they are defined
2236 try:
2236 try:
2237 filename = inspect.getabsfile(data)
2237 filename = inspect.getabsfile(data)
2238 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2238 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2239 # class created by %edit? Try to find source
2239 # class created by %edit? Try to find source
2240 # by looking for method definitions instead, the
2240 # by looking for method definitions instead, the
2241 # __module__ in those classes is FakeModule.
2241 # __module__ in those classes is FakeModule.
2242 attrs = [getattr(data, aname) for aname in dir(data)]
2242 attrs = [getattr(data, aname) for aname in dir(data)]
2243 for attr in attrs:
2243 for attr in attrs:
2244 if not inspect.ismethod(attr):
2244 if not inspect.ismethod(attr):
2245 continue
2245 continue
2246 filename = inspect.getabsfile(attr)
2246 filename = inspect.getabsfile(attr)
2247 if filename and 'fakemodule' not in filename.lower():
2247 if filename and 'fakemodule' not in filename.lower():
2248 # change the attribute to be the edit target instead
2248 # change the attribute to be the edit target instead
2249 data = attr
2249 data = attr
2250 break
2250 break
2251
2251
2252 datafile = 1
2252 datafile = 1
2253 except TypeError:
2253 except TypeError:
2254 filename = make_filename(args)
2254 filename = make_filename(args)
2255 datafile = 1
2255 datafile = 1
2256 warn('Could not find file where `%s` is defined.\n'
2256 warn('Could not find file where `%s` is defined.\n'
2257 'Opening a file named `%s`' % (args,filename))
2257 'Opening a file named `%s`' % (args,filename))
2258 # Now, make sure we can actually read the source (if it was in
2258 # Now, make sure we can actually read the source (if it was in
2259 # a temp file it's gone by now).
2259 # a temp file it's gone by now).
2260 if datafile:
2260 if datafile:
2261 try:
2261 try:
2262 if lineno is None:
2262 if lineno is None:
2263 lineno = inspect.getsourcelines(data)[1]
2263 lineno = inspect.getsourcelines(data)[1]
2264 except IOError:
2264 except IOError:
2265 filename = make_filename(args)
2265 filename = make_filename(args)
2266 if filename is None:
2266 if filename is None:
2267 warn('The file `%s` where `%s` was defined cannot '
2267 warn('The file `%s` where `%s` was defined cannot '
2268 'be read.' % (filename,data))
2268 'be read.' % (filename,data))
2269 return
2269 return
2270 use_temp = False
2270 use_temp = False
2271
2271
2272 if use_temp:
2272 if use_temp:
2273 filename = self.shell.mktempfile(data)
2273 filename = self.shell.mktempfile(data)
2274 print 'IPython will make a temporary file named:',filename
2274 print 'IPython will make a temporary file named:',filename
2275
2275
2276 return filename, lineno, use_temp
2276 return filename, lineno, use_temp
2277
2277
2278 def _edit_macro(self,mname,macro):
2278 def _edit_macro(self,mname,macro):
2279 """open an editor with the macro data in a file"""
2279 """open an editor with the macro data in a file"""
2280 filename = self.shell.mktempfile(macro.value)
2280 filename = self.shell.mktempfile(macro.value)
2281 self.shell.hooks.editor(filename)
2281 self.shell.hooks.editor(filename)
2282
2282
2283 # and make a new macro object, to replace the old one
2283 # and make a new macro object, to replace the old one
2284 mfile = open(filename)
2284 mfile = open(filename)
2285 mvalue = mfile.read()
2285 mvalue = mfile.read()
2286 mfile.close()
2286 mfile.close()
2287 self.shell.user_ns[mname] = Macro(mvalue)
2287 self.shell.user_ns[mname] = Macro(mvalue)
2288
2288
2289 def magic_ed(self,parameter_s=''):
2289 def magic_ed(self,parameter_s=''):
2290 """Alias to %edit."""
2290 """Alias to %edit."""
2291 return self.magic_edit(parameter_s)
2291 return self.magic_edit(parameter_s)
2292
2292
2293 @skip_doctest
2293 @skip_doctest
2294 def magic_edit(self,parameter_s='',last_call=['','']):
2294 def magic_edit(self,parameter_s='',last_call=['','']):
2295 """Bring up an editor and execute the resulting code.
2295 """Bring up an editor and execute the resulting code.
2296
2296
2297 Usage:
2297 Usage:
2298 %edit [options] [args]
2298 %edit [options] [args]
2299
2299
2300 %edit runs IPython's editor hook. The default version of this hook is
2300 %edit runs IPython's editor hook. The default version of this hook is
2301 set to call the editor specified by your $EDITOR environment variable.
2301 set to call the editor specified by your $EDITOR environment variable.
2302 If this isn't found, it will default to vi under Linux/Unix and to
2302 If this isn't found, it will default to vi under Linux/Unix and to
2303 notepad under Windows. See the end of this docstring for how to change
2303 notepad under Windows. See the end of this docstring for how to change
2304 the editor hook.
2304 the editor hook.
2305
2305
2306 You can also set the value of this editor via the
2306 You can also set the value of this editor via the
2307 ``TerminalInteractiveShell.editor`` option in your configuration file.
2307 ``TerminalInteractiveShell.editor`` option in your configuration file.
2308 This is useful if you wish to use a different editor from your typical
2308 This is useful if you wish to use a different editor from your typical
2309 default with IPython (and for Windows users who typically don't set
2309 default with IPython (and for Windows users who typically don't set
2310 environment variables).
2310 environment variables).
2311
2311
2312 This command allows you to conveniently edit multi-line code right in
2312 This command allows you to conveniently edit multi-line code right in
2313 your IPython session.
2313 your IPython session.
2314
2314
2315 If called without arguments, %edit opens up an empty editor with a
2315 If called without arguments, %edit opens up an empty editor with a
2316 temporary file and will execute the contents of this file when you
2316 temporary file and will execute the contents of this file when you
2317 close it (don't forget to save it!).
2317 close it (don't forget to save it!).
2318
2318
2319
2319
2320 Options:
2320 Options:
2321
2321
2322 -n <number>: open the editor at a specified line number. By default,
2322 -n <number>: open the editor at a specified line number. By default,
2323 the IPython editor hook uses the unix syntax 'editor +N filename', but
2323 the IPython editor hook uses the unix syntax 'editor +N filename', but
2324 you can configure this by providing your own modified hook if your
2324 you can configure this by providing your own modified hook if your
2325 favorite editor supports line-number specifications with a different
2325 favorite editor supports line-number specifications with a different
2326 syntax.
2326 syntax.
2327
2327
2328 -p: this will call the editor with the same data as the previous time
2328 -p: this will call the editor with the same data as the previous time
2329 it was used, regardless of how long ago (in your current session) it
2329 it was used, regardless of how long ago (in your current session) it
2330 was.
2330 was.
2331
2331
2332 -r: use 'raw' input. This option only applies to input taken from the
2332 -r: use 'raw' input. This option only applies to input taken from the
2333 user's history. By default, the 'processed' history is used, so that
2333 user's history. By default, the 'processed' history is used, so that
2334 magics are loaded in their transformed version to valid Python. If
2334 magics are loaded in their transformed version to valid Python. If
2335 this option is given, the raw input as typed as the command line is
2335 this option is given, the raw input as typed as the command line is
2336 used instead. When you exit the editor, it will be executed by
2336 used instead. When you exit the editor, it will be executed by
2337 IPython's own processor.
2337 IPython's own processor.
2338
2338
2339 -x: do not execute the edited code immediately upon exit. This is
2339 -x: do not execute the edited code immediately upon exit. This is
2340 mainly useful if you are editing programs which need to be called with
2340 mainly useful if you are editing programs which need to be called with
2341 command line arguments, which you can then do using %run.
2341 command line arguments, which you can then do using %run.
2342
2342
2343
2343
2344 Arguments:
2344 Arguments:
2345
2345
2346 If arguments are given, the following possibilites exist:
2346 If arguments are given, the following possibilites exist:
2347
2347
2348 - If the argument is a filename, IPython will load that into the
2348 - If the argument is a filename, IPython will load that into the
2349 editor. It will execute its contents with execfile() when you exit,
2349 editor. It will execute its contents with execfile() when you exit,
2350 loading any code in the file into your interactive namespace.
2350 loading any code in the file into your interactive namespace.
2351
2351
2352 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2352 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2353 The syntax is the same as in the %history magic.
2353 The syntax is the same as in the %history magic.
2354
2354
2355 - If the argument is a string variable, its contents are loaded
2355 - If the argument is a string variable, its contents are loaded
2356 into the editor. You can thus edit any string which contains
2356 into the editor. You can thus edit any string which contains
2357 python code (including the result of previous edits).
2357 python code (including the result of previous edits).
2358
2358
2359 - If the argument is the name of an object (other than a string),
2359 - If the argument is the name of an object (other than a string),
2360 IPython will try to locate the file where it was defined and open the
2360 IPython will try to locate the file where it was defined and open the
2361 editor at the point where it is defined. You can use `%edit function`
2361 editor at the point where it is defined. You can use `%edit function`
2362 to load an editor exactly at the point where 'function' is defined,
2362 to load an editor exactly at the point where 'function' is defined,
2363 edit it and have the file be executed automatically.
2363 edit it and have the file be executed automatically.
2364
2364
2365 - If the object is a macro (see %macro for details), this opens up your
2365 - If the object is a macro (see %macro for details), this opens up your
2366 specified editor with a temporary file containing the macro's data.
2366 specified editor with a temporary file containing the macro's data.
2367 Upon exit, the macro is reloaded with the contents of the file.
2367 Upon exit, the macro is reloaded with the contents of the file.
2368
2368
2369 Note: opening at an exact line is only supported under Unix, and some
2369 Note: opening at an exact line is only supported under Unix, and some
2370 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2370 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2371 '+NUMBER' parameter necessary for this feature. Good editors like
2371 '+NUMBER' parameter necessary for this feature. Good editors like
2372 (X)Emacs, vi, jed, pico and joe all do.
2372 (X)Emacs, vi, jed, pico and joe all do.
2373
2373
2374 After executing your code, %edit will return as output the code you
2374 After executing your code, %edit will return as output the code you
2375 typed in the editor (except when it was an existing file). This way
2375 typed in the editor (except when it was an existing file). This way
2376 you can reload the code in further invocations of %edit as a variable,
2376 you can reload the code in further invocations of %edit as a variable,
2377 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2377 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2378 the output.
2378 the output.
2379
2379
2380 Note that %edit is also available through the alias %ed.
2380 Note that %edit is also available through the alias %ed.
2381
2381
2382 This is an example of creating a simple function inside the editor and
2382 This is an example of creating a simple function inside the editor and
2383 then modifying it. First, start up the editor:
2383 then modifying it. First, start up the editor:
2384
2384
2385 In [1]: ed
2385 In [1]: ed
2386 Editing... done. Executing edited code...
2386 Editing... done. Executing edited code...
2387 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2387 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2388
2388
2389 We can then call the function foo():
2389 We can then call the function foo():
2390
2390
2391 In [2]: foo()
2391 In [2]: foo()
2392 foo() was defined in an editing session
2392 foo() was defined in an editing session
2393
2393
2394 Now we edit foo. IPython automatically loads the editor with the
2394 Now we edit foo. IPython automatically loads the editor with the
2395 (temporary) file where foo() was previously defined:
2395 (temporary) file where foo() was previously defined:
2396
2396
2397 In [3]: ed foo
2397 In [3]: ed foo
2398 Editing... done. Executing edited code...
2398 Editing... done. Executing edited code...
2399
2399
2400 And if we call foo() again we get the modified version:
2400 And if we call foo() again we get the modified version:
2401
2401
2402 In [4]: foo()
2402 In [4]: foo()
2403 foo() has now been changed!
2403 foo() has now been changed!
2404
2404
2405 Here is an example of how to edit a code snippet successive
2405 Here is an example of how to edit a code snippet successive
2406 times. First we call the editor:
2406 times. First we call the editor:
2407
2407
2408 In [5]: ed
2408 In [5]: ed
2409 Editing... done. Executing edited code...
2409 Editing... done. Executing edited code...
2410 hello
2410 hello
2411 Out[5]: "print 'hello'n"
2411 Out[5]: "print 'hello'n"
2412
2412
2413 Now we call it again with the previous output (stored in _):
2413 Now we call it again with the previous output (stored in _):
2414
2414
2415 In [6]: ed _
2415 In [6]: ed _
2416 Editing... done. Executing edited code...
2416 Editing... done. Executing edited code...
2417 hello world
2417 hello world
2418 Out[6]: "print 'hello world'n"
2418 Out[6]: "print 'hello world'n"
2419
2419
2420 Now we call it with the output #8 (stored in _8, also as Out[8]):
2420 Now we call it with the output #8 (stored in _8, also as Out[8]):
2421
2421
2422 In [7]: ed _8
2422 In [7]: ed _8
2423 Editing... done. Executing edited code...
2423 Editing... done. Executing edited code...
2424 hello again
2424 hello again
2425 Out[7]: "print 'hello again'n"
2425 Out[7]: "print 'hello again'n"
2426
2426
2427
2427
2428 Changing the default editor hook:
2428 Changing the default editor hook:
2429
2429
2430 If you wish to write your own editor hook, you can put it in a
2430 If you wish to write your own editor hook, you can put it in a
2431 configuration file which you load at startup time. The default hook
2431 configuration file which you load at startup time. The default hook
2432 is defined in the IPython.core.hooks module, and you can use that as a
2432 is defined in the IPython.core.hooks module, and you can use that as a
2433 starting example for further modifications. That file also has
2433 starting example for further modifications. That file also has
2434 general instructions on how to set a new hook for use once you've
2434 general instructions on how to set a new hook for use once you've
2435 defined it."""
2435 defined it."""
2436 opts,args = self.parse_options(parameter_s,'prxn:')
2436 opts,args = self.parse_options(parameter_s,'prxn:')
2437
2437
2438 try:
2438 try:
2439 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2439 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2440 except MacroToEdit as e:
2440 except MacroToEdit as e:
2441 self._edit_macro(args, e.args[0])
2441 self._edit_macro(args, e.args[0])
2442 return
2442 return
2443
2443
2444 # do actual editing here
2444 # do actual editing here
2445 print 'Editing...',
2445 print 'Editing...',
2446 sys.stdout.flush()
2446 sys.stdout.flush()
2447 try:
2447 try:
2448 # Quote filenames that may have spaces in them
2448 # Quote filenames that may have spaces in them
2449 if ' ' in filename:
2449 if ' ' in filename:
2450 filename = "'%s'" % filename
2450 filename = "'%s'" % filename
2451 self.shell.hooks.editor(filename,lineno)
2451 self.shell.hooks.editor(filename,lineno)
2452 except TryNext:
2452 except TryNext:
2453 warn('Could not open editor')
2453 warn('Could not open editor')
2454 return
2454 return
2455
2455
2456 # XXX TODO: should this be generalized for all string vars?
2456 # XXX TODO: should this be generalized for all string vars?
2457 # For now, this is special-cased to blocks created by cpaste
2457 # For now, this is special-cased to blocks created by cpaste
2458 if args.strip() == 'pasted_block':
2458 if args.strip() == 'pasted_block':
2459 self.shell.user_ns['pasted_block'] = file_read(filename)
2459 self.shell.user_ns['pasted_block'] = file_read(filename)
2460
2460
2461 if 'x' in opts: # -x prevents actual execution
2461 if 'x' in opts: # -x prevents actual execution
2462 print
2462 print
2463 else:
2463 else:
2464 print 'done. Executing edited code...'
2464 print 'done. Executing edited code...'
2465 if 'r' in opts: # Untranslated IPython code
2465 if 'r' in opts: # Untranslated IPython code
2466 self.shell.run_cell(file_read(filename),
2466 self.shell.run_cell(file_read(filename),
2467 store_history=False)
2467 store_history=False)
2468 else:
2468 else:
2469 self.shell.safe_execfile(filename,self.shell.user_ns,
2469 self.shell.safe_execfile(filename,self.shell.user_ns,
2470 self.shell.user_ns)
2470 self.shell.user_ns)
2471
2471
2472 if is_temp:
2472 if is_temp:
2473 try:
2473 try:
2474 return open(filename).read()
2474 return open(filename).read()
2475 except IOError,msg:
2475 except IOError,msg:
2476 if msg.filename == filename:
2476 if msg.filename == filename:
2477 warn('File not found. Did you forget to save?')
2477 warn('File not found. Did you forget to save?')
2478 return
2478 return
2479 else:
2479 else:
2480 self.shell.showtraceback()
2480 self.shell.showtraceback()
2481
2481
2482 def magic_xmode(self,parameter_s = ''):
2482 def magic_xmode(self,parameter_s = ''):
2483 """Switch modes for the exception handlers.
2483 """Switch modes for the exception handlers.
2484
2484
2485 Valid modes: Plain, Context and Verbose.
2485 Valid modes: Plain, Context and Verbose.
2486
2486
2487 If called without arguments, acts as a toggle."""
2487 If called without arguments, acts as a toggle."""
2488
2488
2489 def xmode_switch_err(name):
2489 def xmode_switch_err(name):
2490 warn('Error changing %s exception modes.\n%s' %
2490 warn('Error changing %s exception modes.\n%s' %
2491 (name,sys.exc_info()[1]))
2491 (name,sys.exc_info()[1]))
2492
2492
2493 shell = self.shell
2493 shell = self.shell
2494 new_mode = parameter_s.strip().capitalize()
2494 new_mode = parameter_s.strip().capitalize()
2495 try:
2495 try:
2496 shell.InteractiveTB.set_mode(mode=new_mode)
2496 shell.InteractiveTB.set_mode(mode=new_mode)
2497 print 'Exception reporting mode:',shell.InteractiveTB.mode
2497 print 'Exception reporting mode:',shell.InteractiveTB.mode
2498 except:
2498 except:
2499 xmode_switch_err('user')
2499 xmode_switch_err('user')
2500
2500
2501 def magic_colors(self,parameter_s = ''):
2501 def magic_colors(self,parameter_s = ''):
2502 """Switch color scheme for prompts, info system and exception handlers.
2502 """Switch color scheme for prompts, info system and exception handlers.
2503
2503
2504 Currently implemented schemes: NoColor, Linux, LightBG.
2504 Currently implemented schemes: NoColor, Linux, LightBG.
2505
2505
2506 Color scheme names are not case-sensitive.
2506 Color scheme names are not case-sensitive.
2507
2507
2508 Examples
2508 Examples
2509 --------
2509 --------
2510 To get a plain black and white terminal::
2510 To get a plain black and white terminal::
2511
2511
2512 %colors nocolor
2512 %colors nocolor
2513 """
2513 """
2514
2514
2515 def color_switch_err(name):
2515 def color_switch_err(name):
2516 warn('Error changing %s color schemes.\n%s' %
2516 warn('Error changing %s color schemes.\n%s' %
2517 (name,sys.exc_info()[1]))
2517 (name,sys.exc_info()[1]))
2518
2518
2519
2519
2520 new_scheme = parameter_s.strip()
2520 new_scheme = parameter_s.strip()
2521 if not new_scheme:
2521 if not new_scheme:
2522 raise UsageError(
2522 raise UsageError(
2523 "%colors: you must specify a color scheme. See '%colors?'")
2523 "%colors: you must specify a color scheme. See '%colors?'")
2524 return
2524 return
2525 # local shortcut
2525 # local shortcut
2526 shell = self.shell
2526 shell = self.shell
2527
2527
2528 import IPython.utils.rlineimpl as readline
2528 import IPython.utils.rlineimpl as readline
2529
2529
2530 if not shell.colors_force and \
2530 if not shell.colors_force and \
2531 not readline.have_readline and sys.platform == "win32":
2531 not readline.have_readline and sys.platform == "win32":
2532 msg = """\
2532 msg = """\
2533 Proper color support under MS Windows requires the pyreadline library.
2533 Proper color support under MS Windows requires the pyreadline library.
2534 You can find it at:
2534 You can find it at:
2535 http://ipython.org/pyreadline.html
2535 http://ipython.org/pyreadline.html
2536 Gary's readline needs the ctypes module, from:
2536 Gary's readline needs the ctypes module, from:
2537 http://starship.python.net/crew/theller/ctypes
2537 http://starship.python.net/crew/theller/ctypes
2538 (Note that ctypes is already part of Python versions 2.5 and newer).
2538 (Note that ctypes is already part of Python versions 2.5 and newer).
2539
2539
2540 Defaulting color scheme to 'NoColor'"""
2540 Defaulting color scheme to 'NoColor'"""
2541 new_scheme = 'NoColor'
2541 new_scheme = 'NoColor'
2542 warn(msg)
2542 warn(msg)
2543
2543
2544 # readline option is 0
2544 # readline option is 0
2545 if not shell.colors_force and not shell.has_readline:
2545 if not shell.colors_force and not shell.has_readline:
2546 new_scheme = 'NoColor'
2546 new_scheme = 'NoColor'
2547
2547
2548 # Set prompt colors
2548 # Set prompt colors
2549 try:
2549 try:
2550 shell.displayhook.set_colors(new_scheme)
2550 shell.displayhook.set_colors(new_scheme)
2551 except:
2551 except:
2552 color_switch_err('prompt')
2552 color_switch_err('prompt')
2553 else:
2553 else:
2554 shell.colors = \
2554 shell.colors = \
2555 shell.displayhook.color_table.active_scheme_name
2555 shell.displayhook.color_table.active_scheme_name
2556 # Set exception colors
2556 # Set exception colors
2557 try:
2557 try:
2558 shell.InteractiveTB.set_colors(scheme = new_scheme)
2558 shell.InteractiveTB.set_colors(scheme = new_scheme)
2559 shell.SyntaxTB.set_colors(scheme = new_scheme)
2559 shell.SyntaxTB.set_colors(scheme = new_scheme)
2560 except:
2560 except:
2561 color_switch_err('exception')
2561 color_switch_err('exception')
2562
2562
2563 # Set info (for 'object?') colors
2563 # Set info (for 'object?') colors
2564 if shell.color_info:
2564 if shell.color_info:
2565 try:
2565 try:
2566 shell.inspector.set_active_scheme(new_scheme)
2566 shell.inspector.set_active_scheme(new_scheme)
2567 except:
2567 except:
2568 color_switch_err('object inspector')
2568 color_switch_err('object inspector')
2569 else:
2569 else:
2570 shell.inspector.set_active_scheme('NoColor')
2570 shell.inspector.set_active_scheme('NoColor')
2571
2571
2572 def magic_pprint(self, parameter_s=''):
2572 def magic_pprint(self, parameter_s=''):
2573 """Toggle pretty printing on/off."""
2573 """Toggle pretty printing on/off."""
2574 ptformatter = self.shell.display_formatter.formatters['text/plain']
2574 ptformatter = self.shell.display_formatter.formatters['text/plain']
2575 ptformatter.pprint = bool(1 - ptformatter.pprint)
2575 ptformatter.pprint = bool(1 - ptformatter.pprint)
2576 print 'Pretty printing has been turned', \
2576 print 'Pretty printing has been turned', \
2577 ['OFF','ON'][ptformatter.pprint]
2577 ['OFF','ON'][ptformatter.pprint]
2578
2578
2579 #......................................................................
2579 #......................................................................
2580 # Functions to implement unix shell-type things
2580 # Functions to implement unix shell-type things
2581
2581
2582 @skip_doctest
2582 @skip_doctest
2583 def magic_alias(self, parameter_s = ''):
2583 def magic_alias(self, parameter_s = ''):
2584 """Define an alias for a system command.
2584 """Define an alias for a system command.
2585
2585
2586 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2586 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2587
2587
2588 Then, typing 'alias_name params' will execute the system command 'cmd
2588 Then, typing 'alias_name params' will execute the system command 'cmd
2589 params' (from your underlying operating system).
2589 params' (from your underlying operating system).
2590
2590
2591 Aliases have lower precedence than magic functions and Python normal
2591 Aliases have lower precedence than magic functions and Python normal
2592 variables, so if 'foo' is both a Python variable and an alias, the
2592 variables, so if 'foo' is both a Python variable and an alias, the
2593 alias can not be executed until 'del foo' removes the Python variable.
2593 alias can not be executed until 'del foo' removes the Python variable.
2594
2594
2595 You can use the %l specifier in an alias definition to represent the
2595 You can use the %l specifier in an alias definition to represent the
2596 whole line when the alias is called. For example:
2596 whole line when the alias is called. For example:
2597
2597
2598 In [2]: alias bracket echo "Input in brackets: <%l>"
2598 In [2]: alias bracket echo "Input in brackets: <%l>"
2599 In [3]: bracket hello world
2599 In [3]: bracket hello world
2600 Input in brackets: <hello world>
2600 Input in brackets: <hello world>
2601
2601
2602 You can also define aliases with parameters using %s specifiers (one
2602 You can also define aliases with parameters using %s specifiers (one
2603 per parameter):
2603 per parameter):
2604
2604
2605 In [1]: alias parts echo first %s second %s
2605 In [1]: alias parts echo first %s second %s
2606 In [2]: %parts A B
2606 In [2]: %parts A B
2607 first A second B
2607 first A second B
2608 In [3]: %parts A
2608 In [3]: %parts A
2609 Incorrect number of arguments: 2 expected.
2609 Incorrect number of arguments: 2 expected.
2610 parts is an alias to: 'echo first %s second %s'
2610 parts is an alias to: 'echo first %s second %s'
2611
2611
2612 Note that %l and %s are mutually exclusive. You can only use one or
2612 Note that %l and %s are mutually exclusive. You can only use one or
2613 the other in your aliases.
2613 the other in your aliases.
2614
2614
2615 Aliases expand Python variables just like system calls using ! or !!
2615 Aliases expand Python variables just like system calls using ! or !!
2616 do: all expressions prefixed with '$' get expanded. For details of
2616 do: all expressions prefixed with '$' get expanded. For details of
2617 the semantic rules, see PEP-215:
2617 the semantic rules, see PEP-215:
2618 http://www.python.org/peps/pep-0215.html. This is the library used by
2618 http://www.python.org/peps/pep-0215.html. This is the library used by
2619 IPython for variable expansion. If you want to access a true shell
2619 IPython for variable expansion. If you want to access a true shell
2620 variable, an extra $ is necessary to prevent its expansion by IPython:
2620 variable, an extra $ is necessary to prevent its expansion by IPython:
2621
2621
2622 In [6]: alias show echo
2622 In [6]: alias show echo
2623 In [7]: PATH='A Python string'
2623 In [7]: PATH='A Python string'
2624 In [8]: show $PATH
2624 In [8]: show $PATH
2625 A Python string
2625 A Python string
2626 In [9]: show $$PATH
2626 In [9]: show $$PATH
2627 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2627 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2628
2628
2629 You can use the alias facility to acess all of $PATH. See the %rehash
2629 You can use the alias facility to acess all of $PATH. See the %rehash
2630 and %rehashx functions, which automatically create aliases for the
2630 and %rehashx functions, which automatically create aliases for the
2631 contents of your $PATH.
2631 contents of your $PATH.
2632
2632
2633 If called with no parameters, %alias prints the current alias table."""
2633 If called with no parameters, %alias prints the current alias table."""
2634
2634
2635 par = parameter_s.strip()
2635 par = parameter_s.strip()
2636 if not par:
2636 if not par:
2637 stored = self.db.get('stored_aliases', {} )
2637 stored = self.db.get('stored_aliases', {} )
2638 aliases = sorted(self.shell.alias_manager.aliases)
2638 aliases = sorted(self.shell.alias_manager.aliases)
2639 # for k, v in stored:
2639 # for k, v in stored:
2640 # atab.append(k, v[0])
2640 # atab.append(k, v[0])
2641
2641
2642 print "Total number of aliases:", len(aliases)
2642 print "Total number of aliases:", len(aliases)
2643 sys.stdout.flush()
2643 sys.stdout.flush()
2644 return aliases
2644 return aliases
2645
2645
2646 # Now try to define a new one
2646 # Now try to define a new one
2647 try:
2647 try:
2648 alias,cmd = par.split(None, 1)
2648 alias,cmd = par.split(None, 1)
2649 except:
2649 except:
2650 print oinspect.getdoc(self.magic_alias)
2650 print oinspect.getdoc(self.magic_alias)
2651 else:
2651 else:
2652 self.shell.alias_manager.soft_define_alias(alias, cmd)
2652 self.shell.alias_manager.soft_define_alias(alias, cmd)
2653 # end magic_alias
2653 # end magic_alias
2654
2654
2655 def magic_unalias(self, parameter_s = ''):
2655 def magic_unalias(self, parameter_s = ''):
2656 """Remove an alias"""
2656 """Remove an alias"""
2657
2657
2658 aname = parameter_s.strip()
2658 aname = parameter_s.strip()
2659 self.shell.alias_manager.undefine_alias(aname)
2659 self.shell.alias_manager.undefine_alias(aname)
2660 stored = self.db.get('stored_aliases', {} )
2660 stored = self.db.get('stored_aliases', {} )
2661 if aname in stored:
2661 if aname in stored:
2662 print "Removing %stored alias",aname
2662 print "Removing %stored alias",aname
2663 del stored[aname]
2663 del stored[aname]
2664 self.db['stored_aliases'] = stored
2664 self.db['stored_aliases'] = stored
2665
2665
2666 def magic_rehashx(self, parameter_s = ''):
2666 def magic_rehashx(self, parameter_s = ''):
2667 """Update the alias table with all executable files in $PATH.
2667 """Update the alias table with all executable files in $PATH.
2668
2668
2669 This version explicitly checks that every entry in $PATH is a file
2669 This version explicitly checks that every entry in $PATH is a file
2670 with execute access (os.X_OK), so it is much slower than %rehash.
2670 with execute access (os.X_OK), so it is much slower than %rehash.
2671
2671
2672 Under Windows, it checks executability as a match agains a
2672 Under Windows, it checks executability as a match agains a
2673 '|'-separated string of extensions, stored in the IPython config
2673 '|'-separated string of extensions, stored in the IPython config
2674 variable win_exec_ext. This defaults to 'exe|com|bat'.
2674 variable win_exec_ext. This defaults to 'exe|com|bat'.
2675
2675
2676 This function also resets the root module cache of module completer,
2676 This function also resets the root module cache of module completer,
2677 used on slow filesystems.
2677 used on slow filesystems.
2678 """
2678 """
2679 from IPython.core.alias import InvalidAliasError
2679 from IPython.core.alias import InvalidAliasError
2680
2680
2681 # for the benefit of module completer in ipy_completers.py
2681 # for the benefit of module completer in ipy_completers.py
2682 del self.db['rootmodules']
2682 del self.db['rootmodules']
2683
2683
2684 path = [os.path.abspath(os.path.expanduser(p)) for p in
2684 path = [os.path.abspath(os.path.expanduser(p)) for p in
2685 os.environ.get('PATH','').split(os.pathsep)]
2685 os.environ.get('PATH','').split(os.pathsep)]
2686 path = filter(os.path.isdir,path)
2686 path = filter(os.path.isdir,path)
2687
2687
2688 syscmdlist = []
2688 syscmdlist = []
2689 # Now define isexec in a cross platform manner.
2689 # Now define isexec in a cross platform manner.
2690 if os.name == 'posix':
2690 if os.name == 'posix':
2691 isexec = lambda fname:os.path.isfile(fname) and \
2691 isexec = lambda fname:os.path.isfile(fname) and \
2692 os.access(fname,os.X_OK)
2692 os.access(fname,os.X_OK)
2693 else:
2693 else:
2694 try:
2694 try:
2695 winext = os.environ['pathext'].replace(';','|').replace('.','')
2695 winext = os.environ['pathext'].replace(';','|').replace('.','')
2696 except KeyError:
2696 except KeyError:
2697 winext = 'exe|com|bat|py'
2697 winext = 'exe|com|bat|py'
2698 if 'py' not in winext:
2698 if 'py' not in winext:
2699 winext += '|py'
2699 winext += '|py'
2700 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2700 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2701 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2701 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2702 savedir = os.getcwdu()
2702 savedir = os.getcwdu()
2703
2703
2704 # Now walk the paths looking for executables to alias.
2704 # Now walk the paths looking for executables to alias.
2705 try:
2705 try:
2706 # write the whole loop for posix/Windows so we don't have an if in
2706 # write the whole loop for posix/Windows so we don't have an if in
2707 # the innermost part
2707 # the innermost part
2708 if os.name == 'posix':
2708 if os.name == 'posix':
2709 for pdir in path:
2709 for pdir in path:
2710 os.chdir(pdir)
2710 os.chdir(pdir)
2711 for ff in os.listdir(pdir):
2711 for ff in os.listdir(pdir):
2712 if isexec(ff):
2712 if isexec(ff):
2713 try:
2713 try:
2714 # Removes dots from the name since ipython
2714 # Removes dots from the name since ipython
2715 # will assume names with dots to be python.
2715 # will assume names with dots to be python.
2716 self.shell.alias_manager.define_alias(
2716 self.shell.alias_manager.define_alias(
2717 ff.replace('.',''), ff)
2717 ff.replace('.',''), ff)
2718 except InvalidAliasError:
2718 except InvalidAliasError:
2719 pass
2719 pass
2720 else:
2720 else:
2721 syscmdlist.append(ff)
2721 syscmdlist.append(ff)
2722 else:
2722 else:
2723 no_alias = self.shell.alias_manager.no_alias
2723 no_alias = self.shell.alias_manager.no_alias
2724 for pdir in path:
2724 for pdir in path:
2725 os.chdir(pdir)
2725 os.chdir(pdir)
2726 for ff in os.listdir(pdir):
2726 for ff in os.listdir(pdir):
2727 base, ext = os.path.splitext(ff)
2727 base, ext = os.path.splitext(ff)
2728 if isexec(ff) and base.lower() not in no_alias:
2728 if isexec(ff) and base.lower() not in no_alias:
2729 if ext.lower() == '.exe':
2729 if ext.lower() == '.exe':
2730 ff = base
2730 ff = base
2731 try:
2731 try:
2732 # Removes dots from the name since ipython
2732 # Removes dots from the name since ipython
2733 # will assume names with dots to be python.
2733 # will assume names with dots to be python.
2734 self.shell.alias_manager.define_alias(
2734 self.shell.alias_manager.define_alias(
2735 base.lower().replace('.',''), ff)
2735 base.lower().replace('.',''), ff)
2736 except InvalidAliasError:
2736 except InvalidAliasError:
2737 pass
2737 pass
2738 syscmdlist.append(ff)
2738 syscmdlist.append(ff)
2739 db = self.db
2739 db = self.db
2740 db['syscmdlist'] = syscmdlist
2740 db['syscmdlist'] = syscmdlist
2741 finally:
2741 finally:
2742 os.chdir(savedir)
2742 os.chdir(savedir)
2743
2743
2744 @skip_doctest
2744 @skip_doctest
2745 def magic_pwd(self, parameter_s = ''):
2745 def magic_pwd(self, parameter_s = ''):
2746 """Return the current working directory path.
2746 """Return the current working directory path.
2747
2747
2748 Examples
2748 Examples
2749 --------
2749 --------
2750 ::
2750 ::
2751
2751
2752 In [9]: pwd
2752 In [9]: pwd
2753 Out[9]: '/home/tsuser/sprint/ipython'
2753 Out[9]: '/home/tsuser/sprint/ipython'
2754 """
2754 """
2755 return os.getcwdu()
2755 return os.getcwdu()
2756
2756
2757 @skip_doctest
2757 @skip_doctest
2758 def magic_cd(self, parameter_s=''):
2758 def magic_cd(self, parameter_s=''):
2759 """Change the current working directory.
2759 """Change the current working directory.
2760
2760
2761 This command automatically maintains an internal list of directories
2761 This command automatically maintains an internal list of directories
2762 you visit during your IPython session, in the variable _dh. The
2762 you visit during your IPython session, in the variable _dh. The
2763 command %dhist shows this history nicely formatted. You can also
2763 command %dhist shows this history nicely formatted. You can also
2764 do 'cd -<tab>' to see directory history conveniently.
2764 do 'cd -<tab>' to see directory history conveniently.
2765
2765
2766 Usage:
2766 Usage:
2767
2767
2768 cd 'dir': changes to directory 'dir'.
2768 cd 'dir': changes to directory 'dir'.
2769
2769
2770 cd -: changes to the last visited directory.
2770 cd -: changes to the last visited directory.
2771
2771
2772 cd -<n>: changes to the n-th directory in the directory history.
2772 cd -<n>: changes to the n-th directory in the directory history.
2773
2773
2774 cd --foo: change to directory that matches 'foo' in history
2774 cd --foo: change to directory that matches 'foo' in history
2775
2775
2776 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2776 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2777 (note: cd <bookmark_name> is enough if there is no
2777 (note: cd <bookmark_name> is enough if there is no
2778 directory <bookmark_name>, but a bookmark with the name exists.)
2778 directory <bookmark_name>, but a bookmark with the name exists.)
2779 'cd -b <tab>' allows you to tab-complete bookmark names.
2779 'cd -b <tab>' allows you to tab-complete bookmark names.
2780
2780
2781 Options:
2781 Options:
2782
2782
2783 -q: quiet. Do not print the working directory after the cd command is
2783 -q: quiet. Do not print the working directory after the cd command is
2784 executed. By default IPython's cd command does print this directory,
2784 executed. By default IPython's cd command does print this directory,
2785 since the default prompts do not display path information.
2785 since the default prompts do not display path information.
2786
2786
2787 Note that !cd doesn't work for this purpose because the shell where
2787 Note that !cd doesn't work for this purpose because the shell where
2788 !command runs is immediately discarded after executing 'command'.
2788 !command runs is immediately discarded after executing 'command'.
2789
2789
2790 Examples
2790 Examples
2791 --------
2791 --------
2792 ::
2792 ::
2793
2793
2794 In [10]: cd parent/child
2794 In [10]: cd parent/child
2795 /home/tsuser/parent/child
2795 /home/tsuser/parent/child
2796 """
2796 """
2797
2797
2798 parameter_s = parameter_s.strip()
2798 parameter_s = parameter_s.strip()
2799 #bkms = self.shell.persist.get("bookmarks",{})
2799 #bkms = self.shell.persist.get("bookmarks",{})
2800
2800
2801 oldcwd = os.getcwdu()
2801 oldcwd = os.getcwdu()
2802 numcd = re.match(r'(-)(\d+)$',parameter_s)
2802 numcd = re.match(r'(-)(\d+)$',parameter_s)
2803 # jump in directory history by number
2803 # jump in directory history by number
2804 if numcd:
2804 if numcd:
2805 nn = int(numcd.group(2))
2805 nn = int(numcd.group(2))
2806 try:
2806 try:
2807 ps = self.shell.user_ns['_dh'][nn]
2807 ps = self.shell.user_ns['_dh'][nn]
2808 except IndexError:
2808 except IndexError:
2809 print 'The requested directory does not exist in history.'
2809 print 'The requested directory does not exist in history.'
2810 return
2810 return
2811 else:
2811 else:
2812 opts = {}
2812 opts = {}
2813 elif parameter_s.startswith('--'):
2813 elif parameter_s.startswith('--'):
2814 ps = None
2814 ps = None
2815 fallback = None
2815 fallback = None
2816 pat = parameter_s[2:]
2816 pat = parameter_s[2:]
2817 dh = self.shell.user_ns['_dh']
2817 dh = self.shell.user_ns['_dh']
2818 # first search only by basename (last component)
2818 # first search only by basename (last component)
2819 for ent in reversed(dh):
2819 for ent in reversed(dh):
2820 if pat in os.path.basename(ent) and os.path.isdir(ent):
2820 if pat in os.path.basename(ent) and os.path.isdir(ent):
2821 ps = ent
2821 ps = ent
2822 break
2822 break
2823
2823
2824 if fallback is None and pat in ent and os.path.isdir(ent):
2824 if fallback is None and pat in ent and os.path.isdir(ent):
2825 fallback = ent
2825 fallback = ent
2826
2826
2827 # if we have no last part match, pick the first full path match
2827 # if we have no last part match, pick the first full path match
2828 if ps is None:
2828 if ps is None:
2829 ps = fallback
2829 ps = fallback
2830
2830
2831 if ps is None:
2831 if ps is None:
2832 print "No matching entry in directory history"
2832 print "No matching entry in directory history"
2833 return
2833 return
2834 else:
2834 else:
2835 opts = {}
2835 opts = {}
2836
2836
2837
2837
2838 else:
2838 else:
2839 #turn all non-space-escaping backslashes to slashes,
2839 #turn all non-space-escaping backslashes to slashes,
2840 # for c:\windows\directory\names\
2840 # for c:\windows\directory\names\
2841 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2841 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2842 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2842 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2843 # jump to previous
2843 # jump to previous
2844 if ps == '-':
2844 if ps == '-':
2845 try:
2845 try:
2846 ps = self.shell.user_ns['_dh'][-2]
2846 ps = self.shell.user_ns['_dh'][-2]
2847 except IndexError:
2847 except IndexError:
2848 raise UsageError('%cd -: No previous directory to change to.')
2848 raise UsageError('%cd -: No previous directory to change to.')
2849 # jump to bookmark if needed
2849 # jump to bookmark if needed
2850 else:
2850 else:
2851 if not os.path.isdir(ps) or opts.has_key('b'):
2851 if not os.path.isdir(ps) or opts.has_key('b'):
2852 bkms = self.db.get('bookmarks', {})
2852 bkms = self.db.get('bookmarks', {})
2853
2853
2854 if bkms.has_key(ps):
2854 if bkms.has_key(ps):
2855 target = bkms[ps]
2855 target = bkms[ps]
2856 print '(bookmark:%s) -> %s' % (ps,target)
2856 print '(bookmark:%s) -> %s' % (ps,target)
2857 ps = target
2857 ps = target
2858 else:
2858 else:
2859 if opts.has_key('b'):
2859 if opts.has_key('b'):
2860 raise UsageError("Bookmark '%s' not found. "
2860 raise UsageError("Bookmark '%s' not found. "
2861 "Use '%%bookmark -l' to see your bookmarks." % ps)
2861 "Use '%%bookmark -l' to see your bookmarks." % ps)
2862
2862
2863 # strip extra quotes on Windows, because os.chdir doesn't like them
2863 # strip extra quotes on Windows, because os.chdir doesn't like them
2864 ps = unquote_filename(ps)
2864 ps = unquote_filename(ps)
2865 # at this point ps should point to the target dir
2865 # at this point ps should point to the target dir
2866 if ps:
2866 if ps:
2867 try:
2867 try:
2868 os.chdir(os.path.expanduser(ps))
2868 os.chdir(os.path.expanduser(ps))
2869 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2869 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2870 set_term_title('IPython: ' + abbrev_cwd())
2870 set_term_title('IPython: ' + abbrev_cwd())
2871 except OSError:
2871 except OSError:
2872 print sys.exc_info()[1]
2872 print sys.exc_info()[1]
2873 else:
2873 else:
2874 cwd = os.getcwdu()
2874 cwd = os.getcwdu()
2875 dhist = self.shell.user_ns['_dh']
2875 dhist = self.shell.user_ns['_dh']
2876 if oldcwd != cwd:
2876 if oldcwd != cwd:
2877 dhist.append(cwd)
2877 dhist.append(cwd)
2878 self.db['dhist'] = compress_dhist(dhist)[-100:]
2878 self.db['dhist'] = compress_dhist(dhist)[-100:]
2879
2879
2880 else:
2880 else:
2881 os.chdir(self.shell.home_dir)
2881 os.chdir(self.shell.home_dir)
2882 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2882 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2883 set_term_title('IPython: ' + '~')
2883 set_term_title('IPython: ' + '~')
2884 cwd = os.getcwdu()
2884 cwd = os.getcwdu()
2885 dhist = self.shell.user_ns['_dh']
2885 dhist = self.shell.user_ns['_dh']
2886
2886
2887 if oldcwd != cwd:
2887 if oldcwd != cwd:
2888 dhist.append(cwd)
2888 dhist.append(cwd)
2889 self.db['dhist'] = compress_dhist(dhist)[-100:]
2889 self.db['dhist'] = compress_dhist(dhist)[-100:]
2890 if not 'q' in opts and self.shell.user_ns['_dh']:
2890 if not 'q' in opts and self.shell.user_ns['_dh']:
2891 print self.shell.user_ns['_dh'][-1]
2891 print self.shell.user_ns['_dh'][-1]
2892
2892
2893
2893
2894 def magic_env(self, parameter_s=''):
2894 def magic_env(self, parameter_s=''):
2895 """List environment variables."""
2895 """List environment variables."""
2896
2896
2897 return os.environ.data
2897 return os.environ.data
2898
2898
2899 def magic_pushd(self, parameter_s=''):
2899 def magic_pushd(self, parameter_s=''):
2900 """Place the current dir on stack and change directory.
2900 """Place the current dir on stack and change directory.
2901
2901
2902 Usage:\\
2902 Usage:\\
2903 %pushd ['dirname']
2903 %pushd ['dirname']
2904 """
2904 """
2905
2905
2906 dir_s = self.shell.dir_stack
2906 dir_s = self.shell.dir_stack
2907 tgt = os.path.expanduser(unquote_filename(parameter_s))
2907 tgt = os.path.expanduser(unquote_filename(parameter_s))
2908 cwd = os.getcwdu().replace(self.home_dir,'~')
2908 cwd = os.getcwdu().replace(self.home_dir,'~')
2909 if tgt:
2909 if tgt:
2910 self.magic_cd(parameter_s)
2910 self.magic_cd(parameter_s)
2911 dir_s.insert(0,cwd)
2911 dir_s.insert(0,cwd)
2912 return self.magic_dirs()
2912 return self.magic_dirs()
2913
2913
2914 def magic_popd(self, parameter_s=''):
2914 def magic_popd(self, parameter_s=''):
2915 """Change to directory popped off the top of the stack.
2915 """Change to directory popped off the top of the stack.
2916 """
2916 """
2917 if not self.shell.dir_stack:
2917 if not self.shell.dir_stack:
2918 raise UsageError("%popd on empty stack")
2918 raise UsageError("%popd on empty stack")
2919 top = self.shell.dir_stack.pop(0)
2919 top = self.shell.dir_stack.pop(0)
2920 self.magic_cd(top)
2920 self.magic_cd(top)
2921 print "popd ->",top
2921 print "popd ->",top
2922
2922
2923 def magic_dirs(self, parameter_s=''):
2923 def magic_dirs(self, parameter_s=''):
2924 """Return the current directory stack."""
2924 """Return the current directory stack."""
2925
2925
2926 return self.shell.dir_stack
2926 return self.shell.dir_stack
2927
2927
2928 def magic_dhist(self, parameter_s=''):
2928 def magic_dhist(self, parameter_s=''):
2929 """Print your history of visited directories.
2929 """Print your history of visited directories.
2930
2930
2931 %dhist -> print full history\\
2931 %dhist -> print full history\\
2932 %dhist n -> print last n entries only\\
2932 %dhist n -> print last n entries only\\
2933 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2933 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2934
2934
2935 This history is automatically maintained by the %cd command, and
2935 This history is automatically maintained by the %cd command, and
2936 always available as the global list variable _dh. You can use %cd -<n>
2936 always available as the global list variable _dh. You can use %cd -<n>
2937 to go to directory number <n>.
2937 to go to directory number <n>.
2938
2938
2939 Note that most of time, you should view directory history by entering
2939 Note that most of time, you should view directory history by entering
2940 cd -<TAB>.
2940 cd -<TAB>.
2941
2941
2942 """
2942 """
2943
2943
2944 dh = self.shell.user_ns['_dh']
2944 dh = self.shell.user_ns['_dh']
2945 if parameter_s:
2945 if parameter_s:
2946 try:
2946 try:
2947 args = map(int,parameter_s.split())
2947 args = map(int,parameter_s.split())
2948 except:
2948 except:
2949 self.arg_err(Magic.magic_dhist)
2949 self.arg_err(Magic.magic_dhist)
2950 return
2950 return
2951 if len(args) == 1:
2951 if len(args) == 1:
2952 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2952 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2953 elif len(args) == 2:
2953 elif len(args) == 2:
2954 ini,fin = args
2954 ini,fin = args
2955 else:
2955 else:
2956 self.arg_err(Magic.magic_dhist)
2956 self.arg_err(Magic.magic_dhist)
2957 return
2957 return
2958 else:
2958 else:
2959 ini,fin = 0,len(dh)
2959 ini,fin = 0,len(dh)
2960 nlprint(dh,
2960 nlprint(dh,
2961 header = 'Directory history (kept in _dh)',
2961 header = 'Directory history (kept in _dh)',
2962 start=ini,stop=fin)
2962 start=ini,stop=fin)
2963
2963
2964 @skip_doctest
2964 @skip_doctest
2965 def magic_sc(self, parameter_s=''):
2965 def magic_sc(self, parameter_s=''):
2966 """Shell capture - execute a shell command and capture its output.
2966 """Shell capture - execute a shell command and capture its output.
2967
2967
2968 DEPRECATED. Suboptimal, retained for backwards compatibility.
2968 DEPRECATED. Suboptimal, retained for backwards compatibility.
2969
2969
2970 You should use the form 'var = !command' instead. Example:
2970 You should use the form 'var = !command' instead. Example:
2971
2971
2972 "%sc -l myfiles = ls ~" should now be written as
2972 "%sc -l myfiles = ls ~" should now be written as
2973
2973
2974 "myfiles = !ls ~"
2974 "myfiles = !ls ~"
2975
2975
2976 myfiles.s, myfiles.l and myfiles.n still apply as documented
2976 myfiles.s, myfiles.l and myfiles.n still apply as documented
2977 below.
2977 below.
2978
2978
2979 --
2979 --
2980 %sc [options] varname=command
2980 %sc [options] varname=command
2981
2981
2982 IPython will run the given command using commands.getoutput(), and
2982 IPython will run the given command using commands.getoutput(), and
2983 will then update the user's interactive namespace with a variable
2983 will then update the user's interactive namespace with a variable
2984 called varname, containing the value of the call. Your command can
2984 called varname, containing the value of the call. Your command can
2985 contain shell wildcards, pipes, etc.
2985 contain shell wildcards, pipes, etc.
2986
2986
2987 The '=' sign in the syntax is mandatory, and the variable name you
2987 The '=' sign in the syntax is mandatory, and the variable name you
2988 supply must follow Python's standard conventions for valid names.
2988 supply must follow Python's standard conventions for valid names.
2989
2989
2990 (A special format without variable name exists for internal use)
2990 (A special format without variable name exists for internal use)
2991
2991
2992 Options:
2992 Options:
2993
2993
2994 -l: list output. Split the output on newlines into a list before
2994 -l: list output. Split the output on newlines into a list before
2995 assigning it to the given variable. By default the output is stored
2995 assigning it to the given variable. By default the output is stored
2996 as a single string.
2996 as a single string.
2997
2997
2998 -v: verbose. Print the contents of the variable.
2998 -v: verbose. Print the contents of the variable.
2999
2999
3000 In most cases you should not need to split as a list, because the
3000 In most cases you should not need to split as a list, because the
3001 returned value is a special type of string which can automatically
3001 returned value is a special type of string which can automatically
3002 provide its contents either as a list (split on newlines) or as a
3002 provide its contents either as a list (split on newlines) or as a
3003 space-separated string. These are convenient, respectively, either
3003 space-separated string. These are convenient, respectively, either
3004 for sequential processing or to be passed to a shell command.
3004 for sequential processing or to be passed to a shell command.
3005
3005
3006 For example:
3006 For example:
3007
3007
3008 # all-random
3008 # all-random
3009
3009
3010 # Capture into variable a
3010 # Capture into variable a
3011 In [1]: sc a=ls *py
3011 In [1]: sc a=ls *py
3012
3012
3013 # a is a string with embedded newlines
3013 # a is a string with embedded newlines
3014 In [2]: a
3014 In [2]: a
3015 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3015 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3016
3016
3017 # which can be seen as a list:
3017 # which can be seen as a list:
3018 In [3]: a.l
3018 In [3]: a.l
3019 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3019 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3020
3020
3021 # or as a whitespace-separated string:
3021 # or as a whitespace-separated string:
3022 In [4]: a.s
3022 In [4]: a.s
3023 Out[4]: 'setup.py win32_manual_post_install.py'
3023 Out[4]: 'setup.py win32_manual_post_install.py'
3024
3024
3025 # a.s is useful to pass as a single command line:
3025 # a.s is useful to pass as a single command line:
3026 In [5]: !wc -l $a.s
3026 In [5]: !wc -l $a.s
3027 146 setup.py
3027 146 setup.py
3028 130 win32_manual_post_install.py
3028 130 win32_manual_post_install.py
3029 276 total
3029 276 total
3030
3030
3031 # while the list form is useful to loop over:
3031 # while the list form is useful to loop over:
3032 In [6]: for f in a.l:
3032 In [6]: for f in a.l:
3033 ...: !wc -l $f
3033 ...: !wc -l $f
3034 ...:
3034 ...:
3035 146 setup.py
3035 146 setup.py
3036 130 win32_manual_post_install.py
3036 130 win32_manual_post_install.py
3037
3037
3038 Similiarly, the lists returned by the -l option are also special, in
3038 Similiarly, the lists returned by the -l option are also special, in
3039 the sense that you can equally invoke the .s attribute on them to
3039 the sense that you can equally invoke the .s attribute on them to
3040 automatically get a whitespace-separated string from their contents:
3040 automatically get a whitespace-separated string from their contents:
3041
3041
3042 In [7]: sc -l b=ls *py
3042 In [7]: sc -l b=ls *py
3043
3043
3044 In [8]: b
3044 In [8]: b
3045 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3045 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3046
3046
3047 In [9]: b.s
3047 In [9]: b.s
3048 Out[9]: 'setup.py win32_manual_post_install.py'
3048 Out[9]: 'setup.py win32_manual_post_install.py'
3049
3049
3050 In summary, both the lists and strings used for ouptut capture have
3050 In summary, both the lists and strings used for ouptut capture have
3051 the following special attributes:
3051 the following special attributes:
3052
3052
3053 .l (or .list) : value as list.
3053 .l (or .list) : value as list.
3054 .n (or .nlstr): value as newline-separated string.
3054 .n (or .nlstr): value as newline-separated string.
3055 .s (or .spstr): value as space-separated string.
3055 .s (or .spstr): value as space-separated string.
3056 """
3056 """
3057
3057
3058 opts,args = self.parse_options(parameter_s,'lv')
3058 opts,args = self.parse_options(parameter_s,'lv')
3059 # Try to get a variable name and command to run
3059 # Try to get a variable name and command to run
3060 try:
3060 try:
3061 # the variable name must be obtained from the parse_options
3061 # the variable name must be obtained from the parse_options
3062 # output, which uses shlex.split to strip options out.
3062 # output, which uses shlex.split to strip options out.
3063 var,_ = args.split('=',1)
3063 var,_ = args.split('=',1)
3064 var = var.strip()
3064 var = var.strip()
3065 # But the the command has to be extracted from the original input
3065 # But the the command has to be extracted from the original input
3066 # parameter_s, not on what parse_options returns, to avoid the
3066 # parameter_s, not on what parse_options returns, to avoid the
3067 # quote stripping which shlex.split performs on it.
3067 # quote stripping which shlex.split performs on it.
3068 _,cmd = parameter_s.split('=',1)
3068 _,cmd = parameter_s.split('=',1)
3069 except ValueError:
3069 except ValueError:
3070 var,cmd = '',''
3070 var,cmd = '',''
3071 # If all looks ok, proceed
3071 # If all looks ok, proceed
3072 split = 'l' in opts
3072 split = 'l' in opts
3073 out = self.shell.getoutput(cmd, split=split)
3073 out = self.shell.getoutput(cmd, split=split)
3074 if opts.has_key('v'):
3074 if opts.has_key('v'):
3075 print '%s ==\n%s' % (var,pformat(out))
3075 print '%s ==\n%s' % (var,pformat(out))
3076 if var:
3076 if var:
3077 self.shell.user_ns.update({var:out})
3077 self.shell.user_ns.update({var:out})
3078 else:
3078 else:
3079 return out
3079 return out
3080
3080
3081 def magic_sx(self, parameter_s=''):
3081 def magic_sx(self, parameter_s=''):
3082 """Shell execute - run a shell command and capture its output.
3082 """Shell execute - run a shell command and capture its output.
3083
3083
3084 %sx command
3084 %sx command
3085
3085
3086 IPython will run the given command using commands.getoutput(), and
3086 IPython will run the given command using commands.getoutput(), and
3087 return the result formatted as a list (split on '\\n'). Since the
3087 return the result formatted as a list (split on '\\n'). Since the
3088 output is _returned_, it will be stored in ipython's regular output
3088 output is _returned_, it will be stored in ipython's regular output
3089 cache Out[N] and in the '_N' automatic variables.
3089 cache Out[N] and in the '_N' automatic variables.
3090
3090
3091 Notes:
3091 Notes:
3092
3092
3093 1) If an input line begins with '!!', then %sx is automatically
3093 1) If an input line begins with '!!', then %sx is automatically
3094 invoked. That is, while:
3094 invoked. That is, while:
3095 !ls
3095 !ls
3096 causes ipython to simply issue system('ls'), typing
3096 causes ipython to simply issue system('ls'), typing
3097 !!ls
3097 !!ls
3098 is a shorthand equivalent to:
3098 is a shorthand equivalent to:
3099 %sx ls
3099 %sx ls
3100
3100
3101 2) %sx differs from %sc in that %sx automatically splits into a list,
3101 2) %sx differs from %sc in that %sx automatically splits into a list,
3102 like '%sc -l'. The reason for this is to make it as easy as possible
3102 like '%sc -l'. The reason for this is to make it as easy as possible
3103 to process line-oriented shell output via further python commands.
3103 to process line-oriented shell output via further python commands.
3104 %sc is meant to provide much finer control, but requires more
3104 %sc is meant to provide much finer control, but requires more
3105 typing.
3105 typing.
3106
3106
3107 3) Just like %sc -l, this is a list with special attributes:
3107 3) Just like %sc -l, this is a list with special attributes:
3108
3108
3109 .l (or .list) : value as list.
3109 .l (or .list) : value as list.
3110 .n (or .nlstr): value as newline-separated string.
3110 .n (or .nlstr): value as newline-separated string.
3111 .s (or .spstr): value as whitespace-separated string.
3111 .s (or .spstr): value as whitespace-separated string.
3112
3112
3113 This is very useful when trying to use such lists as arguments to
3113 This is very useful when trying to use such lists as arguments to
3114 system commands."""
3114 system commands."""
3115
3115
3116 if parameter_s:
3116 if parameter_s:
3117 return self.shell.getoutput(parameter_s)
3117 return self.shell.getoutput(parameter_s)
3118
3118
3119
3119
3120 def magic_bookmark(self, parameter_s=''):
3120 def magic_bookmark(self, parameter_s=''):
3121 """Manage IPython's bookmark system.
3121 """Manage IPython's bookmark system.
3122
3122
3123 %bookmark <name> - set bookmark to current dir
3123 %bookmark <name> - set bookmark to current dir
3124 %bookmark <name> <dir> - set bookmark to <dir>
3124 %bookmark <name> <dir> - set bookmark to <dir>
3125 %bookmark -l - list all bookmarks
3125 %bookmark -l - list all bookmarks
3126 %bookmark -d <name> - remove bookmark
3126 %bookmark -d <name> - remove bookmark
3127 %bookmark -r - remove all bookmarks
3127 %bookmark -r - remove all bookmarks
3128
3128
3129 You can later on access a bookmarked folder with:
3129 You can later on access a bookmarked folder with:
3130 %cd -b <name>
3130 %cd -b <name>
3131 or simply '%cd <name>' if there is no directory called <name> AND
3131 or simply '%cd <name>' if there is no directory called <name> AND
3132 there is such a bookmark defined.
3132 there is such a bookmark defined.
3133
3133
3134 Your bookmarks persist through IPython sessions, but they are
3134 Your bookmarks persist through IPython sessions, but they are
3135 associated with each profile."""
3135 associated with each profile."""
3136
3136
3137 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3137 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3138 if len(args) > 2:
3138 if len(args) > 2:
3139 raise UsageError("%bookmark: too many arguments")
3139 raise UsageError("%bookmark: too many arguments")
3140
3140
3141 bkms = self.db.get('bookmarks',{})
3141 bkms = self.db.get('bookmarks',{})
3142
3142
3143 if opts.has_key('d'):
3143 if opts.has_key('d'):
3144 try:
3144 try:
3145 todel = args[0]
3145 todel = args[0]
3146 except IndexError:
3146 except IndexError:
3147 raise UsageError(
3147 raise UsageError(
3148 "%bookmark -d: must provide a bookmark to delete")
3148 "%bookmark -d: must provide a bookmark to delete")
3149 else:
3149 else:
3150 try:
3150 try:
3151 del bkms[todel]
3151 del bkms[todel]
3152 except KeyError:
3152 except KeyError:
3153 raise UsageError(
3153 raise UsageError(
3154 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3154 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3155
3155
3156 elif opts.has_key('r'):
3156 elif opts.has_key('r'):
3157 bkms = {}
3157 bkms = {}
3158 elif opts.has_key('l'):
3158 elif opts.has_key('l'):
3159 bks = bkms.keys()
3159 bks = bkms.keys()
3160 bks.sort()
3160 bks.sort()
3161 if bks:
3161 if bks:
3162 size = max(map(len,bks))
3162 size = max(map(len,bks))
3163 else:
3163 else:
3164 size = 0
3164 size = 0
3165 fmt = '%-'+str(size)+'s -> %s'
3165 fmt = '%-'+str(size)+'s -> %s'
3166 print 'Current bookmarks:'
3166 print 'Current bookmarks:'
3167 for bk in bks:
3167 for bk in bks:
3168 print fmt % (bk,bkms[bk])
3168 print fmt % (bk,bkms[bk])
3169 else:
3169 else:
3170 if not args:
3170 if not args:
3171 raise UsageError("%bookmark: You must specify the bookmark name")
3171 raise UsageError("%bookmark: You must specify the bookmark name")
3172 elif len(args)==1:
3172 elif len(args)==1:
3173 bkms[args[0]] = os.getcwdu()
3173 bkms[args[0]] = os.getcwdu()
3174 elif len(args)==2:
3174 elif len(args)==2:
3175 bkms[args[0]] = args[1]
3175 bkms[args[0]] = args[1]
3176 self.db['bookmarks'] = bkms
3176 self.db['bookmarks'] = bkms
3177
3177
3178 def magic_pycat(self, parameter_s=''):
3178 def magic_pycat(self, parameter_s=''):
3179 """Show a syntax-highlighted file through a pager.
3179 """Show a syntax-highlighted file through a pager.
3180
3180
3181 This magic is similar to the cat utility, but it will assume the file
3181 This magic is similar to the cat utility, but it will assume the file
3182 to be Python source and will show it with syntax highlighting. """
3182 to be Python source and will show it with syntax highlighting. """
3183
3183
3184 try:
3184 try:
3185 filename = get_py_filename(parameter_s)
3185 filename = get_py_filename(parameter_s)
3186 cont = file_read(filename)
3186 cont = file_read(filename)
3187 except IOError:
3187 except IOError:
3188 try:
3188 try:
3189 cont = eval(parameter_s,self.user_ns)
3189 cont = eval(parameter_s,self.user_ns)
3190 except NameError:
3190 except NameError:
3191 cont = None
3191 cont = None
3192 if cont is None:
3192 if cont is None:
3193 print "Error: no such file or variable"
3193 print "Error: no such file or variable"
3194 return
3194 return
3195
3195
3196 page.page(self.shell.pycolorize(cont))
3196 page.page(self.shell.pycolorize(cont))
3197
3197
3198 def _rerun_pasted(self):
3198 def _rerun_pasted(self):
3199 """ Rerun a previously pasted command.
3199 """ Rerun a previously pasted command.
3200 """
3200 """
3201 b = self.user_ns.get('pasted_block', None)
3201 b = self.user_ns.get('pasted_block', None)
3202 if b is None:
3202 if b is None:
3203 raise UsageError('No previous pasted block available')
3203 raise UsageError('No previous pasted block available')
3204 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3204 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3205 exec b in self.user_ns
3205 exec b in self.user_ns
3206
3206
3207 def _get_pasted_lines(self, sentinel):
3207 def _get_pasted_lines(self, sentinel):
3208 """ Yield pasted lines until the user enters the given sentinel value.
3208 """ Yield pasted lines until the user enters the given sentinel value.
3209 """
3209 """
3210 from IPython.core import interactiveshell
3210 from IPython.core import interactiveshell
3211 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3211 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3212 while True:
3212 while True:
3213 try:
3213 try:
3214 l = self.shell.raw_input_original(':')
3214 l = self.shell.raw_input_original(':')
3215 if l == sentinel:
3215 if l == sentinel:
3216 return
3216 return
3217 else:
3217 else:
3218 yield l
3218 yield l
3219 except EOFError:
3219 except EOFError:
3220 print '<EOF>'
3220 print '<EOF>'
3221 return
3221 return
3222
3222
3223 def _strip_pasted_lines_for_code(self, raw_lines):
3223 def _strip_pasted_lines_for_code(self, raw_lines):
3224 """ Strip non-code parts of a sequence of lines to return a block of
3224 """ Strip non-code parts of a sequence of lines to return a block of
3225 code.
3225 code.
3226 """
3226 """
3227 # Regular expressions that declare text we strip from the input:
3227 # Regular expressions that declare text we strip from the input:
3228 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3228 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3229 r'^\s*(\s?>)+', # Python input prompt
3229 r'^\s*(\s?>)+', # Python input prompt
3230 r'^\s*\.{3,}', # Continuation prompts
3230 r'^\s*\.{3,}', # Continuation prompts
3231 r'^\++',
3231 r'^\++',
3232 ]
3232 ]
3233
3233
3234 strip_from_start = map(re.compile,strip_re)
3234 strip_from_start = map(re.compile,strip_re)
3235
3235
3236 lines = []
3236 lines = []
3237 for l in raw_lines:
3237 for l in raw_lines:
3238 for pat in strip_from_start:
3238 for pat in strip_from_start:
3239 l = pat.sub('',l)
3239 l = pat.sub('',l)
3240 lines.append(l)
3240 lines.append(l)
3241
3241
3242 block = "\n".join(lines) + '\n'
3242 block = "\n".join(lines) + '\n'
3243 #print "block:\n",block
3243 #print "block:\n",block
3244 return block
3244 return block
3245
3245
3246 def _execute_block(self, block, par):
3246 def _execute_block(self, block, par):
3247 """ Execute a block, or store it in a variable, per the user's request.
3247 """ Execute a block, or store it in a variable, per the user's request.
3248 """
3248 """
3249 if not par:
3249 if not par:
3250 b = textwrap.dedent(block)
3250 b = textwrap.dedent(block)
3251 self.user_ns['pasted_block'] = b
3251 self.user_ns['pasted_block'] = b
3252 self.run_cell(b)
3252 self.run_cell(b)
3253 else:
3253 else:
3254 self.user_ns[par] = SList(block.splitlines())
3254 self.user_ns[par] = SList(block.splitlines())
3255 print "Block assigned to '%s'" % par
3255 print "Block assigned to '%s'" % par
3256
3256
3257 def magic_quickref(self,arg):
3257 def magic_quickref(self,arg):
3258 """ Show a quick reference sheet """
3258 """ Show a quick reference sheet """
3259 import IPython.core.usage
3259 import IPython.core.usage
3260 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3260 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3261
3261
3262 page.page(qr)
3262 page.page(qr)
3263
3263
3264 def magic_doctest_mode(self,parameter_s=''):
3264 def magic_doctest_mode(self,parameter_s=''):
3265 """Toggle doctest mode on and off.
3265 """Toggle doctest mode on and off.
3266
3266
3267 This mode is intended to make IPython behave as much as possible like a
3267 This mode is intended to make IPython behave as much as possible like a
3268 plain Python shell, from the perspective of how its prompts, exceptions
3268 plain Python shell, from the perspective of how its prompts, exceptions
3269 and output look. This makes it easy to copy and paste parts of a
3269 and output look. This makes it easy to copy and paste parts of a
3270 session into doctests. It does so by:
3270 session into doctests. It does so by:
3271
3271
3272 - Changing the prompts to the classic ``>>>`` ones.
3272 - Changing the prompts to the classic ``>>>`` ones.
3273 - Changing the exception reporting mode to 'Plain'.
3273 - Changing the exception reporting mode to 'Plain'.
3274 - Disabling pretty-printing of output.
3274 - Disabling pretty-printing of output.
3275
3275
3276 Note that IPython also supports the pasting of code snippets that have
3276 Note that IPython also supports the pasting of code snippets that have
3277 leading '>>>' and '...' prompts in them. This means that you can paste
3277 leading '>>>' and '...' prompts in them. This means that you can paste
3278 doctests from files or docstrings (even if they have leading
3278 doctests from files or docstrings (even if they have leading
3279 whitespace), and the code will execute correctly. You can then use
3279 whitespace), and the code will execute correctly. You can then use
3280 '%history -t' to see the translated history; this will give you the
3280 '%history -t' to see the translated history; this will give you the
3281 input after removal of all the leading prompts and whitespace, which
3281 input after removal of all the leading prompts and whitespace, which
3282 can be pasted back into an editor.
3282 can be pasted back into an editor.
3283
3283
3284 With these features, you can switch into this mode easily whenever you
3284 With these features, you can switch into this mode easily whenever you
3285 need to do testing and changes to doctests, without having to leave
3285 need to do testing and changes to doctests, without having to leave
3286 your existing IPython session.
3286 your existing IPython session.
3287 """
3287 """
3288
3288
3289 from IPython.utils.ipstruct import Struct
3289 from IPython.utils.ipstruct import Struct
3290
3290
3291 # Shorthands
3291 # Shorthands
3292 shell = self.shell
3292 shell = self.shell
3293 oc = shell.displayhook
3293 oc = shell.displayhook
3294 meta = shell.meta
3294 meta = shell.meta
3295 disp_formatter = self.shell.display_formatter
3295 disp_formatter = self.shell.display_formatter
3296 ptformatter = disp_formatter.formatters['text/plain']
3296 ptformatter = disp_formatter.formatters['text/plain']
3297 # dstore is a data store kept in the instance metadata bag to track any
3297 # dstore is a data store kept in the instance metadata bag to track any
3298 # changes we make, so we can undo them later.
3298 # changes we make, so we can undo them later.
3299 dstore = meta.setdefault('doctest_mode',Struct())
3299 dstore = meta.setdefault('doctest_mode',Struct())
3300 save_dstore = dstore.setdefault
3300 save_dstore = dstore.setdefault
3301
3301
3302 # save a few values we'll need to recover later
3302 # save a few values we'll need to recover later
3303 mode = save_dstore('mode',False)
3303 mode = save_dstore('mode',False)
3304 save_dstore('rc_pprint',ptformatter.pprint)
3304 save_dstore('rc_pprint',ptformatter.pprint)
3305 save_dstore('xmode',shell.InteractiveTB.mode)
3305 save_dstore('xmode',shell.InteractiveTB.mode)
3306 save_dstore('rc_separate_out',shell.separate_out)
3306 save_dstore('rc_separate_out',shell.separate_out)
3307 save_dstore('rc_separate_out2',shell.separate_out2)
3307 save_dstore('rc_separate_out2',shell.separate_out2)
3308 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3308 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3309 save_dstore('rc_separate_in',shell.separate_in)
3309 save_dstore('rc_separate_in',shell.separate_in)
3310 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3310 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3311
3311
3312 if mode == False:
3312 if mode == False:
3313 # turn on
3313 # turn on
3314 oc.prompt1.p_template = '>>> '
3314 oc.prompt1.p_template = '>>> '
3315 oc.prompt2.p_template = '... '
3315 oc.prompt2.p_template = '... '
3316 oc.prompt_out.p_template = ''
3316 oc.prompt_out.p_template = ''
3317
3317
3318 # Prompt separators like plain python
3318 # Prompt separators like plain python
3319 oc.input_sep = oc.prompt1.sep = ''
3319 oc.input_sep = oc.prompt1.sep = ''
3320 oc.output_sep = ''
3320 oc.output_sep = ''
3321 oc.output_sep2 = ''
3321 oc.output_sep2 = ''
3322
3322
3323 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3323 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3324 oc.prompt_out.pad_left = False
3324 oc.prompt_out.pad_left = False
3325
3325
3326 ptformatter.pprint = False
3326 ptformatter.pprint = False
3327 disp_formatter.plain_text_only = True
3327 disp_formatter.plain_text_only = True
3328
3328
3329 shell.magic_xmode('Plain')
3329 shell.magic_xmode('Plain')
3330 else:
3330 else:
3331 # turn off
3331 # turn off
3332 oc.prompt1.p_template = shell.prompt_in1
3332 oc.prompt1.p_template = shell.prompt_in1
3333 oc.prompt2.p_template = shell.prompt_in2
3333 oc.prompt2.p_template = shell.prompt_in2
3334 oc.prompt_out.p_template = shell.prompt_out
3334 oc.prompt_out.p_template = shell.prompt_out
3335
3335
3336 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3336 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3337
3337
3338 oc.output_sep = dstore.rc_separate_out
3338 oc.output_sep = dstore.rc_separate_out
3339 oc.output_sep2 = dstore.rc_separate_out2
3339 oc.output_sep2 = dstore.rc_separate_out2
3340
3340
3341 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3341 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3342 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3342 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3343
3343
3344 ptformatter.pprint = dstore.rc_pprint
3344 ptformatter.pprint = dstore.rc_pprint
3345 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3345 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3346
3346
3347 shell.magic_xmode(dstore.xmode)
3347 shell.magic_xmode(dstore.xmode)
3348
3348
3349 # Store new mode and inform
3349 # Store new mode and inform
3350 dstore.mode = bool(1-int(mode))
3350 dstore.mode = bool(1-int(mode))
3351 mode_label = ['OFF','ON'][dstore.mode]
3351 mode_label = ['OFF','ON'][dstore.mode]
3352 print 'Doctest mode is:', mode_label
3352 print 'Doctest mode is:', mode_label
3353
3353
3354 def magic_gui(self, parameter_s=''):
3354 def magic_gui(self, parameter_s=''):
3355 """Enable or disable IPython GUI event loop integration.
3355 """Enable or disable IPython GUI event loop integration.
3356
3356
3357 %gui [GUINAME]
3357 %gui [GUINAME]
3358
3358
3359 This magic replaces IPython's threaded shells that were activated
3359 This magic replaces IPython's threaded shells that were activated
3360 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3360 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3361 can now be enabled, disabled and changed at runtime and keyboard
3361 can now be enabled, disabled and changed at runtime and keyboard
3362 interrupts should work without any problems. The following toolkits
3362 interrupts should work without any problems. The following toolkits
3363 are supported: wxPython, PyQt4, PyGTK, and Tk::
3363 are supported: wxPython, PyQt4, PyGTK, and Tk::
3364
3364
3365 %gui wx # enable wxPython event loop integration
3365 %gui wx # enable wxPython event loop integration
3366 %gui qt4|qt # enable PyQt4 event loop integration
3366 %gui qt4|qt # enable PyQt4 event loop integration
3367 %gui gtk # enable PyGTK event loop integration
3367 %gui gtk # enable PyGTK event loop integration
3368 %gui tk # enable Tk event loop integration
3368 %gui tk # enable Tk event loop integration
3369 %gui # disable all event loop integration
3369 %gui # disable all event loop integration
3370
3370
3371 WARNING: after any of these has been called you can simply create
3371 WARNING: after any of these has been called you can simply create
3372 an application object, but DO NOT start the event loop yourself, as
3372 an application object, but DO NOT start the event loop yourself, as
3373 we have already handled that.
3373 we have already handled that.
3374 """
3374 """
3375 from IPython.lib.inputhook import enable_gui
3375 from IPython.lib.inputhook import enable_gui
3376 opts, arg = self.parse_options(parameter_s, '')
3376 opts, arg = self.parse_options(parameter_s, '')
3377 if arg=='': arg = None
3377 if arg=='': arg = None
3378 return enable_gui(arg)
3378 return enable_gui(arg)
3379
3379
3380 def magic_load_ext(self, module_str):
3380 def magic_load_ext(self, module_str):
3381 """Load an IPython extension by its module name."""
3381 """Load an IPython extension by its module name."""
3382 return self.extension_manager.load_extension(module_str)
3382 return self.extension_manager.load_extension(module_str)
3383
3383
3384 def magic_unload_ext(self, module_str):
3384 def magic_unload_ext(self, module_str):
3385 """Unload an IPython extension by its module name."""
3385 """Unload an IPython extension by its module name."""
3386 self.extension_manager.unload_extension(module_str)
3386 self.extension_manager.unload_extension(module_str)
3387
3387
3388 def magic_reload_ext(self, module_str):
3388 def magic_reload_ext(self, module_str):
3389 """Reload an IPython extension by its module name."""
3389 """Reload an IPython extension by its module name."""
3390 self.extension_manager.reload_extension(module_str)
3390 self.extension_manager.reload_extension(module_str)
3391
3391
3392 @skip_doctest
3392 @skip_doctest
3393 def magic_install_profiles(self, s):
3393 def magic_install_profiles(self, s):
3394 """Install the default IPython profiles into the .ipython dir.
3394 """Install the default IPython profiles into the .ipython dir.
3395
3395
3396 If the default profiles have already been installed, they will not
3396 If the default profiles have already been installed, they will not
3397 be overwritten. You can force overwriting them by using the ``-o``
3397 be overwritten. You can force overwriting them by using the ``-o``
3398 option::
3398 option::
3399
3399
3400 In [1]: %install_profiles -o
3400 In [1]: %install_profiles -o
3401 """
3401 """
3402 if '-o' in s:
3402 if '-o' in s:
3403 overwrite = True
3403 overwrite = True
3404 else:
3404 else:
3405 overwrite = False
3405 overwrite = False
3406 from IPython.config import profile
3406 from IPython.config import profile
3407 profile_dir = os.path.dirname(profile.__file__)
3407 profile_dir = os.path.dirname(profile.__file__)
3408 ipython_dir = self.ipython_dir
3408 ipython_dir = self.ipython_dir
3409 print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite)
3409 print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite)
3410 for src in os.listdir(profile_dir):
3410 for src in os.listdir(profile_dir):
3411 if src.startswith('profile_'):
3411 if src.startswith('profile_'):
3412 name = src.replace('profile_', '')
3412 name = src.replace('profile_', '')
3413 print " %s"%name
3413 print " %s"%name
3414 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3414 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3415 pd.copy_config_file('ipython_config.py', path=src,
3415 pd.copy_config_file('ipython_config.py', path=src,
3416 overwrite=overwrite)
3416 overwrite=overwrite)
3417
3417
3418 @skip_doctest
3418 @skip_doctest
3419 def magic_install_default_config(self, s):
3419 def magic_install_default_config(self, s):
3420 """Install IPython's default config file into the .ipython dir.
3420 """Install IPython's default config file into the .ipython dir.
3421
3421
3422 If the default config file (:file:`ipython_config.py`) is already
3422 If the default config file (:file:`ipython_config.py`) is already
3423 installed, it will not be overwritten. You can force overwriting
3423 installed, it will not be overwritten. You can force overwriting
3424 by using the ``-o`` option::
3424 by using the ``-o`` option::
3425
3425
3426 In [1]: %install_default_config
3426 In [1]: %install_default_config
3427 """
3427 """
3428 if '-o' in s:
3428 if '-o' in s:
3429 overwrite = True
3429 overwrite = True
3430 else:
3430 else:
3431 overwrite = False
3431 overwrite = False
3432 pd = self.shell.profile_dir
3432 pd = self.shell.profile_dir
3433 print "Installing default config file in: %s" % pd.location
3433 print "Installing default config file in: %s" % pd.location
3434 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3434 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3435
3435
3436 # Pylab support: simple wrappers that activate pylab, load gui input
3436 # Pylab support: simple wrappers that activate pylab, load gui input
3437 # handling and modify slightly %run
3437 # handling and modify slightly %run
3438
3438
3439 @skip_doctest
3439 @skip_doctest
3440 def _pylab_magic_run(self, parameter_s=''):
3440 def _pylab_magic_run(self, parameter_s=''):
3441 Magic.magic_run(self, parameter_s,
3441 Magic.magic_run(self, parameter_s,
3442 runner=mpl_runner(self.shell.safe_execfile))
3442 runner=mpl_runner(self.shell.safe_execfile))
3443
3443
3444 _pylab_magic_run.__doc__ = magic_run.__doc__
3444 _pylab_magic_run.__doc__ = magic_run.__doc__
3445
3445
3446 @skip_doctest
3446 @skip_doctest
3447 def magic_pylab(self, s):
3447 def magic_pylab(self, s):
3448 """Load numpy and matplotlib to work interactively.
3448 """Load numpy and matplotlib to work interactively.
3449
3449
3450 %pylab [GUINAME]
3450 %pylab [GUINAME]
3451
3451
3452 This function lets you activate pylab (matplotlib, numpy and
3452 This function lets you activate pylab (matplotlib, numpy and
3453 interactive support) at any point during an IPython session.
3453 interactive support) at any point during an IPython session.
3454
3454
3455 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3455 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3456 pylab and mlab, as well as all names from numpy and pylab.
3456 pylab and mlab, as well as all names from numpy and pylab.
3457
3457
3458 If you are using the inline matplotlib backend for embedded figures,
3458 If you are using the inline matplotlib backend for embedded figures,
3459 you can adjust its behavior via the %config magic::
3459 you can adjust its behavior via the %config magic::
3460
3460
3461 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3461 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3462 In [1]: %config InlineBackend.figure_format = 'svg'
3462 In [1]: %config InlineBackend.figure_format = 'svg'
3463
3463
3464 # change the behavior of closing all figures at the end of each
3464 # change the behavior of closing all figures at the end of each
3465 # execution (cell), or allowing reuse of active figures across
3465 # execution (cell), or allowing reuse of active figures across
3466 # cells:
3466 # cells:
3467 In [2]: %config InlineBackend.close_figures = False
3467 In [2]: %config InlineBackend.close_figures = False
3468
3468
3469 Parameters
3469 Parameters
3470 ----------
3470 ----------
3471 guiname : optional
3471 guiname : optional
3472 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3472 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3473 'tk'). If given, the corresponding Matplotlib backend is used,
3473 'tk'). If given, the corresponding Matplotlib backend is used,
3474 otherwise matplotlib's default (which you can override in your
3474 otherwise matplotlib's default (which you can override in your
3475 matplotlib config file) is used.
3475 matplotlib config file) is used.
3476
3476
3477 Examples
3477 Examples
3478 --------
3478 --------
3479 In this case, where the MPL default is TkAgg::
3479 In this case, where the MPL default is TkAgg::
3480
3480
3481 In [2]: %pylab
3481 In [2]: %pylab
3482
3482
3483 Welcome to pylab, a matplotlib-based Python environment.
3483 Welcome to pylab, a matplotlib-based Python environment.
3484 Backend in use: TkAgg
3484 Backend in use: TkAgg
3485 For more information, type 'help(pylab)'.
3485 For more information, type 'help(pylab)'.
3486
3486
3487 But you can explicitly request a different backend::
3487 But you can explicitly request a different backend::
3488
3488
3489 In [3]: %pylab qt
3489 In [3]: %pylab qt
3490
3490
3491 Welcome to pylab, a matplotlib-based Python environment.
3491 Welcome to pylab, a matplotlib-based Python environment.
3492 Backend in use: Qt4Agg
3492 Backend in use: Qt4Agg
3493 For more information, type 'help(pylab)'.
3493 For more information, type 'help(pylab)'.
3494 """
3494 """
3495
3495
3496 if Application.initialized():
3496 if Application.initialized():
3497 app = Application.instance()
3497 app = Application.instance()
3498 try:
3498 try:
3499 import_all_status = app.pylab_import_all
3499 import_all_status = app.pylab_import_all
3500 except AttributeError:
3500 except AttributeError:
3501 import_all_status = True
3501 import_all_status = True
3502 else:
3502 else:
3503 import_all_status = True
3503 import_all_status = True
3504
3504
3505 self.shell.enable_pylab(s,import_all=import_all_status)
3505 self.shell.enable_pylab(s,import_all=import_all_status)
3506
3506
3507 def magic_tb(self, s):
3507 def magic_tb(self, s):
3508 """Print the last traceback with the currently active exception mode.
3508 """Print the last traceback with the currently active exception mode.
3509
3509
3510 See %xmode for changing exception reporting modes."""
3510 See %xmode for changing exception reporting modes."""
3511 self.shell.showtraceback()
3511 self.shell.showtraceback()
3512
3512
3513 @skip_doctest
3513 @skip_doctest
3514 def magic_precision(self, s=''):
3514 def magic_precision(self, s=''):
3515 """Set floating point precision for pretty printing.
3515 """Set floating point precision for pretty printing.
3516
3516
3517 Can set either integer precision or a format string.
3517 Can set either integer precision or a format string.
3518
3518
3519 If numpy has been imported and precision is an int,
3519 If numpy has been imported and precision is an int,
3520 numpy display precision will also be set, via ``numpy.set_printoptions``.
3520 numpy display precision will also be set, via ``numpy.set_printoptions``.
3521
3521
3522 If no argument is given, defaults will be restored.
3522 If no argument is given, defaults will be restored.
3523
3523
3524 Examples
3524 Examples
3525 --------
3525 --------
3526 ::
3526 ::
3527
3527
3528 In [1]: from math import pi
3528 In [1]: from math import pi
3529
3529
3530 In [2]: %precision 3
3530 In [2]: %precision 3
3531 Out[2]: u'%.3f'
3531 Out[2]: u'%.3f'
3532
3532
3533 In [3]: pi
3533 In [3]: pi
3534 Out[3]: 3.142
3534 Out[3]: 3.142
3535
3535
3536 In [4]: %precision %i
3536 In [4]: %precision %i
3537 Out[4]: u'%i'
3537 Out[4]: u'%i'
3538
3538
3539 In [5]: pi
3539 In [5]: pi
3540 Out[5]: 3
3540 Out[5]: 3
3541
3541
3542 In [6]: %precision %e
3542 In [6]: %precision %e
3543 Out[6]: u'%e'
3543 Out[6]: u'%e'
3544
3544
3545 In [7]: pi**10
3545 In [7]: pi**10
3546 Out[7]: 9.364805e+04
3546 Out[7]: 9.364805e+04
3547
3547
3548 In [8]: %precision
3548 In [8]: %precision
3549 Out[8]: u'%r'
3549 Out[8]: u'%r'
3550
3550
3551 In [9]: pi**10
3551 In [9]: pi**10
3552 Out[9]: 93648.047476082982
3552 Out[9]: 93648.047476082982
3553
3553
3554 """
3554 """
3555
3555
3556 ptformatter = self.shell.display_formatter.formatters['text/plain']
3556 ptformatter = self.shell.display_formatter.formatters['text/plain']
3557 ptformatter.float_precision = s
3557 ptformatter.float_precision = s
3558 return ptformatter.float_format
3558 return ptformatter.float_format
3559
3559
3560
3560
3561 @magic_arguments.magic_arguments()
3561 @magic_arguments.magic_arguments()
3562 @magic_arguments.argument(
3562 @magic_arguments.argument(
3563 '-e', '--export', action='store_true', default=False,
3563 '-e', '--export', action='store_true', default=False,
3564 help='Export IPython history as a notebook. The filename argument '
3564 help='Export IPython history as a notebook. The filename argument '
3565 'is used to specify the notebook name and format. For example '
3565 'is used to specify the notebook name and format. For example '
3566 'a filename of notebook.ipynb will result in a notebook name '
3566 'a filename of notebook.ipynb will result in a notebook name '
3567 'of "notebook" and a format of "xml". Likewise using a ".json" '
3567 'of "notebook" and a format of "xml". Likewise using a ".json" '
3568 'or ".py" file extension will write the notebook in the json '
3568 'or ".py" file extension will write the notebook in the json '
3569 'or py formats.'
3569 'or py formats.'
3570 )
3570 )
3571 @magic_arguments.argument(
3571 @magic_arguments.argument(
3572 '-f', '--format',
3572 '-f', '--format',
3573 help='Convert an existing IPython notebook to a new format. This option '
3573 help='Convert an existing IPython notebook to a new format. This option '
3574 'specifies the new format and can have the values: xml, json, py. '
3574 'specifies the new format and can have the values: xml, json, py. '
3575 'The target filename is choosen automatically based on the new '
3575 'The target filename is choosen automatically based on the new '
3576 'format. The filename argument gives the name of the source file.'
3576 'format. The filename argument gives the name of the source file.'
3577 )
3577 )
3578 @magic_arguments.argument(
3578 @magic_arguments.argument(
3579 'filename', type=unicode,
3579 'filename', type=unicode,
3580 help='Notebook name or filename'
3580 help='Notebook name or filename'
3581 )
3581 )
3582 def magic_notebook(self, s):
3582 def magic_notebook(self, s):
3583 """Export and convert IPython notebooks.
3583 """Export and convert IPython notebooks.
3584
3584
3585 This function can export the current IPython history to a notebook file
3585 This function can export the current IPython history to a notebook file
3586 or can convert an existing notebook file into a different format. For
3586 or can convert an existing notebook file into a different format. For
3587 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3587 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3588 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3588 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3589 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3589 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3590 formats include (json/ipynb, py).
3590 formats include (json/ipynb, py).
3591 """
3591 """
3592 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3592 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3593
3593
3594 from IPython.nbformat import current
3594 from IPython.nbformat import current
3595 args.filename = unquote_filename(args.filename)
3595 args.filename = unquote_filename(args.filename)
3596 if args.export:
3596 if args.export:
3597 fname, name, format = current.parse_filename(args.filename)
3597 fname, name, format = current.parse_filename(args.filename)
3598 cells = []
3598 cells = []
3599 hist = list(self.history_manager.get_range())
3599 hist = list(self.history_manager.get_range())
3600 for session, prompt_number, input in hist[:-1]:
3600 for session, prompt_number, input in hist[:-1]:
3601 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3601 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3602 worksheet = current.new_worksheet(cells=cells)
3602 worksheet = current.new_worksheet(cells=cells)
3603 nb = current.new_notebook(name=name,worksheets=[worksheet])
3603 nb = current.new_notebook(name=name,worksheets=[worksheet])
3604 with open(fname, 'w') as f:
3604 with open(fname, 'w') as f:
3605 current.write(nb, f, format);
3605 current.write(nb, f, format);
3606 elif args.format is not None:
3606 elif args.format is not None:
3607 old_fname, old_name, old_format = current.parse_filename(args.filename)
3607 old_fname, old_name, old_format = current.parse_filename(args.filename)
3608 new_format = args.format
3608 new_format = args.format
3609 if new_format == u'xml':
3609 if new_format == u'xml':
3610 raise ValueError('Notebooks cannot be written as xml.')
3610 raise ValueError('Notebooks cannot be written as xml.')
3611 elif new_format == u'ipynb' or new_format == u'json':
3611 elif new_format == u'ipynb' or new_format == u'json':
3612 new_fname = old_name + u'.ipynb'
3612 new_fname = old_name + u'.ipynb'
3613 new_format = u'json'
3613 new_format = u'json'
3614 elif new_format == u'py':
3614 elif new_format == u'py':
3615 new_fname = old_name + u'.py'
3615 new_fname = old_name + u'.py'
3616 else:
3616 else:
3617 raise ValueError('Invalid notebook format: %s' % new_format)
3617 raise ValueError('Invalid notebook format: %s' % new_format)
3618 with open(old_fname, 'r') as f:
3618 with open(old_fname, 'r') as f:
3619 s = f.read()
3619 s = f.read()
3620 try:
3620 try:
3621 nb = current.reads(s, old_format)
3621 nb = current.reads(s, old_format)
3622 except:
3622 except:
3623 nb = current.reads(s, u'xml')
3623 nb = current.reads(s, u'xml')
3624 with open(new_fname, 'w') as f:
3624 with open(new_fname, 'w') as f:
3625 current.write(nb, f, new_format)
3625 current.write(nb, f, new_format)
3626
3626
3627 def magic_config(self, s):
3627 def magic_config(self, s):
3628 """configure IPython
3628 """configure IPython
3629
3629
3630 %config Class[.trait=value]
3630 %config Class[.trait=value]
3631
3631
3632 This magic exposes most of the IPython config system. Any
3632 This magic exposes most of the IPython config system. Any
3633 Configurable class should be able to be configured with the simple
3633 Configurable class should be able to be configured with the simple
3634 line::
3634 line::
3635
3635
3636 %config Class.trait=value
3636 %config Class.trait=value
3637
3637
3638 Where `value` will be resolved in the user's namespace, if it is an
3638 Where `value` will be resolved in the user's namespace, if it is an
3639 expression or variable name.
3639 expression or variable name.
3640
3640
3641 Examples
3641 Examples
3642 --------
3642 --------
3643
3643
3644 To see what classes are availabe for config, pass no arguments::
3644 To see what classes are availabe for config, pass no arguments::
3645
3645
3646 In [1]: %config
3646 In [1]: %config
3647 Available objects for config:
3647 Available objects for config:
3648 TerminalInteractiveShell
3648 TerminalInteractiveShell
3649 HistoryManager
3649 HistoryManager
3650 PrefilterManager
3650 PrefilterManager
3651 AliasManager
3651 AliasManager
3652 IPCompleter
3652 IPCompleter
3653 DisplayFormatter
3653 DisplayFormatter
3654
3654
3655 To view what is configurable on a given class, just pass the class name::
3655 To view what is configurable on a given class, just pass the class name::
3656
3656
3657 In [2]: %config IPCompleter
3657 In [2]: %config IPCompleter
3658 IPCompleter options
3658 IPCompleter options
3659 -----------------
3659 -----------------
3660 IPCompleter.omit__names=<Enum>
3661 Current: 2
3662 Choices: (0, 1, 2)
3663 Instruct the completer to omit private method names
3664 Specifically, when completing on ``object.<tab>``.
3665 When 2 [default]: all names that start with '_' will be excluded.
3666 When 1: all 'magic' names (``__foo__``) will be excluded.
3667 When 0: nothing will be excluded.
3668 IPCompleter.merge_completions=<CBool>
3669 Current: True
3670 Whether to merge completion results into a single list
3671 If False, only the completion results from the first non-empty completer
3672 will be returned.
3660 IPCompleter.greedy=<CBool>
3673 IPCompleter.greedy=<CBool>
3661 Current: False
3674 Current: False
3662 Activate greedy completion
3675 Activate greedy completion
3663 This will enable completion on elements of lists, results of function calls,
3676 This will enable completion on elements of lists, results of function calls,
3664 etc., but can be unsafe because the code is actually evaluated on TAB.
3677 etc., but can be unsafe because the code is actually evaluated on TAB.
3665
3678
3666 but the real use is in setting values::
3679 but the real use is in setting values::
3667
3680
3668 In [3]: %config IPCompleter.greedy = True
3681 In [3]: %config IPCompleter.greedy = True
3669
3682
3670 and these values are read from the user_ns if they are variables::
3683 and these values are read from the user_ns if they are variables::
3671
3684
3672 In [4]: feeling_greedy=False
3685 In [4]: feeling_greedy=False
3673
3686
3674 In [5]: %config IPCompleter.greedy = feeling_greedy
3687 In [5]: %config IPCompleter.greedy = feeling_greedy
3675
3688
3676 """
3689 """
3677 from IPython.config.loader import Config
3690 from IPython.config.loader import Config
3678 # get list of class names for configurables that have someting to configure:
3691 # get list of class names for configurables that have someting to configure:
3679 classnames = [ c.__class__.__name__ for c in self.configurables if c.__class__.class_traits(config=True) ]
3692 classnames = [ c.__class__.__name__ for c in self.configurables if c.__class__.class_traits(config=True) ]
3680 line = s.strip()
3693 line = s.strip()
3681 if not line:
3694 if not line:
3682 # print available configurable names
3695 # print available configurable names
3683 print "Available objects for config:"
3696 print "Available objects for config:"
3684 for name in classnames:
3697 for name in classnames:
3685 print " ", name
3698 print " ", name
3686 return
3699 return
3687 elif line in classnames:
3700 elif line in classnames:
3688 # `%config TerminalInteractiveShell` will print trait info for
3701 # `%config TerminalInteractiveShell` will print trait info for
3689 # TerminalInteractiveShell
3702 # TerminalInteractiveShell
3690 c = self.configurables[classnames.index(line)]
3703 c = self.configurables[classnames.index(line)]
3691 cls = c.__class__
3704 cls = c.__class__
3692 help = cls.class_get_help(c)
3705 help = cls.class_get_help(c)
3693 # strip leading '--' from cl-args:
3706 # strip leading '--' from cl-args:
3694 help = re.sub(r'^\-\-', '', help, flags=re.MULTILINE)
3707 help = re.sub(r'^\-\-', '', help, flags=re.MULTILINE)
3695 print help
3708 print help
3696 return
3709 return
3697 elif '=' not in line:
3710 elif '=' not in line:
3698 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3711 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3699
3712
3700
3713
3701 # otherwise, assume we are setting configurables.
3714 # otherwise, assume we are setting configurables.
3702 # leave quotes on args when splitting, because we want
3715 # leave quotes on args when splitting, because we want
3703 # unquoted args to eval in user_ns
3716 # unquoted args to eval in user_ns
3704 cfg = Config()
3717 cfg = Config()
3705 exec "cfg."+line in locals(), self.user_ns
3718 exec "cfg."+line in locals(), self.user_ns
3706
3719
3707 for configurable in self.configurables:
3720 for configurable in self.configurables:
3708 try:
3721 try:
3709 configurable.update_config(cfg)
3722 configurable.update_config(cfg)
3710 except Exception as e:
3723 except Exception as e:
3711 error(e)
3724 error(e)
3712
3725
3713 # end Magic
3726 # end Magic
@@ -1,207 +1,232 b''
1 """Tests for the IPython tab-completion machinery.
1 """Tests for the IPython tab-completion machinery.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # stdlib
7 # stdlib
8 import os
8 import os
9 import sys
9 import sys
10 import unittest
10 import unittest
11
11
12 # third party
12 # third party
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 # our own packages
15 # our own packages
16 from IPython.config.loader import Config
16 from IPython.core import completer
17 from IPython.core import completer
17 from IPython.external.decorators import knownfailureif
18 from IPython.external.decorators import knownfailureif
18 from IPython.utils.tempdir import TemporaryDirectory
19 from IPython.utils.tempdir import TemporaryDirectory
19 from IPython.utils.generics import complete_object
20 from IPython.utils.generics import complete_object
20
21
21 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
22 # Test functions
23 # Test functions
23 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
24 def test_protect_filename():
25 def test_protect_filename():
25 pairs = [ ('abc','abc'),
26 pairs = [ ('abc','abc'),
26 (' abc',r'\ abc'),
27 (' abc',r'\ abc'),
27 ('a bc',r'a\ bc'),
28 ('a bc',r'a\ bc'),
28 ('a bc',r'a\ \ bc'),
29 ('a bc',r'a\ \ bc'),
29 (' bc',r'\ \ bc'),
30 (' bc',r'\ \ bc'),
30 ]
31 ]
31 # On posix, we also protect parens and other special characters
32 # On posix, we also protect parens and other special characters
32 if sys.platform != 'win32':
33 if sys.platform != 'win32':
33 pairs.extend( [('a(bc',r'a\(bc'),
34 pairs.extend( [('a(bc',r'a\(bc'),
34 ('a)bc',r'a\)bc'),
35 ('a)bc',r'a\)bc'),
35 ('a( )bc',r'a\(\ \)bc'),
36 ('a( )bc',r'a\(\ \)bc'),
36 ('a[1]bc', r'a\[1\]bc'),
37 ('a[1]bc', r'a\[1\]bc'),
37 ('a{1}bc', r'a\{1\}bc'),
38 ('a{1}bc', r'a\{1\}bc'),
38 ('a#bc', r'a\#bc'),
39 ('a#bc', r'a\#bc'),
39 ('a?bc', r'a\?bc'),
40 ('a?bc', r'a\?bc'),
40 ('a=bc', r'a\=bc'),
41 ('a=bc', r'a\=bc'),
41 ('a\\bc', r'a\\bc'),
42 ('a\\bc', r'a\\bc'),
42 ('a|bc', r'a\|bc'),
43 ('a|bc', r'a\|bc'),
43 ('a;bc', r'a\;bc'),
44 ('a;bc', r'a\;bc'),
44 ('a:bc', r'a\:bc'),
45 ('a:bc', r'a\:bc'),
45 ("a'bc", r"a\'bc"),
46 ("a'bc", r"a\'bc"),
46 ('a*bc', r'a\*bc'),
47 ('a*bc', r'a\*bc'),
47 ('a"bc', r'a\"bc'),
48 ('a"bc', r'a\"bc'),
48 ('a^bc', r'a\^bc'),
49 ('a^bc', r'a\^bc'),
49 ('a&bc', r'a\&bc'),
50 ('a&bc', r'a\&bc'),
50 ] )
51 ] )
51 # run the actual tests
52 # run the actual tests
52 for s1, s2 in pairs:
53 for s1, s2 in pairs:
53 s1p = completer.protect_filename(s1)
54 s1p = completer.protect_filename(s1)
54 nt.assert_equals(s1p, s2)
55 nt.assert_equals(s1p, s2)
55
56
56
57
57 def check_line_split(splitter, test_specs):
58 def check_line_split(splitter, test_specs):
58 for part1, part2, split in test_specs:
59 for part1, part2, split in test_specs:
59 cursor_pos = len(part1)
60 cursor_pos = len(part1)
60 line = part1+part2
61 line = part1+part2
61 out = splitter.split_line(line, cursor_pos)
62 out = splitter.split_line(line, cursor_pos)
62 nt.assert_equal(out, split)
63 nt.assert_equal(out, split)
63
64
64
65
65 def test_line_split():
66 def test_line_split():
66 """Basice line splitter test with default specs."""
67 """Basice line splitter test with default specs."""
67 sp = completer.CompletionSplitter()
68 sp = completer.CompletionSplitter()
68 # The format of the test specs is: part1, part2, expected answer. Parts 1
69 # The format of the test specs is: part1, part2, expected answer. Parts 1
69 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
70 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
70 # was at the end of part1. So an empty part2 represents someone hitting
71 # was at the end of part1. So an empty part2 represents someone hitting
71 # tab at the end of the line, the most common case.
72 # tab at the end of the line, the most common case.
72 t = [('run some/scrip', '', 'some/scrip'),
73 t = [('run some/scrip', '', 'some/scrip'),
73 ('run scripts/er', 'ror.py foo', 'scripts/er'),
74 ('run scripts/er', 'ror.py foo', 'scripts/er'),
74 ('echo $HOM', '', 'HOM'),
75 ('echo $HOM', '', 'HOM'),
75 ('print sys.pa', '', 'sys.pa'),
76 ('print sys.pa', '', 'sys.pa'),
76 ('print(sys.pa', '', 'sys.pa'),
77 ('print(sys.pa', '', 'sys.pa'),
77 ("execfile('scripts/er", '', 'scripts/er'),
78 ("execfile('scripts/er", '', 'scripts/er'),
78 ('a[x.', '', 'x.'),
79 ('a[x.', '', 'x.'),
79 ('a[x.', 'y', 'x.'),
80 ('a[x.', 'y', 'x.'),
80 ('cd "some_file/', '', 'some_file/'),
81 ('cd "some_file/', '', 'some_file/'),
81 ]
82 ]
82 check_line_split(sp, t)
83 check_line_split(sp, t)
83 # Ensure splitting works OK with unicode by re-running the tests with
84 # Ensure splitting works OK with unicode by re-running the tests with
84 # all inputs turned into unicode
85 # all inputs turned into unicode
85 check_line_split(sp, [ map(unicode, p) for p in t] )
86 check_line_split(sp, [ map(unicode, p) for p in t] )
86
87
87 def test_custom_completion_error():
88 def test_custom_completion_error():
88 """Test that errors from custom attribute completers are silenced."""
89 """Test that errors from custom attribute completers are silenced."""
89 ip = get_ipython()
90 ip = get_ipython()
90 class A(object): pass
91 class A(object): pass
91 ip.user_ns['a'] = A()
92 ip.user_ns['a'] = A()
92
93
93 @complete_object.when_type(A)
94 @complete_object.when_type(A)
94 def complete_A(a, existing_completions):
95 def complete_A(a, existing_completions):
95 raise TypeError("this should be silenced")
96 raise TypeError("this should be silenced")
96
97
97 ip.complete("a.")
98 ip.complete("a.")
98
99
99
100
100 def test_unicode_completions():
101 def test_unicode_completions():
101 ip = get_ipython()
102 ip = get_ipython()
102 # Some strings that trigger different types of completion. Check them both
103 # Some strings that trigger different types of completion. Check them both
103 # in str and unicode forms
104 # in str and unicode forms
104 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
105 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
105 for t in s + map(unicode, s):
106 for t in s + map(unicode, s):
106 # We don't need to check exact completion values (they may change
107 # We don't need to check exact completion values (they may change
107 # depending on the state of the namespace, but at least no exceptions
108 # depending on the state of the namespace, but at least no exceptions
108 # should be thrown and the return value should be a pair of text, list
109 # should be thrown and the return value should be a pair of text, list
109 # values.
110 # values.
110 text, matches = ip.complete(t)
111 text, matches = ip.complete(t)
111 nt.assert_true(isinstance(text, basestring))
112 nt.assert_true(isinstance(text, basestring))
112 nt.assert_true(isinstance(matches, list))
113 nt.assert_true(isinstance(matches, list))
113
114
114
115
115 class CompletionSplitterTestCase(unittest.TestCase):
116 class CompletionSplitterTestCase(unittest.TestCase):
116 def setUp(self):
117 def setUp(self):
117 self.sp = completer.CompletionSplitter()
118 self.sp = completer.CompletionSplitter()
118
119
119 def test_delim_setting(self):
120 def test_delim_setting(self):
120 self.sp.set_delims(' ')
121 self.sp.set_delims(' ')
121 nt.assert_equal(self.sp.get_delims(), ' ')
122 nt.assert_equal(self.sp.get_delims(), ' ')
122 nt.assert_equal(self.sp._delim_expr, '[\ ]')
123 nt.assert_equal(self.sp._delim_expr, '[\ ]')
123
124
124 def test_spaces(self):
125 def test_spaces(self):
125 """Test with only spaces as split chars."""
126 """Test with only spaces as split chars."""
126 self.sp.delims = ' '
127 self.sp.delims = ' '
127 t = [('foo', '', 'foo'),
128 t = [('foo', '', 'foo'),
128 ('run foo', '', 'foo'),
129 ('run foo', '', 'foo'),
129 ('run foo', 'bar', 'foo'),
130 ('run foo', 'bar', 'foo'),
130 ]
131 ]
131 check_line_split(self.sp, t)
132 check_line_split(self.sp, t)
132
133
133
134
134 def test_has_open_quotes1():
135 def test_has_open_quotes1():
135 for s in ["'", "'''", "'hi' '"]:
136 for s in ["'", "'''", "'hi' '"]:
136 nt.assert_equal(completer.has_open_quotes(s), "'")
137 nt.assert_equal(completer.has_open_quotes(s), "'")
137
138
138
139
139 def test_has_open_quotes2():
140 def test_has_open_quotes2():
140 for s in ['"', '"""', '"hi" "']:
141 for s in ['"', '"""', '"hi" "']:
141 nt.assert_equal(completer.has_open_quotes(s), '"')
142 nt.assert_equal(completer.has_open_quotes(s), '"')
142
143
143
144
144 def test_has_open_quotes3():
145 def test_has_open_quotes3():
145 for s in ["''", "''' '''", "'hi' 'ipython'"]:
146 for s in ["''", "''' '''", "'hi' 'ipython'"]:
146 nt.assert_false(completer.has_open_quotes(s))
147 nt.assert_false(completer.has_open_quotes(s))
147
148
148
149
149 def test_has_open_quotes4():
150 def test_has_open_quotes4():
150 for s in ['""', '""" """', '"hi" "ipython"']:
151 for s in ['""', '""" """', '"hi" "ipython"']:
151 nt.assert_false(completer.has_open_quotes(s))
152 nt.assert_false(completer.has_open_quotes(s))
152
153
153 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
154 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
154 def test_abspath_file_completions():
155 def test_abspath_file_completions():
155 ip = get_ipython()
156 ip = get_ipython()
156 with TemporaryDirectory() as tmpdir:
157 with TemporaryDirectory() as tmpdir:
157 prefix = os.path.join(tmpdir, 'foo')
158 prefix = os.path.join(tmpdir, 'foo')
158 suffixes = map(str, [1,2])
159 suffixes = map(str, [1,2])
159 names = [prefix+s for s in suffixes]
160 names = [prefix+s for s in suffixes]
160 for n in names:
161 for n in names:
161 open(n, 'w').close()
162 open(n, 'w').close()
162
163
163 # Check simple completion
164 # Check simple completion
164 c = ip.complete(prefix)[1]
165 c = ip.complete(prefix)[1]
165 nt.assert_equal(c, names)
166 nt.assert_equal(c, names)
166
167
167 # Now check with a function call
168 # Now check with a function call
168 cmd = 'a = f("%s' % prefix
169 cmd = 'a = f("%s' % prefix
169 c = ip.complete(prefix, cmd)[1]
170 c = ip.complete(prefix, cmd)[1]
170 comp = [prefix+s for s in suffixes]
171 comp = [prefix+s for s in suffixes]
171 nt.assert_equal(c, comp)
172 nt.assert_equal(c, comp)
172
173
173 def test_local_file_completions():
174 def test_local_file_completions():
174 ip = get_ipython()
175 ip = get_ipython()
175 cwd = os.getcwdu()
176 cwd = os.getcwdu()
176 try:
177 try:
177 with TemporaryDirectory() as tmpdir:
178 with TemporaryDirectory() as tmpdir:
178 os.chdir(tmpdir)
179 os.chdir(tmpdir)
179 prefix = './foo'
180 prefix = './foo'
180 suffixes = map(str, [1,2])
181 suffixes = map(str, [1,2])
181 names = [prefix+s for s in suffixes]
182 names = [prefix+s for s in suffixes]
182 for n in names:
183 for n in names:
183 open(n, 'w').close()
184 open(n, 'w').close()
184
185
185 # Check simple completion
186 # Check simple completion
186 c = ip.complete(prefix)[1]
187 c = ip.complete(prefix)[1]
187 nt.assert_equal(c, names)
188 nt.assert_equal(c, names)
188
189
189 # Now check with a function call
190 # Now check with a function call
190 cmd = 'a = f("%s' % prefix
191 cmd = 'a = f("%s' % prefix
191 c = ip.complete(prefix, cmd)[1]
192 c = ip.complete(prefix, cmd)[1]
192 comp = [prefix+s for s in suffixes]
193 comp = [prefix+s for s in suffixes]
193 nt.assert_equal(c, comp)
194 nt.assert_equal(c, comp)
194 finally:
195 finally:
195 # prevent failures from making chdir stick
196 # prevent failures from making chdir stick
196 os.chdir(cwd)
197 os.chdir(cwd)
197
198
198 def test_greedy_completions():
199 def test_greedy_completions():
199 ip = get_ipython()
200 ip = get_ipython()
200 ip.Completer.greedy = False
201 ip.Completer.greedy = False
201 ip.ex('a=range(5)')
202 ip.ex('a=range(5)')
202 _,c = ip.complete('.',line='a[0].')
203 _,c = ip.complete('.',line='a[0].')
203 nt.assert_false('a[0].real' in c, "Shouldn't have completed on a[0]: %s"%c)
204 nt.assert_false('a[0].real' in c, "Shouldn't have completed on a[0]: %s"%c)
204 ip.Completer.greedy = True
205 ip.Completer.greedy = True
205 _,c = ip.complete('.',line='a[0].')
206 _,c = ip.complete('.',line='a[0].')
206 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
207 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
207
208
209 def test_omit__names():
210 # also happens to test IPCompleter as a configurable
211 ip = get_ipython()
212 ip._hidden_attr = 1
213 c = ip.Completer
214 ip.ex('ip=get_ipython()')
215 cfg = Config()
216 cfg.IPCompleter.omit__names = 0
217 c.update_config(cfg)
218 s,matches = c.complete('ip.')
219 nt.assert_true('ip.__str__' in matches)
220 nt.assert_true('ip._hidden_attr' in matches)
221 cfg.IPCompleter.omit__names = 1
222 c.update_config(cfg)
223 s,matches = c.complete('ip.')
224 nt.assert_false('ip.__str__' in matches)
225 nt.assert_true('ip._hidden_attr' in matches)
226 cfg.IPCompleter.omit__names = 2
227 c.update_config(cfg)
228 s,matches = c.complete('ip.')
229 nt.assert_false('ip.__str__' in matches)
230 nt.assert_false('ip._hidden_attr' in matches)
231 del ip._hidden_attr
232 No newline at end of file
@@ -1,396 +1,396 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors
7 Authors
8 -------
8 -------
9
9
10 * Brian Granger
10 * Brian Granger
11 * Fernando Perez
11 * Fernando Perez
12 * Min Ragan-Kelley
12 * Min Ragan-Kelley
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2010 The IPython Development Team
16 # Copyright (C) 2008-2010 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import absolute_import
26 from __future__ import absolute_import
27
27
28 import logging
28 import logging
29 import os
29 import os
30 import sys
30 import sys
31
31
32 from IPython.config.loader import (
32 from IPython.config.loader import (
33 Config, PyFileConfigLoader, ConfigFileNotFound
33 Config, PyFileConfigLoader, ConfigFileNotFound
34 )
34 )
35 from IPython.config.application import boolean_flag, catch_config_error
35 from IPython.config.application import boolean_flag, catch_config_error
36 from IPython.core import release
36 from IPython.core import release
37 from IPython.core import usage
37 from IPython.core import usage
38 from IPython.core.completer import Completer
38 from IPython.core.completer import IPCompleter
39 from IPython.core.crashhandler import CrashHandler
39 from IPython.core.crashhandler import CrashHandler
40 from IPython.core.formatters import PlainTextFormatter
40 from IPython.core.formatters import PlainTextFormatter
41 from IPython.core.application import (
41 from IPython.core.application import (
42 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
42 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
43 )
43 )
44 from IPython.core.shellapp import (
44 from IPython.core.shellapp import (
45 InteractiveShellApp, shell_flags, shell_aliases
45 InteractiveShellApp, shell_flags, shell_aliases
46 )
46 )
47 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
47 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
48 from IPython.lib import inputhook
48 from IPython.lib import inputhook
49 from IPython.utils import warn
49 from IPython.utils import warn
50 from IPython.utils.path import get_ipython_dir, check_for_old_config
50 from IPython.utils.path import get_ipython_dir, check_for_old_config
51 from IPython.utils.traitlets import (
51 from IPython.utils.traitlets import (
52 Bool, List, Dict, CaselessStrEnum
52 Bool, List, Dict, CaselessStrEnum
53 )
53 )
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Globals, utilities and helpers
56 # Globals, utilities and helpers
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59 #: The default config file name for this application.
59 #: The default config file name for this application.
60 default_config_file_name = u'ipython_config.py'
60 default_config_file_name = u'ipython_config.py'
61
61
62 _examples = """
62 _examples = """
63 ipython --pylab # start in pylab mode
63 ipython --pylab # start in pylab mode
64 ipython --pylab=qt # start in pylab mode with the qt4 backend
64 ipython --pylab=qt # start in pylab mode with the qt4 backend
65 ipython --log-level=DEBUG # set logging to DEBUG
65 ipython --log-level=DEBUG # set logging to DEBUG
66 ipython --profile=foo # start with profile foo
66 ipython --profile=foo # start with profile foo
67
67
68 ipython qtconsole # start the qtconsole GUI application
68 ipython qtconsole # start the qtconsole GUI application
69 ipython qtconsole -h # show the help string for the qtconsole subcmd
69 ipython qtconsole -h # show the help string for the qtconsole subcmd
70
70
71 ipython profile create foo # create profile foo w/ default config files
71 ipython profile create foo # create profile foo w/ default config files
72 ipython profile -h # show the help string for the profile subcmd
72 ipython profile -h # show the help string for the profile subcmd
73 """
73 """
74
74
75 #-----------------------------------------------------------------------------
75 #-----------------------------------------------------------------------------
76 # Crash handler for this application
76 # Crash handler for this application
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78
78
79 class IPAppCrashHandler(CrashHandler):
79 class IPAppCrashHandler(CrashHandler):
80 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
80 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
81
81
82 def __init__(self, app):
82 def __init__(self, app):
83 contact_name = release.authors['Fernando'][0]
83 contact_name = release.authors['Fernando'][0]
84 contact_email = release.authors['Fernando'][1]
84 contact_email = release.authors['Fernando'][1]
85 bug_tracker = 'http://github.com/ipython/ipython/issues'
85 bug_tracker = 'http://github.com/ipython/ipython/issues'
86 super(IPAppCrashHandler,self).__init__(
86 super(IPAppCrashHandler,self).__init__(
87 app, contact_name, contact_email, bug_tracker
87 app, contact_name, contact_email, bug_tracker
88 )
88 )
89
89
90 def make_report(self,traceback):
90 def make_report(self,traceback):
91 """Return a string containing a crash report."""
91 """Return a string containing a crash report."""
92
92
93 sec_sep = self.section_sep
93 sec_sep = self.section_sep
94 # Start with parent report
94 # Start with parent report
95 report = [super(IPAppCrashHandler, self).make_report(traceback)]
95 report = [super(IPAppCrashHandler, self).make_report(traceback)]
96 # Add interactive-specific info we may have
96 # Add interactive-specific info we may have
97 rpt_add = report.append
97 rpt_add = report.append
98 try:
98 try:
99 rpt_add(sec_sep+"History of session input:")
99 rpt_add(sec_sep+"History of session input:")
100 for line in self.app.shell.user_ns['_ih']:
100 for line in self.app.shell.user_ns['_ih']:
101 rpt_add(line)
101 rpt_add(line)
102 rpt_add('\n*** Last line of input (may not be in above history):\n')
102 rpt_add('\n*** Last line of input (may not be in above history):\n')
103 rpt_add(self.app.shell._last_input_line+'\n')
103 rpt_add(self.app.shell._last_input_line+'\n')
104 except:
104 except:
105 pass
105 pass
106
106
107 return ''.join(report)
107 return ''.join(report)
108
108
109 #-----------------------------------------------------------------------------
109 #-----------------------------------------------------------------------------
110 # Aliases and Flags
110 # Aliases and Flags
111 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
112 flags = dict(base_flags)
112 flags = dict(base_flags)
113 flags.update(shell_flags)
113 flags.update(shell_flags)
114 addflag = lambda *args: flags.update(boolean_flag(*args))
114 addflag = lambda *args: flags.update(boolean_flag(*args))
115 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
115 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
116 'Turn on auto editing of files with syntax errors.',
116 'Turn on auto editing of files with syntax errors.',
117 'Turn off auto editing of files with syntax errors.'
117 'Turn off auto editing of files with syntax errors.'
118 )
118 )
119 addflag('banner', 'TerminalIPythonApp.display_banner',
119 addflag('banner', 'TerminalIPythonApp.display_banner',
120 "Display a banner upon starting IPython.",
120 "Display a banner upon starting IPython.",
121 "Don't display a banner upon starting IPython."
121 "Don't display a banner upon starting IPython."
122 )
122 )
123 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
123 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
124 """Set to confirm when you try to exit IPython with an EOF (Control-D
124 """Set to confirm when you try to exit IPython with an EOF (Control-D
125 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
125 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
126 you can force a direct exit without any confirmation.""",
126 you can force a direct exit without any confirmation.""",
127 "Don't prompt the user when exiting."
127 "Don't prompt the user when exiting."
128 )
128 )
129 addflag('term-title', 'TerminalInteractiveShell.term_title',
129 addflag('term-title', 'TerminalInteractiveShell.term_title',
130 "Enable auto setting the terminal title.",
130 "Enable auto setting the terminal title.",
131 "Disable auto setting the terminal title."
131 "Disable auto setting the terminal title."
132 )
132 )
133 classic_config = Config()
133 classic_config = Config()
134 classic_config.InteractiveShell.cache_size = 0
134 classic_config.InteractiveShell.cache_size = 0
135 classic_config.PlainTextFormatter.pprint = False
135 classic_config.PlainTextFormatter.pprint = False
136 classic_config.InteractiveShell.prompt_in1 = '>>> '
136 classic_config.InteractiveShell.prompt_in1 = '>>> '
137 classic_config.InteractiveShell.prompt_in2 = '... '
137 classic_config.InteractiveShell.prompt_in2 = '... '
138 classic_config.InteractiveShell.prompt_out = ''
138 classic_config.InteractiveShell.prompt_out = ''
139 classic_config.InteractiveShell.separate_in = ''
139 classic_config.InteractiveShell.separate_in = ''
140 classic_config.InteractiveShell.separate_out = ''
140 classic_config.InteractiveShell.separate_out = ''
141 classic_config.InteractiveShell.separate_out2 = ''
141 classic_config.InteractiveShell.separate_out2 = ''
142 classic_config.InteractiveShell.colors = 'NoColor'
142 classic_config.InteractiveShell.colors = 'NoColor'
143 classic_config.InteractiveShell.xmode = 'Plain'
143 classic_config.InteractiveShell.xmode = 'Plain'
144
144
145 flags['classic']=(
145 flags['classic']=(
146 classic_config,
146 classic_config,
147 "Gives IPython a similar feel to the classic Python prompt."
147 "Gives IPython a similar feel to the classic Python prompt."
148 )
148 )
149 # # log doesn't make so much sense this way anymore
149 # # log doesn't make so much sense this way anymore
150 # paa('--log','-l',
150 # paa('--log','-l',
151 # action='store_true', dest='InteractiveShell.logstart',
151 # action='store_true', dest='InteractiveShell.logstart',
152 # help="Start logging to the default log file (./ipython_log.py).")
152 # help="Start logging to the default log file (./ipython_log.py).")
153 #
153 #
154 # # quick is harder to implement
154 # # quick is harder to implement
155 flags['quick']=(
155 flags['quick']=(
156 {'TerminalIPythonApp' : {'quick' : True}},
156 {'TerminalIPythonApp' : {'quick' : True}},
157 "Enable quick startup with no config files."
157 "Enable quick startup with no config files."
158 )
158 )
159
159
160 flags['i'] = (
160 flags['i'] = (
161 {'TerminalIPythonApp' : {'force_interact' : True}},
161 {'TerminalIPythonApp' : {'force_interact' : True}},
162 """If running code from the command line, become interactive afterwards.
162 """If running code from the command line, become interactive afterwards.
163 Note: can also be given simply as '-i.'"""
163 Note: can also be given simply as '-i.'"""
164 )
164 )
165 flags['pylab'] = (
165 flags['pylab'] = (
166 {'TerminalIPythonApp' : {'pylab' : 'auto'}},
166 {'TerminalIPythonApp' : {'pylab' : 'auto'}},
167 """Pre-load matplotlib and numpy for interactive use with
167 """Pre-load matplotlib and numpy for interactive use with
168 the default matplotlib backend."""
168 the default matplotlib backend."""
169 )
169 )
170
170
171 aliases = dict(base_aliases)
171 aliases = dict(base_aliases)
172 aliases.update(shell_aliases)
172 aliases.update(shell_aliases)
173
173
174 # it's possible we don't want short aliases for *all* of these:
174 # it's possible we don't want short aliases for *all* of these:
175 aliases.update(dict(
175 aliases.update(dict(
176 gui='TerminalIPythonApp.gui',
176 gui='TerminalIPythonApp.gui',
177 pylab='TerminalIPythonApp.pylab',
177 pylab='TerminalIPythonApp.pylab',
178 ))
178 ))
179
179
180 #-----------------------------------------------------------------------------
180 #-----------------------------------------------------------------------------
181 # Main classes and functions
181 # Main classes and functions
182 #-----------------------------------------------------------------------------
182 #-----------------------------------------------------------------------------
183
183
184 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
184 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
185 name = u'ipython'
185 name = u'ipython'
186 description = usage.cl_usage
186 description = usage.cl_usage
187 default_config_file_name = default_config_file_name
187 default_config_file_name = default_config_file_name
188 crash_handler_class = IPAppCrashHandler
188 crash_handler_class = IPAppCrashHandler
189 examples = _examples
189 examples = _examples
190
190
191 flags = Dict(flags)
191 flags = Dict(flags)
192 aliases = Dict(aliases)
192 aliases = Dict(aliases)
193 classes = List()
193 classes = List()
194 def _classes_default(self):
194 def _classes_default(self):
195 """This has to be in a method, for TerminalIPythonApp to be available."""
195 """This has to be in a method, for TerminalIPythonApp to be available."""
196 return [
196 return [
197 InteractiveShellApp, # ShellApp comes before TerminalApp, because
197 InteractiveShellApp, # ShellApp comes before TerminalApp, because
198 self.__class__, # it will also affect subclasses (e.g. QtConsole)
198 self.__class__, # it will also affect subclasses (e.g. QtConsole)
199 TerminalInteractiveShell,
199 TerminalInteractiveShell,
200 ProfileDir,
200 ProfileDir,
201 PlainTextFormatter,
201 PlainTextFormatter,
202 Completer,
202 IPCompleter,
203 ]
203 ]
204
204
205 subcommands = Dict(dict(
205 subcommands = Dict(dict(
206 qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
206 qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
207 """Launch the IPython Qt Console."""
207 """Launch the IPython Qt Console."""
208 ),
208 ),
209 notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp',
209 notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp',
210 """Launch the IPython HTML Notebook Server"""
210 """Launch the IPython HTML Notebook Server"""
211 ),
211 ),
212 profile = ("IPython.core.profileapp.ProfileApp",
212 profile = ("IPython.core.profileapp.ProfileApp",
213 "Create and manage IPython profiles."
213 "Create and manage IPython profiles."
214 ),
214 ),
215 kernel = ("IPython.zmq.ipkernel.IPKernelApp",
215 kernel = ("IPython.zmq.ipkernel.IPKernelApp",
216 "Start a kernel without an attached frontend."
216 "Start a kernel without an attached frontend."
217 ),
217 ),
218 ))
218 ))
219
219
220 # *do* autocreate requested profile, but don't create the config file.
220 # *do* autocreate requested profile, but don't create the config file.
221 auto_create=Bool(True)
221 auto_create=Bool(True)
222 # configurables
222 # configurables
223 ignore_old_config=Bool(False, config=True,
223 ignore_old_config=Bool(False, config=True,
224 help="Suppress warning messages about legacy config files"
224 help="Suppress warning messages about legacy config files"
225 )
225 )
226 quick = Bool(False, config=True,
226 quick = Bool(False, config=True,
227 help="""Start IPython quickly by skipping the loading of config files."""
227 help="""Start IPython quickly by skipping the loading of config files."""
228 )
228 )
229 def _quick_changed(self, name, old, new):
229 def _quick_changed(self, name, old, new):
230 if new:
230 if new:
231 self.load_config_file = lambda *a, **kw: None
231 self.load_config_file = lambda *a, **kw: None
232 self.ignore_old_config=True
232 self.ignore_old_config=True
233
233
234 gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet'), config=True,
234 gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet'), config=True,
235 help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet')."
235 help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet')."
236 )
236 )
237 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'],
237 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'],
238 config=True,
238 config=True,
239 help="""Pre-load matplotlib and numpy for interactive use,
239 help="""Pre-load matplotlib and numpy for interactive use,
240 selecting a particular matplotlib backend and loop integration.
240 selecting a particular matplotlib backend and loop integration.
241 """
241 """
242 )
242 )
243 display_banner = Bool(True, config=True,
243 display_banner = Bool(True, config=True,
244 help="Whether to display a banner upon starting IPython."
244 help="Whether to display a banner upon starting IPython."
245 )
245 )
246
246
247 # if there is code of files to run from the cmd line, don't interact
247 # if there is code of files to run from the cmd line, don't interact
248 # unless the --i flag (App.force_interact) is true.
248 # unless the --i flag (App.force_interact) is true.
249 force_interact = Bool(False, config=True,
249 force_interact = Bool(False, config=True,
250 help="""If a command or file is given via the command-line,
250 help="""If a command or file is given via the command-line,
251 e.g. 'ipython foo.py"""
251 e.g. 'ipython foo.py"""
252 )
252 )
253 def _force_interact_changed(self, name, old, new):
253 def _force_interact_changed(self, name, old, new):
254 if new:
254 if new:
255 self.interact = True
255 self.interact = True
256
256
257 def _file_to_run_changed(self, name, old, new):
257 def _file_to_run_changed(self, name, old, new):
258 if new and not self.force_interact:
258 if new and not self.force_interact:
259 self.interact = False
259 self.interact = False
260 _code_to_run_changed = _file_to_run_changed
260 _code_to_run_changed = _file_to_run_changed
261
261
262 # internal, not-configurable
262 # internal, not-configurable
263 interact=Bool(True)
263 interact=Bool(True)
264
264
265
265
266 def parse_command_line(self, argv=None):
266 def parse_command_line(self, argv=None):
267 """override to allow old '-pylab' flag with deprecation warning"""
267 """override to allow old '-pylab' flag with deprecation warning"""
268
268
269 argv = sys.argv[1:] if argv is None else argv
269 argv = sys.argv[1:] if argv is None else argv
270
270
271 if '-pylab' in argv:
271 if '-pylab' in argv:
272 # deprecated `-pylab` given,
272 # deprecated `-pylab` given,
273 # warn and transform into current syntax
273 # warn and transform into current syntax
274 argv = argv[:] # copy, don't clobber
274 argv = argv[:] # copy, don't clobber
275 idx = argv.index('-pylab')
275 idx = argv.index('-pylab')
276 warn.warn("`-pylab` flag has been deprecated.\n"
276 warn.warn("`-pylab` flag has been deprecated.\n"
277 " Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
277 " Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
278 sub = '--pylab'
278 sub = '--pylab'
279 if len(argv) > idx+1:
279 if len(argv) > idx+1:
280 # check for gui arg, as in '-pylab qt'
280 # check for gui arg, as in '-pylab qt'
281 gui = argv[idx+1]
281 gui = argv[idx+1]
282 if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
282 if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
283 sub = '--pylab='+gui
283 sub = '--pylab='+gui
284 argv.pop(idx+1)
284 argv.pop(idx+1)
285 argv[idx] = sub
285 argv[idx] = sub
286
286
287 return super(TerminalIPythonApp, self).parse_command_line(argv)
287 return super(TerminalIPythonApp, self).parse_command_line(argv)
288
288
289 @catch_config_error
289 @catch_config_error
290 def initialize(self, argv=None):
290 def initialize(self, argv=None):
291 """Do actions after construct, but before starting the app."""
291 """Do actions after construct, but before starting the app."""
292 super(TerminalIPythonApp, self).initialize(argv)
292 super(TerminalIPythonApp, self).initialize(argv)
293 if self.subapp is not None:
293 if self.subapp is not None:
294 # don't bother initializing further, starting subapp
294 # don't bother initializing further, starting subapp
295 return
295 return
296 if not self.ignore_old_config:
296 if not self.ignore_old_config:
297 check_for_old_config(self.ipython_dir)
297 check_for_old_config(self.ipython_dir)
298 # print self.extra_args
298 # print self.extra_args
299 if self.extra_args:
299 if self.extra_args:
300 self.file_to_run = self.extra_args[0]
300 self.file_to_run = self.extra_args[0]
301 # create the shell
301 # create the shell
302 self.init_shell()
302 self.init_shell()
303 # and draw the banner
303 # and draw the banner
304 self.init_banner()
304 self.init_banner()
305 # Now a variety of things that happen after the banner is printed.
305 # Now a variety of things that happen after the banner is printed.
306 self.init_gui_pylab()
306 self.init_gui_pylab()
307 self.init_extensions()
307 self.init_extensions()
308 self.init_code()
308 self.init_code()
309
309
310 def init_shell(self):
310 def init_shell(self):
311 """initialize the InteractiveShell instance"""
311 """initialize the InteractiveShell instance"""
312 # I am a little hesitant to put these into InteractiveShell itself.
312 # I am a little hesitant to put these into InteractiveShell itself.
313 # But that might be the place for them
313 # But that might be the place for them
314 sys.path.insert(0, '')
314 sys.path.insert(0, '')
315
315
316 # Create an InteractiveShell instance.
316 # Create an InteractiveShell instance.
317 # shell.display_banner should always be False for the terminal
317 # shell.display_banner should always be False for the terminal
318 # based app, because we call shell.show_banner() by hand below
318 # based app, because we call shell.show_banner() by hand below
319 # so the banner shows *before* all extension loading stuff.
319 # so the banner shows *before* all extension loading stuff.
320 self.shell = TerminalInteractiveShell.instance(config=self.config,
320 self.shell = TerminalInteractiveShell.instance(config=self.config,
321 display_banner=False, profile_dir=self.profile_dir,
321 display_banner=False, profile_dir=self.profile_dir,
322 ipython_dir=self.ipython_dir)
322 ipython_dir=self.ipython_dir)
323
323
324 def init_banner(self):
324 def init_banner(self):
325 """optionally display the banner"""
325 """optionally display the banner"""
326 if self.display_banner and self.interact:
326 if self.display_banner and self.interact:
327 self.shell.show_banner()
327 self.shell.show_banner()
328 # Make sure there is a space below the banner.
328 # Make sure there is a space below the banner.
329 if self.log_level <= logging.INFO: print
329 if self.log_level <= logging.INFO: print
330
330
331
331
332 def init_gui_pylab(self):
332 def init_gui_pylab(self):
333 """Enable GUI event loop integration, taking pylab into account."""
333 """Enable GUI event loop integration, taking pylab into account."""
334 gui = self.gui
334 gui = self.gui
335
335
336 # Using `pylab` will also require gui activation, though which toolkit
336 # Using `pylab` will also require gui activation, though which toolkit
337 # to use may be chosen automatically based on mpl configuration.
337 # to use may be chosen automatically based on mpl configuration.
338 if self.pylab:
338 if self.pylab:
339 activate = self.shell.enable_pylab
339 activate = self.shell.enable_pylab
340 if self.pylab == 'auto':
340 if self.pylab == 'auto':
341 gui = None
341 gui = None
342 else:
342 else:
343 gui = self.pylab
343 gui = self.pylab
344 else:
344 else:
345 # Enable only GUI integration, no pylab
345 # Enable only GUI integration, no pylab
346 activate = inputhook.enable_gui
346 activate = inputhook.enable_gui
347
347
348 if gui or self.pylab:
348 if gui or self.pylab:
349 try:
349 try:
350 self.log.info("Enabling GUI event loop integration, "
350 self.log.info("Enabling GUI event loop integration, "
351 "toolkit=%s, pylab=%s" % (gui, self.pylab) )
351 "toolkit=%s, pylab=%s" % (gui, self.pylab) )
352 if self.pylab:
352 if self.pylab:
353 activate(gui, import_all=self.pylab_import_all)
353 activate(gui, import_all=self.pylab_import_all)
354 else:
354 else:
355 activate(gui)
355 activate(gui)
356 except:
356 except:
357 self.log.warn("Error in enabling GUI event loop integration:")
357 self.log.warn("Error in enabling GUI event loop integration:")
358 self.shell.showtraceback()
358 self.shell.showtraceback()
359
359
360 def start(self):
360 def start(self):
361 if self.subapp is not None:
361 if self.subapp is not None:
362 return self.subapp.start()
362 return self.subapp.start()
363 # perform any prexec steps:
363 # perform any prexec steps:
364 if self.interact:
364 if self.interact:
365 self.log.debug("Starting IPython's mainloop...")
365 self.log.debug("Starting IPython's mainloop...")
366 self.shell.mainloop()
366 self.shell.mainloop()
367 else:
367 else:
368 self.log.debug("IPython not interactive...")
368 self.log.debug("IPython not interactive...")
369
369
370
370
371 def load_default_config(ipython_dir=None):
371 def load_default_config(ipython_dir=None):
372 """Load the default config file from the default ipython_dir.
372 """Load the default config file from the default ipython_dir.
373
373
374 This is useful for embedded shells.
374 This is useful for embedded shells.
375 """
375 """
376 if ipython_dir is None:
376 if ipython_dir is None:
377 ipython_dir = get_ipython_dir()
377 ipython_dir = get_ipython_dir()
378 profile_dir = os.path.join(ipython_dir, 'profile_default')
378 profile_dir = os.path.join(ipython_dir, 'profile_default')
379 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
379 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
380 try:
380 try:
381 config = cl.load_config()
381 config = cl.load_config()
382 except ConfigFileNotFound:
382 except ConfigFileNotFound:
383 # no config found
383 # no config found
384 config = Config()
384 config = Config()
385 return config
385 return config
386
386
387
387
388 def launch_new_instance():
388 def launch_new_instance():
389 """Create and run a full blown IPython instance"""
389 """Create and run a full blown IPython instance"""
390 app = TerminalIPythonApp.instance()
390 app = TerminalIPythonApp.instance()
391 app.initialize()
391 app.initialize()
392 app.start()
392 app.start()
393
393
394
394
395 if __name__ == '__main__':
395 if __name__ == '__main__':
396 launch_new_instance()
396 launch_new_instance()
General Comments 0
You need to be logged in to leave comments. Login now