##// END OF EJS Templates
the __future__ is now.
Paul Ivanov -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,152 +1,151 b''
1 1 # encoding: utf-8
2 2 """
3 3 IPython: tools for interactive and parallel computing in Python.
4 4
5 5 http://ipython.org
6 6 """
7 7 #-----------------------------------------------------------------------------
8 8 # Copyright (c) 2008-2011, IPython Development Team.
9 9 # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
10 10 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
11 11 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
12 12 #
13 13 # Distributed under the terms of the Modified BSD License.
14 14 #
15 15 # The full license is in the file COPYING.txt, distributed with this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 from __future__ import absolute_import
22 21
23 22 import os
24 23 import sys
25 24
26 25 #-----------------------------------------------------------------------------
27 26 # Setup everything
28 27 #-----------------------------------------------------------------------------
29 28
30 29 # Don't forget to also update setup.py when this changes!
31 30 if sys.version_info < (3,3):
32 31 raise ImportError(
33 32 """
34 33 IPython 6.0+ does not support Python 2.6, 2.7, 3.0, 3.1, or 3.2.
35 34 When using Python 2.7, please install IPython 5.x LTS Long Term Support version.
36 35 Beginning with IPython 6.0, Python 3.3 and above is required.
37 36
38 37 See IPython `README.rst` file for more information:
39 38
40 39 https://github.com/ipython/ipython/blob/master/README.rst
41 40
42 41 """)
43 42
44 43 # Make it easy to import extensions - they are always directly on pythonpath.
45 44 # Therefore, non-IPython modules can be added to extensions directory.
46 45 # This should probably be in ipapp.py.
47 46 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
48 47
49 48 #-----------------------------------------------------------------------------
50 49 # Setup the top level names
51 50 #-----------------------------------------------------------------------------
52 51
53 52 from .core.getipython import get_ipython
54 53 from .core import release
55 54 from .core.application import Application
56 55 from .terminal.embed import embed
57 56
58 57 from .core.interactiveshell import InteractiveShell
59 58 from .testing import test
60 59 from .utils.sysinfo import sys_info
61 60 from .utils.frame import extract_module_locals
62 61
63 62 # Release data
64 63 __author__ = '%s <%s>' % (release.author, release.author_email)
65 64 __license__ = release.license
66 65 __version__ = release.version
67 66 version_info = release.version_info
68 67
69 68 def embed_kernel(module=None, local_ns=None, **kwargs):
70 69 """Embed and start an IPython kernel in a given scope.
71 70
72 71 If you don't want the kernel to initialize the namespace
73 72 from the scope of the surrounding function,
74 73 and/or you want to load full IPython configuration,
75 74 you probably want `IPython.start_kernel()` instead.
76 75
77 76 Parameters
78 77 ----------
79 78 module : ModuleType, optional
80 79 The module to load into IPython globals (default: caller)
81 80 local_ns : dict, optional
82 81 The namespace to load into IPython user namespace (default: caller)
83 82
84 83 kwargs : various, optional
85 84 Further keyword args are relayed to the IPKernelApp constructor,
86 85 allowing configuration of the Kernel. Will only have an effect
87 86 on the first embed_kernel call for a given process.
88 87 """
89 88
90 89 (caller_module, caller_locals) = extract_module_locals(1)
91 90 if module is None:
92 91 module = caller_module
93 92 if local_ns is None:
94 93 local_ns = caller_locals
95 94
96 95 # Only import .zmq when we really need it
97 96 from ipykernel.embed import embed_kernel as real_embed_kernel
98 97 real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
99 98
100 99 def start_ipython(argv=None, **kwargs):
101 100 """Launch a normal IPython instance (as opposed to embedded)
102 101
103 102 `IPython.embed()` puts a shell in a particular calling scope,
104 103 such as a function or method for debugging purposes,
105 104 which is often not desirable.
106 105
107 106 `start_ipython()` does full, regular IPython initialization,
108 107 including loading startup files, configuration, etc.
109 108 much of which is skipped by `embed()`.
110 109
111 110 This is a public API method, and will survive implementation changes.
112 111
113 112 Parameters
114 113 ----------
115 114
116 115 argv : list or None, optional
117 116 If unspecified or None, IPython will parse command-line options from sys.argv.
118 117 To prevent any command-line parsing, pass an empty list: `argv=[]`.
119 118 user_ns : dict, optional
120 119 specify this dictionary to initialize the IPython user namespace with particular values.
121 120 kwargs : various, optional
122 121 Any other kwargs will be passed to the Application constructor,
123 122 such as `config`.
124 123 """
125 124 from IPython.terminal.ipapp import launch_new_instance
126 125 return launch_new_instance(argv=argv, **kwargs)
127 126
128 127 def start_kernel(argv=None, **kwargs):
129 128 """Launch a normal IPython kernel instance (as opposed to embedded)
130 129
131 130 `IPython.embed_kernel()` puts a shell in a particular calling scope,
132 131 such as a function or method for debugging purposes,
133 132 which is often not desirable.
134 133
135 134 `start_kernel()` does full, regular IPython initialization,
136 135 including loading startup files, configuration, etc.
137 136 much of which is skipped by `embed()`.
138 137
139 138 Parameters
140 139 ----------
141 140
142 141 argv : list or None, optional
143 142 If unspecified or None, IPython will parse command-line options from sys.argv.
144 143 To prevent any command-line parsing, pass an empty list: `argv=[]`.
145 144 user_ns : dict, optional
146 145 specify this dictionary to initialize the IPython user namespace with particular values.
147 146 kwargs : various, optional
148 147 Any other kwargs will be passed to the Application constructor,
149 148 such as `config`.
150 149 """
151 150 from IPython.kernel.zmq.kernelapp import launch_new_instance
152 151 return launch_new_instance(argv=argv, **kwargs)
@@ -1,144 +1,143 b''
1 1 """Compiler tools with improved interactive support.
2 2
3 3 Provides compilation machinery similar to codeop, but with caching support so
4 4 we can provide interactive tracebacks.
5 5
6 6 Authors
7 7 -------
8 8 * Robert Kern
9 9 * Fernando Perez
10 10 * Thomas Kluyver
11 11 """
12 12
13 13 # Note: though it might be more natural to name this module 'compiler', that
14 14 # name is in the stdlib and name collisions with the stdlib tend to produce
15 15 # weird problems (often with third-party tools).
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Copyright (C) 2010-2011 The IPython Development Team.
19 19 #
20 20 # Distributed under the terms of the BSD License.
21 21 #
22 22 # The full license is in the file COPYING.txt, distributed with this software.
23 23 #-----------------------------------------------------------------------------
24 24
25 25 #-----------------------------------------------------------------------------
26 26 # Imports
27 27 #-----------------------------------------------------------------------------
28 from __future__ import print_function
29 28
30 29 # Stdlib imports
31 30 import __future__
32 31 from ast import PyCF_ONLY_AST
33 32 import codeop
34 33 import functools
35 34 import hashlib
36 35 import linecache
37 36 import operator
38 37 import time
39 38
40 39 #-----------------------------------------------------------------------------
41 40 # Constants
42 41 #-----------------------------------------------------------------------------
43 42
44 43 # Roughtly equal to PyCF_MASK | PyCF_MASK_OBSOLETE as defined in pythonrun.h,
45 44 # this is used as a bitmask to extract future-related code flags.
46 45 PyCF_MASK = functools.reduce(operator.or_,
47 46 (getattr(__future__, fname).compiler_flag
48 47 for fname in __future__.all_feature_names))
49 48
50 49 #-----------------------------------------------------------------------------
51 50 # Local utilities
52 51 #-----------------------------------------------------------------------------
53 52
54 53 def code_name(code, number=0):
55 54 """ Compute a (probably) unique name for code for caching.
56 55
57 56 This now expects code to be unicode.
58 57 """
59 58 hash_digest = hashlib.md5(code.encode("utf-8")).hexdigest()
60 59 # Include the number and 12 characters of the hash in the name. It's
61 60 # pretty much impossible that in a single session we'll have collisions
62 61 # even with truncated hashes, and the full one makes tracebacks too long
63 62 return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12])
64 63
65 64 #-----------------------------------------------------------------------------
66 65 # Classes and functions
67 66 #-----------------------------------------------------------------------------
68 67
69 68 class CachingCompiler(codeop.Compile):
70 69 """A compiler that caches code compiled from interactive statements.
71 70 """
72 71
73 72 def __init__(self):
74 73 codeop.Compile.__init__(self)
75 74
76 75 # This is ugly, but it must be done this way to allow multiple
77 76 # simultaneous ipython instances to coexist. Since Python itself
78 77 # directly accesses the data structures in the linecache module, and
79 78 # the cache therein is global, we must work with that data structure.
80 79 # We must hold a reference to the original checkcache routine and call
81 80 # that in our own check_cache() below, but the special IPython cache
82 81 # must also be shared by all IPython instances. If we were to hold
83 82 # separate caches (one in each CachingCompiler instance), any call made
84 83 # by Python itself to linecache.checkcache() would obliterate the
85 84 # cached data from the other IPython instances.
86 85 if not hasattr(linecache, '_ipython_cache'):
87 86 linecache._ipython_cache = {}
88 87 if not hasattr(linecache, '_checkcache_ori'):
89 88 linecache._checkcache_ori = linecache.checkcache
90 89 # Now, we must monkeypatch the linecache directly so that parts of the
91 90 # stdlib that call it outside our control go through our codepath
92 91 # (otherwise we'd lose our tracebacks).
93 92 linecache.checkcache = check_linecache_ipython
94 93
95 94 def ast_parse(self, source, filename='<unknown>', symbol='exec'):
96 95 """Parse code to an AST with the current compiler flags active.
97 96
98 97 Arguments are exactly the same as ast.parse (in the standard library),
99 98 and are passed to the built-in compile function."""
100 99 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
101 100
102 101 def reset_compiler_flags(self):
103 102 """Reset compiler flags to default state."""
104 103 # This value is copied from codeop.Compile.__init__, so if that ever
105 104 # changes, it will need to be updated.
106 105 self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
107 106
108 107 @property
109 108 def compiler_flags(self):
110 109 """Flags currently active in the compilation process.
111 110 """
112 111 return self.flags
113 112
114 113 def cache(self, code, number=0):
115 114 """Make a name for a block of code, and cache the code.
116 115
117 116 Parameters
118 117 ----------
119 118 code : str
120 119 The Python source code to cache.
121 120 number : int
122 121 A number which forms part of the code's name. Used for the execution
123 122 counter.
124 123
125 124 Returns
126 125 -------
127 126 The name of the cached code (as a string). Pass this as the filename
128 127 argument to compilation, so that tracebacks are correctly hooked up.
129 128 """
130 129 name = code_name(code, number)
131 130 entry = (len(code), time.time(),
132 131 [line+'\n' for line in code.splitlines()], name)
133 132 linecache.cache[name] = entry
134 133 linecache._ipython_cache[name] = entry
135 134 return name
136 135
137 136 def check_linecache_ipython(*args):
138 137 """Call linecache.checkcache() safely protecting our cached values.
139 138 """
140 139 # First call the orignal checkcache as intended
141 140 linecache._checkcache_ori(*args)
142 141 # Then, update back the cache with our data, so that tracebacks related
143 142 # to our compiled codes can be produced.
144 143 linecache.cache.update(linecache._ipython_cache)
@@ -1,1237 +1,1236 b''
1 1 # encoding: utf-8
2 2 """Word completion for IPython.
3 3
4 4 This module started as fork of the rlcompleter module in the Python standard
5 5 library. The original enhancements made to rlcompleter have been sent
6 6 upstream and were accepted as of Python 2.3,
7 7
8 8 """
9 9
10 10 # Copyright (c) IPython Development Team.
11 11 # Distributed under the terms of the Modified BSD License.
12 12 #
13 13 # Some of this code originated from rlcompleter in the Python standard library
14 14 # Copyright (C) 2001 Python Software Foundation, www.python.org
15 15
16 from __future__ import print_function
17 16
18 17 import __main__
19 18 import glob
20 19 import inspect
21 20 import itertools
22 21 import keyword
23 22 import os
24 23 import re
25 24 import sys
26 25 import unicodedata
27 26 import string
28 27 import warnings
29 28 from importlib import import_module
30 29
31 30 from traitlets.config.configurable import Configurable
32 31 from IPython.core.error import TryNext
33 32 from IPython.core.inputsplitter import ESC_MAGIC
34 33 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
35 34 from IPython.utils import generics
36 35 from IPython.utils.decorators import undoc
37 36 from IPython.utils.dir2 import dir2, get_real_method
38 37 from IPython.utils.process import arg_split
39 38 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
40 39 from traitlets import Bool, Enum, observe
41 40
42 41 from functools import wraps
43 42
44 43 #-----------------------------------------------------------------------------
45 44 # Globals
46 45 #-----------------------------------------------------------------------------
47 46
48 47 # Public API
49 48 __all__ = ['Completer','IPCompleter']
50 49
51 50 if sys.platform == 'win32':
52 51 PROTECTABLES = ' '
53 52 else:
54 53 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
55 54
56 55
57 56 #-----------------------------------------------------------------------------
58 57 # Work around BUG decorators.
59 58 #-----------------------------------------------------------------------------
60 59
61 60 def _strip_single_trailing_space(complete):
62 61 """
63 62 This is a workaround for a weird IPython/Prompt_toolkit behavior,
64 63 that can be removed once we rely on a slightly more recent prompt_toolkit
65 64 version (likely > 1.0.3). So this can likely be removed in IPython 6.0
66 65
67 66 cf https://github.com/ipython/ipython/issues/9658
68 67 and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328
69 68
70 69 The bug is due to the fact that in PTK the completer will reinvoke itself
71 70 after trying to completer to the longuest common prefix of all the
72 71 completions, unless only one completion is available.
73 72
74 73 This logic is faulty if the completion ends with space, which can happen in
75 74 case like::
76 75
77 76 from foo import im<ta>
78 77
79 78 which only matching completion is `import `. Note the leading space at the
80 79 end. So leaving a space at the end is a reasonable request, but for now
81 80 we'll strip it.
82 81 """
83 82
84 83 @wraps(complete)
85 84 def comp(*args, **kwargs):
86 85 text, matches = complete(*args, **kwargs)
87 86 if len(matches) == 1:
88 87 return text, [matches[0].rstrip()]
89 88 return text, matches
90 89
91 90 return comp
92 91
93 92
94 93
95 94 #-----------------------------------------------------------------------------
96 95 # Main functions and classes
97 96 #-----------------------------------------------------------------------------
98 97
99 98 def has_open_quotes(s):
100 99 """Return whether a string has open quotes.
101 100
102 101 This simply counts whether the number of quote characters of either type in
103 102 the string is odd.
104 103
105 104 Returns
106 105 -------
107 106 If there is an open quote, the quote character is returned. Else, return
108 107 False.
109 108 """
110 109 # We check " first, then ', so complex cases with nested quotes will get
111 110 # the " to take precedence.
112 111 if s.count('"') % 2:
113 112 return '"'
114 113 elif s.count("'") % 2:
115 114 return "'"
116 115 else:
117 116 return False
118 117
119 118
120 119 def protect_filename(s):
121 120 """Escape a string to protect certain characters."""
122 121 if set(s) & set(PROTECTABLES):
123 122 if sys.platform == "win32":
124 123 return '"' + s + '"'
125 124 else:
126 125 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
127 126 else:
128 127 return s
129 128
130 129
131 130 def expand_user(path):
132 131 """Expand '~'-style usernames in strings.
133 132
134 133 This is similar to :func:`os.path.expanduser`, but it computes and returns
135 134 extra information that will be useful if the input was being used in
136 135 computing completions, and you wish to return the completions with the
137 136 original '~' instead of its expanded value.
138 137
139 138 Parameters
140 139 ----------
141 140 path : str
142 141 String to be expanded. If no ~ is present, the output is the same as the
143 142 input.
144 143
145 144 Returns
146 145 -------
147 146 newpath : str
148 147 Result of ~ expansion in the input path.
149 148 tilde_expand : bool
150 149 Whether any expansion was performed or not.
151 150 tilde_val : str
152 151 The value that ~ was replaced with.
153 152 """
154 153 # Default values
155 154 tilde_expand = False
156 155 tilde_val = ''
157 156 newpath = path
158 157
159 158 if path.startswith('~'):
160 159 tilde_expand = True
161 160 rest = len(path)-1
162 161 newpath = os.path.expanduser(path)
163 162 if rest:
164 163 tilde_val = newpath[:-rest]
165 164 else:
166 165 tilde_val = newpath
167 166
168 167 return newpath, tilde_expand, tilde_val
169 168
170 169
171 170 def compress_user(path, tilde_expand, tilde_val):
172 171 """Does the opposite of expand_user, with its outputs.
173 172 """
174 173 if tilde_expand:
175 174 return path.replace(tilde_val, '~')
176 175 else:
177 176 return path
178 177
179 178
180 179 def completions_sorting_key(word):
181 180 """key for sorting completions
182 181
183 182 This does several things:
184 183
185 184 - Lowercase all completions, so they are sorted alphabetically with
186 185 upper and lower case words mingled
187 186 - Demote any completions starting with underscores to the end
188 187 - Insert any %magic and %%cellmagic completions in the alphabetical order
189 188 by their name
190 189 """
191 190 # Case insensitive sort
192 191 word = word.lower()
193 192
194 193 prio1, prio2 = 0, 0
195 194
196 195 if word.startswith('__'):
197 196 prio1 = 2
198 197 elif word.startswith('_'):
199 198 prio1 = 1
200 199
201 200 if word.endswith('='):
202 201 prio1 = -1
203 202
204 203 if word.startswith('%%'):
205 204 # If there's another % in there, this is something else, so leave it alone
206 205 if not "%" in word[2:]:
207 206 word = word[2:]
208 207 prio2 = 2
209 208 elif word.startswith('%'):
210 209 if not "%" in word[1:]:
211 210 word = word[1:]
212 211 prio2 = 1
213 212
214 213 return prio1, word, prio2
215 214
216 215
217 216 @undoc
218 217 class Bunch(object): pass
219 218
220 219
221 220 if sys.platform == 'win32':
222 221 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
223 222 else:
224 223 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
225 224
226 225 GREEDY_DELIMS = ' =\r\n'
227 226
228 227
229 228 class CompletionSplitter(object):
230 229 """An object to split an input line in a manner similar to readline.
231 230
232 231 By having our own implementation, we can expose readline-like completion in
233 232 a uniform manner to all frontends. This object only needs to be given the
234 233 line of text to be split and the cursor position on said line, and it
235 234 returns the 'word' to be completed on at the cursor after splitting the
236 235 entire line.
237 236
238 237 What characters are used as splitting delimiters can be controlled by
239 238 setting the `delims` attribute (this is a property that internally
240 239 automatically builds the necessary regular expression)"""
241 240
242 241 # Private interface
243 242
244 243 # A string of delimiter characters. The default value makes sense for
245 244 # IPython's most typical usage patterns.
246 245 _delims = DELIMS
247 246
248 247 # The expression (a normal string) to be compiled into a regular expression
249 248 # for actual splitting. We store it as an attribute mostly for ease of
250 249 # debugging, since this type of code can be so tricky to debug.
251 250 _delim_expr = None
252 251
253 252 # The regular expression that does the actual splitting
254 253 _delim_re = None
255 254
256 255 def __init__(self, delims=None):
257 256 delims = CompletionSplitter._delims if delims is None else delims
258 257 self.delims = delims
259 258
260 259 @property
261 260 def delims(self):
262 261 """Return the string of delimiter characters."""
263 262 return self._delims
264 263
265 264 @delims.setter
266 265 def delims(self, delims):
267 266 """Set the delimiters for line splitting."""
268 267 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
269 268 self._delim_re = re.compile(expr)
270 269 self._delims = delims
271 270 self._delim_expr = expr
272 271
273 272 def split_line(self, line, cursor_pos=None):
274 273 """Split a line of text with a cursor at the given position.
275 274 """
276 275 l = line if cursor_pos is None else line[:cursor_pos]
277 276 return self._delim_re.split(l)[-1]
278 277
279 278
280 279 class Completer(Configurable):
281 280
282 281 greedy = Bool(False,
283 282 help="""Activate greedy completion
284 283 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
285 284
286 285 This will enable completion on elements of lists, results of function calls, etc.,
287 286 but can be unsafe because the code is actually evaluated on TAB.
288 287 """
289 288 ).tag(config=True)
290 289
291 290
292 291 def __init__(self, namespace=None, global_namespace=None, **kwargs):
293 292 """Create a new completer for the command line.
294 293
295 294 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
296 295
297 296 If unspecified, the default namespace where completions are performed
298 297 is __main__ (technically, __main__.__dict__). Namespaces should be
299 298 given as dictionaries.
300 299
301 300 An optional second namespace can be given. This allows the completer
302 301 to handle cases where both the local and global scopes need to be
303 302 distinguished.
304 303
305 304 Completer instances should be used as the completion mechanism of
306 305 readline via the set_completer() call:
307 306
308 307 readline.set_completer(Completer(my_namespace).complete)
309 308 """
310 309
311 310 # Don't bind to namespace quite yet, but flag whether the user wants a
312 311 # specific namespace or to use __main__.__dict__. This will allow us
313 312 # to bind to __main__.__dict__ at completion time, not now.
314 313 if namespace is None:
315 314 self.use_main_ns = 1
316 315 else:
317 316 self.use_main_ns = 0
318 317 self.namespace = namespace
319 318
320 319 # The global namespace, if given, can be bound directly
321 320 if global_namespace is None:
322 321 self.global_namespace = {}
323 322 else:
324 323 self.global_namespace = global_namespace
325 324
326 325 super(Completer, self).__init__(**kwargs)
327 326
328 327 def complete(self, text, state):
329 328 """Return the next possible completion for 'text'.
330 329
331 330 This is called successively with state == 0, 1, 2, ... until it
332 331 returns None. The completion should begin with 'text'.
333 332
334 333 """
335 334 if self.use_main_ns:
336 335 self.namespace = __main__.__dict__
337 336
338 337 if state == 0:
339 338 if "." in text:
340 339 self.matches = self.attr_matches(text)
341 340 else:
342 341 self.matches = self.global_matches(text)
343 342 try:
344 343 return self.matches[state]
345 344 except IndexError:
346 345 return None
347 346
348 347 def global_matches(self, text):
349 348 """Compute matches when text is a simple name.
350 349
351 350 Return a list of all keywords, built-in functions and names currently
352 351 defined in self.namespace or self.global_namespace that match.
353 352
354 353 """
355 354 matches = []
356 355 match_append = matches.append
357 356 n = len(text)
358 357 for lst in [keyword.kwlist,
359 358 builtin_mod.__dict__.keys(),
360 359 self.namespace.keys(),
361 360 self.global_namespace.keys()]:
362 361 for word in lst:
363 362 if word[:n] == text and word != "__builtins__":
364 363 match_append(word)
365 364 return [cast_unicode_py2(m) for m in matches]
366 365
367 366 def attr_matches(self, text):
368 367 """Compute matches when text contains a dot.
369 368
370 369 Assuming the text is of the form NAME.NAME....[NAME], and is
371 370 evaluatable in self.namespace or self.global_namespace, it will be
372 371 evaluated and its attributes (as revealed by dir()) are used as
373 372 possible completions. (For class instances, class members are are
374 373 also considered.)
375 374
376 375 WARNING: this can still invoke arbitrary C code, if an object
377 376 with a __getattr__ hook is evaluated.
378 377
379 378 """
380 379
381 380 # Another option, seems to work great. Catches things like ''.<tab>
382 381 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
383 382
384 383 if m:
385 384 expr, attr = m.group(1, 3)
386 385 elif self.greedy:
387 386 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
388 387 if not m2:
389 388 return []
390 389 expr, attr = m2.group(1,2)
391 390 else:
392 391 return []
393 392
394 393 try:
395 394 obj = eval(expr, self.namespace)
396 395 except:
397 396 try:
398 397 obj = eval(expr, self.global_namespace)
399 398 except:
400 399 return []
401 400
402 401 if self.limit_to__all__ and hasattr(obj, '__all__'):
403 402 words = get__all__entries(obj)
404 403 else:
405 404 words = dir2(obj)
406 405
407 406 try:
408 407 words = generics.complete_object(obj, words)
409 408 except TryNext:
410 409 pass
411 410 except Exception:
412 411 # Silence errors from completion function
413 412 #raise # dbg
414 413 pass
415 414 # Build match list to return
416 415 n = len(attr)
417 416 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
418 417
419 418
420 419 def get__all__entries(obj):
421 420 """returns the strings in the __all__ attribute"""
422 421 try:
423 422 words = getattr(obj, '__all__')
424 423 except:
425 424 return []
426 425
427 426 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
428 427
429 428
430 429 def match_dict_keys(keys, prefix, delims):
431 430 """Used by dict_key_matches, matching the prefix to a list of keys"""
432 431 if not prefix:
433 432 return None, 0, [repr(k) for k in keys
434 433 if isinstance(k, (string_types, bytes))]
435 434 quote_match = re.search('["\']', prefix)
436 435 quote = quote_match.group()
437 436 try:
438 437 prefix_str = eval(prefix + quote, {})
439 438 except Exception:
440 439 return None, 0, []
441 440
442 441 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
443 442 token_match = re.search(pattern, prefix, re.UNICODE)
444 443 token_start = token_match.start()
445 444 token_prefix = token_match.group()
446 445
447 446 # TODO: support bytes in Py3k
448 447 matched = []
449 448 for key in keys:
450 449 try:
451 450 if not key.startswith(prefix_str):
452 451 continue
453 452 except (AttributeError, TypeError, UnicodeError):
454 453 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
455 454 continue
456 455
457 456 # reformat remainder of key to begin with prefix
458 457 rem = key[len(prefix_str):]
459 458 # force repr wrapped in '
460 459 rem_repr = repr(rem + '"')
461 460 if rem_repr.startswith('u') and prefix[0] not in 'uU':
462 461 # Found key is unicode, but prefix is Py2 string.
463 462 # Therefore attempt to interpret key as string.
464 463 try:
465 464 rem_repr = repr(rem.encode('ascii') + '"')
466 465 except UnicodeEncodeError:
467 466 continue
468 467
469 468 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
470 469 if quote == '"':
471 470 # The entered prefix is quoted with ",
472 471 # but the match is quoted with '.
473 472 # A contained " hence needs escaping for comparison:
474 473 rem_repr = rem_repr.replace('"', '\\"')
475 474
476 475 # then reinsert prefix from start of token
477 476 matched.append('%s%s' % (token_prefix, rem_repr))
478 477 return quote, token_start, matched
479 478
480 479
481 480 def _safe_isinstance(obj, module, class_name):
482 481 """Checks if obj is an instance of module.class_name if loaded
483 482 """
484 483 return (module in sys.modules and
485 484 isinstance(obj, getattr(import_module(module), class_name)))
486 485
487 486
488 487 def back_unicode_name_matches(text):
489 488 u"""Match unicode characters back to unicode name
490 489
491 490 This does ☃ -> \\snowman
492 491
493 492 Note that snowman is not a valid python3 combining character but will be expanded.
494 493 Though it will not recombine back to the snowman character by the completion machinery.
495 494
496 495 This will not either back-complete standard sequences like \\n, \\b ...
497 496
498 497 Used on Python 3 only.
499 498 """
500 499 if len(text)<2:
501 500 return u'', ()
502 501 maybe_slash = text[-2]
503 502 if maybe_slash != '\\':
504 503 return u'', ()
505 504
506 505 char = text[-1]
507 506 # no expand on quote for completion in strings.
508 507 # nor backcomplete standard ascii keys
509 508 if char in string.ascii_letters or char in ['"',"'"]:
510 509 return u'', ()
511 510 try :
512 511 unic = unicodedata.name(char)
513 512 return '\\'+char,['\\'+unic]
514 513 except KeyError:
515 514 pass
516 515 return u'', ()
517 516
518 517 def back_latex_name_matches(text):
519 518 u"""Match latex characters back to unicode name
520 519
521 520 This does ->\\sqrt
522 521
523 522 Used on Python 3 only.
524 523 """
525 524 if len(text)<2:
526 525 return u'', ()
527 526 maybe_slash = text[-2]
528 527 if maybe_slash != '\\':
529 528 return u'', ()
530 529
531 530
532 531 char = text[-1]
533 532 # no expand on quote for completion in strings.
534 533 # nor backcomplete standard ascii keys
535 534 if char in string.ascii_letters or char in ['"',"'"]:
536 535 return u'', ()
537 536 try :
538 537 latex = reverse_latex_symbol[char]
539 538 # '\\' replace the \ as well
540 539 return '\\'+char,[latex]
541 540 except KeyError:
542 541 pass
543 542 return u'', ()
544 543
545 544
546 545 class IPCompleter(Completer):
547 546 """Extension of the completer class with IPython-specific features"""
548 547
549 548 @observe('greedy')
550 549 def _greedy_changed(self, change):
551 550 """update the splitter and readline delims when greedy is changed"""
552 551 if change['new']:
553 552 self.splitter.delims = GREEDY_DELIMS
554 553 else:
555 554 self.splitter.delims = DELIMS
556 555
557 556 merge_completions = Bool(True,
558 557 help="""Whether to merge completion results into a single list
559 558
560 559 If False, only the completion results from the first non-empty
561 560 completer will be returned.
562 561 """
563 562 ).tag(config=True)
564 563 omit__names = Enum((0,1,2), default_value=2,
565 564 help="""Instruct the completer to omit private method names
566 565
567 566 Specifically, when completing on ``object.<tab>``.
568 567
569 568 When 2 [default]: all names that start with '_' will be excluded.
570 569
571 570 When 1: all 'magic' names (``__foo__``) will be excluded.
572 571
573 572 When 0: nothing will be excluded.
574 573 """
575 574 ).tag(config=True)
576 575 limit_to__all__ = Bool(False,
577 576 help="""
578 577 DEPRECATED as of version 5.0.
579 578
580 579 Instruct the completer to use __all__ for the completion
581 580
582 581 Specifically, when completing on ``object.<tab>``.
583 582
584 583 When True: only those names in obj.__all__ will be included.
585 584
586 585 When False [default]: the __all__ attribute is ignored
587 586 """,
588 587 ).tag(config=True)
589 588
590 589 def __init__(self, shell=None, namespace=None, global_namespace=None,
591 590 use_readline=False, config=None, **kwargs):
592 591 """IPCompleter() -> completer
593 592
594 593 Return a completer object suitable for use by the readline library
595 594 via readline.set_completer().
596 595
597 596 Inputs:
598 597
599 598 - shell: a pointer to the ipython shell itself. This is needed
600 599 because this completer knows about magic functions, and those can
601 600 only be accessed via the ipython instance.
602 601
603 602 - namespace: an optional dict where completions are performed.
604 603
605 604 - global_namespace: secondary optional dict for completions, to
606 605 handle cases (such as IPython embedded inside functions) where
607 606 both Python scopes are visible.
608 607
609 608 use_readline : bool, optional
610 609 DEPRECATED, ignored.
611 610 """
612 611
613 612 self.magic_escape = ESC_MAGIC
614 613 self.splitter = CompletionSplitter()
615 614
616 615 if use_readline:
617 616 warnings.warn('The use_readline parameter is deprecated and ignored since IPython 6.0.',
618 617 DeprecationWarning, stacklevel=2)
619 618
620 619 # _greedy_changed() depends on splitter and readline being defined:
621 620 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
622 621 config=config, **kwargs)
623 622
624 623 # List where completion matches will be stored
625 624 self.matches = []
626 625 self.shell = shell
627 626 # Regexp to split filenames with spaces in them
628 627 self.space_name_re = re.compile(r'([^\\] )')
629 628 # Hold a local ref. to glob.glob for speed
630 629 self.glob = glob.glob
631 630
632 631 # Determine if we are running on 'dumb' terminals, like (X)Emacs
633 632 # buffers, to avoid completion problems.
634 633 term = os.environ.get('TERM','xterm')
635 634 self.dumb_terminal = term in ['dumb','emacs']
636 635
637 636 # Special handling of backslashes needed in win32 platforms
638 637 if sys.platform == "win32":
639 638 self.clean_glob = self._clean_glob_win32
640 639 else:
641 640 self.clean_glob = self._clean_glob
642 641
643 642 #regexp to parse docstring for function signature
644 643 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
645 644 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
646 645 #use this if positional argument name is also needed
647 646 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
648 647
649 648 # All active matcher routines for completion
650 649 self.matchers = [
651 650 self.python_matches,
652 651 self.file_matches,
653 652 self.magic_matches,
654 653 self.python_func_kw_matches,
655 654 self.dict_key_matches,
656 655 ]
657 656
658 657 # This is set externally by InteractiveShell
659 658 self.custom_completers = None
660 659
661 660 def all_completions(self, text):
662 661 """
663 662 Wrapper around the complete method for the benefit of emacs.
664 663 """
665 664 return self.complete(text)[1]
666 665
667 666 def _clean_glob(self, text):
668 667 return self.glob("%s*" % text)
669 668
670 669 def _clean_glob_win32(self,text):
671 670 return [f.replace("\\","/")
672 671 for f in self.glob("%s*" % text)]
673 672
674 673 def file_matches(self, text):
675 674 """Match filenames, expanding ~USER type strings.
676 675
677 676 Most of the seemingly convoluted logic in this completer is an
678 677 attempt to handle filenames with spaces in them. And yet it's not
679 678 quite perfect, because Python's readline doesn't expose all of the
680 679 GNU readline details needed for this to be done correctly.
681 680
682 681 For a filename with a space in it, the printed completions will be
683 682 only the parts after what's already been typed (instead of the
684 683 full completions, as is normally done). I don't think with the
685 684 current (as of Python 2.3) Python readline it's possible to do
686 685 better."""
687 686
688 687 # chars that require escaping with backslash - i.e. chars
689 688 # that readline treats incorrectly as delimiters, but we
690 689 # don't want to treat as delimiters in filename matching
691 690 # when escaped with backslash
692 691 if text.startswith('!'):
693 692 text = text[1:]
694 693 text_prefix = u'!'
695 694 else:
696 695 text_prefix = u''
697 696
698 697 text_until_cursor = self.text_until_cursor
699 698 # track strings with open quotes
700 699 open_quotes = has_open_quotes(text_until_cursor)
701 700
702 701 if '(' in text_until_cursor or '[' in text_until_cursor:
703 702 lsplit = text
704 703 else:
705 704 try:
706 705 # arg_split ~ shlex.split, but with unicode bugs fixed by us
707 706 lsplit = arg_split(text_until_cursor)[-1]
708 707 except ValueError:
709 708 # typically an unmatched ", or backslash without escaped char.
710 709 if open_quotes:
711 710 lsplit = text_until_cursor.split(open_quotes)[-1]
712 711 else:
713 712 return []
714 713 except IndexError:
715 714 # tab pressed on empty line
716 715 lsplit = ""
717 716
718 717 if not open_quotes and lsplit != protect_filename(lsplit):
719 718 # if protectables are found, do matching on the whole escaped name
720 719 has_protectables = True
721 720 text0,text = text,lsplit
722 721 else:
723 722 has_protectables = False
724 723 text = os.path.expanduser(text)
725 724
726 725 if text == "":
727 726 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
728 727
729 728 # Compute the matches from the filesystem
730 729 if sys.platform == 'win32':
731 730 m0 = self.clean_glob(text)
732 731 else:
733 732 m0 = self.clean_glob(text.replace('\\', ''))
734 733
735 734 if has_protectables:
736 735 # If we had protectables, we need to revert our changes to the
737 736 # beginning of filename so that we don't double-write the part
738 737 # of the filename we have so far
739 738 len_lsplit = len(lsplit)
740 739 matches = [text_prefix + text0 +
741 740 protect_filename(f[len_lsplit:]) for f in m0]
742 741 else:
743 742 if open_quotes:
744 743 # if we have a string with an open quote, we don't need to
745 744 # protect the names at all (and we _shouldn't_, as it
746 745 # would cause bugs when the filesystem call is made).
747 746 matches = m0
748 747 else:
749 748 matches = [text_prefix +
750 749 protect_filename(f) for f in m0]
751 750
752 751 # Mark directories in input list by appending '/' to their names.
753 752 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
754 753
755 754 def magic_matches(self, text):
756 755 """Match magics"""
757 756 # Get all shell magics now rather than statically, so magics loaded at
758 757 # runtime show up too.
759 758 lsm = self.shell.magics_manager.lsmagic()
760 759 line_magics = lsm['line']
761 760 cell_magics = lsm['cell']
762 761 pre = self.magic_escape
763 762 pre2 = pre+pre
764 763
765 764 # Completion logic:
766 765 # - user gives %%: only do cell magics
767 766 # - user gives %: do both line and cell magics
768 767 # - no prefix: do both
769 768 # In other words, line magics are skipped if the user gives %% explicitly
770 769 bare_text = text.lstrip(pre)
771 770 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
772 771 if not text.startswith(pre2):
773 772 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
774 773 return [cast_unicode_py2(c) for c in comp]
775 774
776 775
777 776 def python_matches(self, text):
778 777 """Match attributes or global python names"""
779 778 if "." in text:
780 779 try:
781 780 matches = self.attr_matches(text)
782 781 if text.endswith('.') and self.omit__names:
783 782 if self.omit__names == 1:
784 783 # true if txt is _not_ a __ name, false otherwise:
785 784 no__name = (lambda txt:
786 785 re.match(r'.*\.__.*?__',txt) is None)
787 786 else:
788 787 # true if txt is _not_ a _ name, false otherwise:
789 788 no__name = (lambda txt:
790 789 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
791 790 matches = filter(no__name, matches)
792 791 except NameError:
793 792 # catches <undefined attributes>.<tab>
794 793 matches = []
795 794 else:
796 795 matches = self.global_matches(text)
797 796 return matches
798 797
799 798 def _default_arguments_from_docstring(self, doc):
800 799 """Parse the first line of docstring for call signature.
801 800
802 801 Docstring should be of the form 'min(iterable[, key=func])\n'.
803 802 It can also parse cython docstring of the form
804 803 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
805 804 """
806 805 if doc is None:
807 806 return []
808 807
809 808 #care only the firstline
810 809 line = doc.lstrip().splitlines()[0]
811 810
812 811 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
813 812 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
814 813 sig = self.docstring_sig_re.search(line)
815 814 if sig is None:
816 815 return []
817 816 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
818 817 sig = sig.groups()[0].split(',')
819 818 ret = []
820 819 for s in sig:
821 820 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
822 821 ret += self.docstring_kwd_re.findall(s)
823 822 return ret
824 823
825 824 def _default_arguments(self, obj):
826 825 """Return the list of default arguments of obj if it is callable,
827 826 or empty list otherwise."""
828 827 call_obj = obj
829 828 ret = []
830 829 if inspect.isbuiltin(obj):
831 830 pass
832 831 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
833 832 if inspect.isclass(obj):
834 833 #for cython embededsignature=True the constructor docstring
835 834 #belongs to the object itself not __init__
836 835 ret += self._default_arguments_from_docstring(
837 836 getattr(obj, '__doc__', ''))
838 837 # for classes, check for __init__,__new__
839 838 call_obj = (getattr(obj, '__init__', None) or
840 839 getattr(obj, '__new__', None))
841 840 # for all others, check if they are __call__able
842 841 elif hasattr(obj, '__call__'):
843 842 call_obj = obj.__call__
844 843 ret += self._default_arguments_from_docstring(
845 844 getattr(call_obj, '__doc__', ''))
846 845
847 846 if PY3:
848 847 _keeps = (inspect.Parameter.KEYWORD_ONLY,
849 848 inspect.Parameter.POSITIONAL_OR_KEYWORD)
850 849 signature = inspect.signature
851 850 else:
852 851 import IPython.utils.signatures
853 852 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
854 853 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
855 854 signature = IPython.utils.signatures.signature
856 855
857 856 try:
858 857 sig = signature(call_obj)
859 858 ret.extend(k for k, v in sig.parameters.items() if
860 859 v.kind in _keeps)
861 860 except ValueError:
862 861 pass
863 862
864 863 return list(set(ret))
865 864
866 865 def python_func_kw_matches(self,text):
867 866 """Match named parameters (kwargs) of the last open function"""
868 867
869 868 if "." in text: # a parameter cannot be dotted
870 869 return []
871 870 try: regexp = self.__funcParamsRegex
872 871 except AttributeError:
873 872 regexp = self.__funcParamsRegex = re.compile(r'''
874 873 '.*?(?<!\\)' | # single quoted strings or
875 874 ".*?(?<!\\)" | # double quoted strings or
876 875 \w+ | # identifier
877 876 \S # other characters
878 877 ''', re.VERBOSE | re.DOTALL)
879 878 # 1. find the nearest identifier that comes before an unclosed
880 879 # parenthesis before the cursor
881 880 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
882 881 tokens = regexp.findall(self.text_until_cursor)
883 882 iterTokens = reversed(tokens); openPar = 0
884 883
885 884 for token in iterTokens:
886 885 if token == ')':
887 886 openPar -= 1
888 887 elif token == '(':
889 888 openPar += 1
890 889 if openPar > 0:
891 890 # found the last unclosed parenthesis
892 891 break
893 892 else:
894 893 return []
895 894 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
896 895 ids = []
897 896 isId = re.compile(r'\w+$').match
898 897
899 898 while True:
900 899 try:
901 900 ids.append(next(iterTokens))
902 901 if not isId(ids[-1]):
903 902 ids.pop(); break
904 903 if not next(iterTokens) == '.':
905 904 break
906 905 except StopIteration:
907 906 break
908 907
909 908 # Find all named arguments already assigned to, as to avoid suggesting
910 909 # them again
911 910 usedNamedArgs = set()
912 911 par_level = -1
913 912 for token, next_token in zip(tokens, tokens[1:]):
914 913 if token == '(':
915 914 par_level += 1
916 915 elif token == ')':
917 916 par_level -= 1
918 917
919 918 if par_level != 0:
920 919 continue
921 920
922 921 if next_token != '=':
923 922 continue
924 923
925 924 usedNamedArgs.add(token)
926 925
927 926 # lookup the candidate callable matches either using global_matches
928 927 # or attr_matches for dotted names
929 928 if len(ids) == 1:
930 929 callableMatches = self.global_matches(ids[0])
931 930 else:
932 931 callableMatches = self.attr_matches('.'.join(ids[::-1]))
933 932 argMatches = []
934 933 for callableMatch in callableMatches:
935 934 try:
936 935 namedArgs = self._default_arguments(eval(callableMatch,
937 936 self.namespace))
938 937 except:
939 938 continue
940 939
941 940 # Remove used named arguments from the list, no need to show twice
942 941 for namedArg in set(namedArgs) - usedNamedArgs:
943 942 if namedArg.startswith(text):
944 943 argMatches.append(u"%s=" %namedArg)
945 944 return argMatches
946 945
947 946 def dict_key_matches(self, text):
948 947 "Match string keys in a dictionary, after e.g. 'foo[' "
949 948 def get_keys(obj):
950 949 # Objects can define their own completions by defining an
951 950 # _ipy_key_completions_() method.
952 951 method = get_real_method(obj, '_ipython_key_completions_')
953 952 if method is not None:
954 953 return method()
955 954
956 955 # Special case some common in-memory dict-like types
957 956 if isinstance(obj, dict) or\
958 957 _safe_isinstance(obj, 'pandas', 'DataFrame'):
959 958 try:
960 959 return list(obj.keys())
961 960 except Exception:
962 961 return []
963 962 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
964 963 _safe_isinstance(obj, 'numpy', 'void'):
965 964 return obj.dtype.names or []
966 965 return []
967 966
968 967 try:
969 968 regexps = self.__dict_key_regexps
970 969 except AttributeError:
971 970 dict_key_re_fmt = r'''(?x)
972 971 ( # match dict-referring expression wrt greedy setting
973 972 %s
974 973 )
975 974 \[ # open bracket
976 975 \s* # and optional whitespace
977 976 ([uUbB]? # string prefix (r not handled)
978 977 (?: # unclosed string
979 978 '(?:[^']|(?<!\\)\\')*
980 979 |
981 980 "(?:[^"]|(?<!\\)\\")*
982 981 )
983 982 )?
984 983 $
985 984 '''
986 985 regexps = self.__dict_key_regexps = {
987 986 False: re.compile(dict_key_re_fmt % '''
988 987 # identifiers separated by .
989 988 (?!\d)\w+
990 989 (?:\.(?!\d)\w+)*
991 990 '''),
992 991 True: re.compile(dict_key_re_fmt % '''
993 992 .+
994 993 ''')
995 994 }
996 995
997 996 match = regexps[self.greedy].search(self.text_until_cursor)
998 997 if match is None:
999 998 return []
1000 999
1001 1000 expr, prefix = match.groups()
1002 1001 try:
1003 1002 obj = eval(expr, self.namespace)
1004 1003 except Exception:
1005 1004 try:
1006 1005 obj = eval(expr, self.global_namespace)
1007 1006 except Exception:
1008 1007 return []
1009 1008
1010 1009 keys = get_keys(obj)
1011 1010 if not keys:
1012 1011 return keys
1013 1012 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1014 1013 if not matches:
1015 1014 return matches
1016 1015
1017 1016 # get the cursor position of
1018 1017 # - the text being completed
1019 1018 # - the start of the key text
1020 1019 # - the start of the completion
1021 1020 text_start = len(self.text_until_cursor) - len(text)
1022 1021 if prefix:
1023 1022 key_start = match.start(2)
1024 1023 completion_start = key_start + token_offset
1025 1024 else:
1026 1025 key_start = completion_start = match.end()
1027 1026
1028 1027 # grab the leading prefix, to make sure all completions start with `text`
1029 1028 if text_start > key_start:
1030 1029 leading = ''
1031 1030 else:
1032 1031 leading = text[text_start:completion_start]
1033 1032
1034 1033 # the index of the `[` character
1035 1034 bracket_idx = match.end(1)
1036 1035
1037 1036 # append closing quote and bracket as appropriate
1038 1037 # this is *not* appropriate if the opening quote or bracket is outside
1039 1038 # the text given to this method
1040 1039 suf = ''
1041 1040 continuation = self.line_buffer[len(self.text_until_cursor):]
1042 1041 if key_start > text_start and closing_quote:
1043 1042 # quotes were opened inside text, maybe close them
1044 1043 if continuation.startswith(closing_quote):
1045 1044 continuation = continuation[len(closing_quote):]
1046 1045 else:
1047 1046 suf += closing_quote
1048 1047 if bracket_idx > text_start:
1049 1048 # brackets were opened inside text, maybe close them
1050 1049 if not continuation.startswith(']'):
1051 1050 suf += ']'
1052 1051
1053 1052 return [leading + k + suf for k in matches]
1054 1053
1055 1054 def unicode_name_matches(self, text):
1056 1055 u"""Match Latex-like syntax for unicode characters base
1057 1056 on the name of the character.
1058 1057
1059 1058 This does \\GREEK SMALL LETTER ETA -> η
1060 1059
1061 1060 Works only on valid python 3 identifier, or on combining characters that
1062 1061 will combine to form a valid identifier.
1063 1062
1064 1063 Used on Python 3 only.
1065 1064 """
1066 1065 slashpos = text.rfind('\\')
1067 1066 if slashpos > -1:
1068 1067 s = text[slashpos+1:]
1069 1068 try :
1070 1069 unic = unicodedata.lookup(s)
1071 1070 # allow combining chars
1072 1071 if ('a'+unic).isidentifier():
1073 1072 return '\\'+s,[unic]
1074 1073 except KeyError:
1075 1074 pass
1076 1075 return u'', []
1077 1076
1078 1077
1079 1078
1080 1079
1081 1080 def latex_matches(self, text):
1082 1081 u"""Match Latex syntax for unicode characters.
1083 1082
1084 1083 This does both \\alp -> \\alpha and \\alpha -> α
1085 1084
1086 1085 Used on Python 3 only.
1087 1086 """
1088 1087 slashpos = text.rfind('\\')
1089 1088 if slashpos > -1:
1090 1089 s = text[slashpos:]
1091 1090 if s in latex_symbols:
1092 1091 # Try to complete a full latex symbol to unicode
1093 1092 # \\alpha -> α
1094 1093 return s, [latex_symbols[s]]
1095 1094 else:
1096 1095 # If a user has partially typed a latex symbol, give them
1097 1096 # a full list of options \al -> [\aleph, \alpha]
1098 1097 matches = [k for k in latex_symbols if k.startswith(s)]
1099 1098 return s, matches
1100 1099 return u'', []
1101 1100
1102 1101 def dispatch_custom_completer(self, text):
1103 1102 if not self.custom_completers:
1104 1103 return
1105 1104
1106 1105 line = self.line_buffer
1107 1106 if not line.strip():
1108 1107 return None
1109 1108
1110 1109 # Create a little structure to pass all the relevant information about
1111 1110 # the current completion to any custom completer.
1112 1111 event = Bunch()
1113 1112 event.line = line
1114 1113 event.symbol = text
1115 1114 cmd = line.split(None,1)[0]
1116 1115 event.command = cmd
1117 1116 event.text_until_cursor = self.text_until_cursor
1118 1117
1119 1118 # for foo etc, try also to find completer for %foo
1120 1119 if not cmd.startswith(self.magic_escape):
1121 1120 try_magic = self.custom_completers.s_matches(
1122 1121 self.magic_escape + cmd)
1123 1122 else:
1124 1123 try_magic = []
1125 1124
1126 1125 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1127 1126 try_magic,
1128 1127 self.custom_completers.flat_matches(self.text_until_cursor)):
1129 1128 try:
1130 1129 res = c(event)
1131 1130 if res:
1132 1131 # first, try case sensitive match
1133 1132 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1134 1133 if withcase:
1135 1134 return withcase
1136 1135 # if none, then case insensitive ones are ok too
1137 1136 text_low = text.lower()
1138 1137 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1139 1138 except TryNext:
1140 1139 pass
1141 1140
1142 1141 return None
1143 1142
1144 1143 @_strip_single_trailing_space
1145 1144 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1146 1145 """Find completions for the given text and line context.
1147 1146
1148 1147 Note that both the text and the line_buffer are optional, but at least
1149 1148 one of them must be given.
1150 1149
1151 1150 Parameters
1152 1151 ----------
1153 1152 text : string, optional
1154 1153 Text to perform the completion on. If not given, the line buffer
1155 1154 is split using the instance's CompletionSplitter object.
1156 1155
1157 1156 line_buffer : string, optional
1158 1157 If not given, the completer attempts to obtain the current line
1159 1158 buffer via readline. This keyword allows clients which are
1160 1159 requesting for text completions in non-readline contexts to inform
1161 1160 the completer of the entire text.
1162 1161
1163 1162 cursor_pos : int, optional
1164 1163 Index of the cursor in the full line buffer. Should be provided by
1165 1164 remote frontends where kernel has no access to frontend state.
1166 1165
1167 1166 Returns
1168 1167 -------
1169 1168 text : str
1170 1169 Text that was actually used in the completion.
1171 1170
1172 1171 matches : list
1173 1172 A list of completion matches.
1174 1173 """
1175 1174 # if the cursor position isn't given, the only sane assumption we can
1176 1175 # make is that it's at the end of the line (the common case)
1177 1176 if cursor_pos is None:
1178 1177 cursor_pos = len(line_buffer) if text is None else len(text)
1179 1178
1180 1179 if self.use_main_ns:
1181 1180 self.namespace = __main__.__dict__
1182 1181
1183 1182 if PY3:
1184 1183
1185 1184 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1186 1185 latex_text, latex_matches = self.latex_matches(base_text)
1187 1186 if latex_matches:
1188 1187 return latex_text, latex_matches
1189 1188 name_text = ''
1190 1189 name_matches = []
1191 1190 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1192 1191 name_text, name_matches = meth(base_text)
1193 1192 if name_text:
1194 1193 return name_text, name_matches
1195 1194
1196 1195 # if text is either None or an empty string, rely on the line buffer
1197 1196 if not text:
1198 1197 text = self.splitter.split_line(line_buffer, cursor_pos)
1199 1198
1200 1199 # If no line buffer is given, assume the input text is all there was
1201 1200 if line_buffer is None:
1202 1201 line_buffer = text
1203 1202
1204 1203 self.line_buffer = line_buffer
1205 1204 self.text_until_cursor = self.line_buffer[:cursor_pos]
1206 1205
1207 1206 # Start with a clean slate of completions
1208 1207 self.matches[:] = []
1209 1208 custom_res = self.dispatch_custom_completer(text)
1210 1209 if custom_res is not None:
1211 1210 # did custom completers produce something?
1212 1211 self.matches = custom_res
1213 1212 else:
1214 1213 # Extend the list of completions with the results of each
1215 1214 # matcher, so we return results to the user from all
1216 1215 # namespaces.
1217 1216 if self.merge_completions:
1218 1217 self.matches = []
1219 1218 for matcher in self.matchers:
1220 1219 try:
1221 1220 self.matches.extend(matcher(text))
1222 1221 except:
1223 1222 # Show the ugly traceback if the matcher causes an
1224 1223 # exception, but do NOT crash the kernel!
1225 1224 sys.excepthook(*sys.exc_info())
1226 1225 else:
1227 1226 for matcher in self.matchers:
1228 1227 self.matches = matcher(text)
1229 1228 if self.matches:
1230 1229 break
1231 1230 # FIXME: we should extend our api to return a dict with completions for
1232 1231 # different types of objects. The rlcomplete() method could then
1233 1232 # simply collapse the dict into a list for readline, but we'd have
1234 1233 # richer completion semantics in other evironments.
1235 1234 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1236 1235
1237 1236 return text, self.matches
@@ -1,349 +1,348 b''
1 1 # encoding: utf-8
2 2 """Implementations for various useful completers.
3 3
4 4 These are all loaded by default by IPython.
5 5 """
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2010-2011 The IPython Development Team.
8 8 #
9 9 # Distributed under the terms of the BSD License.
10 10 #
11 11 # The full license is in the file COPYING.txt, distributed with this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 from __future__ import print_function
18 17
19 18 # Stdlib imports
20 19 import glob
21 20 import inspect
22 21 import os
23 22 import re
24 23 import sys
25 24 from importlib import import_module
26 25
27 26 try:
28 27 # Python >= 3.3
29 28 from importlib.machinery import all_suffixes
30 29 _suffixes = all_suffixes()
31 30 except ImportError:
32 31 from imp import get_suffixes
33 32 _suffixes = [ s[0] for s in get_suffixes() ]
34 33
35 34 # Third-party imports
36 35 from time import time
37 36 from zipimport import zipimporter
38 37
39 38 # Our own imports
40 39 from IPython.core.completer import expand_user, compress_user
41 40 from IPython.core.error import TryNext
42 41 from IPython.utils._process_common import arg_split
43 42 from IPython.utils.py3compat import string_types
44 43
45 44 # FIXME: this should be pulled in with the right call via the component system
46 45 from IPython import get_ipython
47 46
48 47 #-----------------------------------------------------------------------------
49 48 # Globals and constants
50 49 #-----------------------------------------------------------------------------
51 50
52 51 # Time in seconds after which the rootmodules will be stored permanently in the
53 52 # ipython ip.db database (kept in the user's .ipython dir).
54 53 TIMEOUT_STORAGE = 2
55 54
56 55 # Time in seconds after which we give up
57 56 TIMEOUT_GIVEUP = 20
58 57
59 58 # Regular expression for the python import statement
60 59 import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
61 60 r'(?P<package>[/\\]__init__)?'
62 61 r'(?P<suffix>%s)$' %
63 62 r'|'.join(re.escape(s) for s in _suffixes))
64 63
65 64 # RE for the ipython %run command (python + ipython scripts)
66 65 magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
67 66
68 67 #-----------------------------------------------------------------------------
69 68 # Local utilities
70 69 #-----------------------------------------------------------------------------
71 70
72 71 def module_list(path):
73 72 """
74 73 Return the list containing the names of the modules available in the given
75 74 folder.
76 75 """
77 76 # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
78 77 if path == '':
79 78 path = '.'
80 79
81 80 # A few local constants to be used in loops below
82 81 pjoin = os.path.join
83 82
84 83 if os.path.isdir(path):
85 84 # Build a list of all files in the directory and all files
86 85 # in its subdirectories. For performance reasons, do not
87 86 # recurse more than one level into subdirectories.
88 87 files = []
89 88 for root, dirs, nondirs in os.walk(path, followlinks=True):
90 89 subdir = root[len(path)+1:]
91 90 if subdir:
92 91 files.extend(pjoin(subdir, f) for f in nondirs)
93 92 dirs[:] = [] # Do not recurse into additional subdirectories.
94 93 else:
95 94 files.extend(nondirs)
96 95
97 96 else:
98 97 try:
99 98 files = list(zipimporter(path)._files.keys())
100 99 except:
101 100 files = []
102 101
103 102 # Build a list of modules which match the import_re regex.
104 103 modules = []
105 104 for f in files:
106 105 m = import_re.match(f)
107 106 if m:
108 107 modules.append(m.group('name'))
109 108 return list(set(modules))
110 109
111 110
112 111 def get_root_modules():
113 112 """
114 113 Returns a list containing the names of all the modules available in the
115 114 folders of the pythonpath.
116 115
117 116 ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
118 117 """
119 118 ip = get_ipython()
120 119 rootmodules_cache = ip.db.get('rootmodules_cache', {})
121 120 rootmodules = list(sys.builtin_module_names)
122 121 start_time = time()
123 122 store = False
124 123 for path in sys.path:
125 124 try:
126 125 modules = rootmodules_cache[path]
127 126 except KeyError:
128 127 modules = module_list(path)
129 128 try:
130 129 modules.remove('__init__')
131 130 except ValueError:
132 131 pass
133 132 if path not in ('', '.'): # cwd modules should not be cached
134 133 rootmodules_cache[path] = modules
135 134 if time() - start_time > TIMEOUT_STORAGE and not store:
136 135 store = True
137 136 print("\nCaching the list of root modules, please wait!")
138 137 print("(This will only be done once - type '%rehashx' to "
139 138 "reset cache!)\n")
140 139 sys.stdout.flush()
141 140 if time() - start_time > TIMEOUT_GIVEUP:
142 141 print("This is taking too long, we give up.\n")
143 142 return []
144 143 rootmodules.extend(modules)
145 144 if store:
146 145 ip.db['rootmodules_cache'] = rootmodules_cache
147 146 rootmodules = list(set(rootmodules))
148 147 return rootmodules
149 148
150 149
151 150 def is_importable(module, attr, only_modules):
152 151 if only_modules:
153 152 return inspect.ismodule(getattr(module, attr))
154 153 else:
155 154 return not(attr[:2] == '__' and attr[-2:] == '__')
156 155
157 156 def try_import(mod, only_modules=False):
158 157 try:
159 158 m = import_module(mod)
160 159 except:
161 160 return []
162 161
163 162 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
164 163
165 164 completions = []
166 165 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
167 166 completions.extend( [attr for attr in dir(m) if
168 167 is_importable(m, attr, only_modules)])
169 168
170 169 completions.extend(getattr(m, '__all__', []))
171 170 if m_is_init:
172 171 completions.extend(module_list(os.path.dirname(m.__file__)))
173 172 completions = {c for c in completions if isinstance(c, string_types)}
174 173 completions.discard('__init__')
175 174 return list(completions)
176 175
177 176
178 177 #-----------------------------------------------------------------------------
179 178 # Completion-related functions.
180 179 #-----------------------------------------------------------------------------
181 180
182 181 def quick_completer(cmd, completions):
183 182 """ Easily create a trivial completer for a command.
184 183
185 184 Takes either a list of completions, or all completions in string (that will
186 185 be split on whitespace).
187 186
188 187 Example::
189 188
190 189 [d:\ipython]|1> import ipy_completers
191 190 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
192 191 [d:\ipython]|3> foo b<TAB>
193 192 bar baz
194 193 [d:\ipython]|3> foo ba
195 194 """
196 195
197 196 if isinstance(completions, string_types):
198 197 completions = completions.split()
199 198
200 199 def do_complete(self, event):
201 200 return completions
202 201
203 202 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
204 203
205 204 def module_completion(line):
206 205 """
207 206 Returns a list containing the completion possibilities for an import line.
208 207
209 208 The line looks like this :
210 209 'import xml.d'
211 210 'from xml.dom import'
212 211 """
213 212
214 213 words = line.split(' ')
215 214 nwords = len(words)
216 215
217 216 # from whatever <tab> -> 'import '
218 217 if nwords == 3 and words[0] == 'from':
219 218 return ['import ']
220 219
221 220 # 'from xy<tab>' or 'import xy<tab>'
222 221 if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
223 222 if nwords == 1:
224 223 return get_root_modules()
225 224 mod = words[1].split('.')
226 225 if len(mod) < 2:
227 226 return get_root_modules()
228 227 completion_list = try_import('.'.join(mod[:-1]), True)
229 228 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
230 229
231 230 # 'from xyz import abc<tab>'
232 231 if nwords >= 3 and words[0] == 'from':
233 232 mod = words[1]
234 233 return try_import(mod)
235 234
236 235 #-----------------------------------------------------------------------------
237 236 # Completers
238 237 #-----------------------------------------------------------------------------
239 238 # These all have the func(self, event) signature to be used as custom
240 239 # completers
241 240
242 241 def module_completer(self,event):
243 242 """Give completions after user has typed 'import ...' or 'from ...'"""
244 243
245 244 # This works in all versions of python. While 2.5 has
246 245 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
247 246 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
248 247 # of possibly problematic side effects.
249 248 # This search the folders in the sys.path for available modules.
250 249
251 250 return module_completion(event.line)
252 251
253 252 # FIXME: there's a lot of logic common to the run, cd and builtin file
254 253 # completers, that is currently reimplemented in each.
255 254
256 255 def magic_run_completer(self, event):
257 256 """Complete files that end in .py or .ipy or .ipynb for the %run command.
258 257 """
259 258 comps = arg_split(event.line, strict=False)
260 259 # relpath should be the current token that we need to complete.
261 260 if (len(comps) > 1) and (not event.line.endswith(' ')):
262 261 relpath = comps[-1].strip("'\"")
263 262 else:
264 263 relpath = ''
265 264
266 265 #print("\nev=", event) # dbg
267 266 #print("rp=", relpath) # dbg
268 267 #print('comps=', comps) # dbg
269 268
270 269 lglob = glob.glob
271 270 isdir = os.path.isdir
272 271 relpath, tilde_expand, tilde_val = expand_user(relpath)
273 272
274 273 # Find if the user has already typed the first filename, after which we
275 274 # should complete on all files, since after the first one other files may
276 275 # be arguments to the input script.
277 276
278 277 if any(magic_run_re.match(c) for c in comps):
279 278 matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
280 279 for f in lglob(relpath+'*')]
281 280 else:
282 281 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
283 282 pys = [f.replace('\\','/')
284 283 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
285 284 lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
286 285
287 286 matches = dirs + pys
288 287
289 288 #print('run comp:', dirs+pys) # dbg
290 289 return [compress_user(p, tilde_expand, tilde_val) for p in matches]
291 290
292 291
293 292 def cd_completer(self, event):
294 293 """Completer function for cd, which only returns directories."""
295 294 ip = get_ipython()
296 295 relpath = event.symbol
297 296
298 297 #print(event) # dbg
299 298 if event.line.endswith('-b') or ' -b ' in event.line:
300 299 # return only bookmark completions
301 300 bkms = self.db.get('bookmarks', None)
302 301 if bkms:
303 302 return bkms.keys()
304 303 else:
305 304 return []
306 305
307 306 if event.symbol == '-':
308 307 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
309 308 # jump in directory history by number
310 309 fmt = '-%0' + width_dh +'d [%s]'
311 310 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
312 311 if len(ents) > 1:
313 312 return ents
314 313 return []
315 314
316 315 if event.symbol.startswith('--'):
317 316 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
318 317
319 318 # Expand ~ in path and normalize directory separators.
320 319 relpath, tilde_expand, tilde_val = expand_user(relpath)
321 320 relpath = relpath.replace('\\','/')
322 321
323 322 found = []
324 323 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
325 324 if os.path.isdir(f)]:
326 325 if ' ' in d:
327 326 # we don't want to deal with any of that, complex code
328 327 # for this is elsewhere
329 328 raise TryNext
330 329
331 330 found.append(d)
332 331
333 332 if not found:
334 333 if os.path.isdir(relpath):
335 334 return [compress_user(relpath, tilde_expand, tilde_val)]
336 335
337 336 # if no completions so far, try bookmarks
338 337 bks = self.db.get('bookmarks',{})
339 338 bkmatches = [s for s in bks if s.startswith(event.symbol)]
340 339 if bkmatches:
341 340 return bkmatches
342 341
343 342 raise TryNext
344 343
345 344 return [compress_user(p, tilde_expand, tilde_val) for p in found]
346 345
347 346 def reset_completer(self, event):
348 347 "A completer for %reset magic"
349 348 return '-f -s in out array dhist'.split()
@@ -1,216 +1,215 b''
1 1 # encoding: utf-8
2 2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3 3
4 4 Authors:
5 5
6 6 * Fernando Perez
7 7 * Brian E. Granger
8 8 """
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 12 # Copyright (C) 2008-2011 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 from __future__ import print_function
22 21
23 22 import os
24 23 import sys
25 24 import traceback
26 25 from pprint import pformat
27 26
28 27 from IPython.core import ultratb
29 28 from IPython.core.release import author_email
30 29 from IPython.utils.sysinfo import sys_info
31 30 from IPython.utils.py3compat import input, getcwd
32 31
33 32 #-----------------------------------------------------------------------------
34 33 # Code
35 34 #-----------------------------------------------------------------------------
36 35
37 36 # Template for the user message.
38 37 _default_message_template = """\
39 38 Oops, {app_name} crashed. We do our best to make it stable, but...
40 39
41 40 A crash report was automatically generated with the following information:
42 41 - A verbatim copy of the crash traceback.
43 42 - A copy of your input history during this session.
44 43 - Data on your current {app_name} configuration.
45 44
46 45 It was left in the file named:
47 46 \t'{crash_report_fname}'
48 47 If you can email this file to the developers, the information in it will help
49 48 them in understanding and correcting the problem.
50 49
51 50 You can mail it to: {contact_name} at {contact_email}
52 51 with the subject '{app_name} Crash Report'.
53 52
54 53 If you want to do it now, the following command will work (under Unix):
55 54 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
56 55
57 56 To ensure accurate tracking of this issue, please file a report about it at:
58 57 {bug_tracker}
59 58 """
60 59
61 60 _lite_message_template = """
62 61 If you suspect this is an IPython bug, please report it at:
63 62 https://github.com/ipython/ipython/issues
64 63 or send an email to the mailing list at {email}
65 64
66 65 You can print a more detailed traceback right now with "%tb", or use "%debug"
67 66 to interactively debug it.
68 67
69 68 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
70 69 {config}Application.verbose_crash=True
71 70 """
72 71
73 72
74 73 class CrashHandler(object):
75 74 """Customizable crash handlers for IPython applications.
76 75
77 76 Instances of this class provide a :meth:`__call__` method which can be
78 77 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
79 78
80 79 def __call__(self, etype, evalue, etb)
81 80 """
82 81
83 82 message_template = _default_message_template
84 83 section_sep = '\n\n'+'*'*75+'\n\n'
85 84
86 85 def __init__(self, app, contact_name=None, contact_email=None,
87 86 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
88 87 """Create a new crash handler
89 88
90 89 Parameters
91 90 ----------
92 91 app : Application
93 92 A running :class:`Application` instance, which will be queried at
94 93 crash time for internal information.
95 94
96 95 contact_name : str
97 96 A string with the name of the person to contact.
98 97
99 98 contact_email : str
100 99 A string with the email address of the contact.
101 100
102 101 bug_tracker : str
103 102 A string with the URL for your project's bug tracker.
104 103
105 104 show_crash_traceback : bool
106 105 If false, don't print the crash traceback on stderr, only generate
107 106 the on-disk report
108 107
109 108 Non-argument instance attributes:
110 109
111 110 These instances contain some non-argument attributes which allow for
112 111 further customization of the crash handler's behavior. Please see the
113 112 source for further details.
114 113 """
115 114 self.crash_report_fname = "Crash_report_%s.txt" % app.name
116 115 self.app = app
117 116 self.call_pdb = call_pdb
118 117 #self.call_pdb = True # dbg
119 118 self.show_crash_traceback = show_crash_traceback
120 119 self.info = dict(app_name = app.name,
121 120 contact_name = contact_name,
122 121 contact_email = contact_email,
123 122 bug_tracker = bug_tracker,
124 123 crash_report_fname = self.crash_report_fname)
125 124
126 125
127 126 def __call__(self, etype, evalue, etb):
128 127 """Handle an exception, call for compatible with sys.excepthook"""
129 128
130 129 # do not allow the crash handler to be called twice without reinstalling it
131 130 # this prevents unlikely errors in the crash handling from entering an
132 131 # infinite loop.
133 132 sys.excepthook = sys.__excepthook__
134 133
135 134 # Report tracebacks shouldn't use color in general (safer for users)
136 135 color_scheme = 'NoColor'
137 136
138 137 # Use this ONLY for developer debugging (keep commented out for release)
139 138 #color_scheme = 'Linux' # dbg
140 139 try:
141 140 rptdir = self.app.ipython_dir
142 141 except:
143 142 rptdir = getcwd()
144 143 if rptdir is None or not os.path.isdir(rptdir):
145 144 rptdir = getcwd()
146 145 report_name = os.path.join(rptdir,self.crash_report_fname)
147 146 # write the report filename into the instance dict so it can get
148 147 # properly expanded out in the user message template
149 148 self.crash_report_fname = report_name
150 149 self.info['crash_report_fname'] = report_name
151 150 TBhandler = ultratb.VerboseTB(
152 151 color_scheme=color_scheme,
153 152 long_header=1,
154 153 call_pdb=self.call_pdb,
155 154 )
156 155 if self.call_pdb:
157 156 TBhandler(etype,evalue,etb)
158 157 return
159 158 else:
160 159 traceback = TBhandler.text(etype,evalue,etb,context=31)
161 160
162 161 # print traceback to screen
163 162 if self.show_crash_traceback:
164 163 print(traceback, file=sys.stderr)
165 164
166 165 # and generate a complete report on disk
167 166 try:
168 167 report = open(report_name,'w')
169 168 except:
170 169 print('Could not create crash report on disk.', file=sys.stderr)
171 170 return
172 171
173 172 # Inform user on stderr of what happened
174 173 print('\n'+'*'*70+'\n', file=sys.stderr)
175 174 print(self.message_template.format(**self.info), file=sys.stderr)
176 175
177 176 # Construct report on disk
178 177 report.write(self.make_report(traceback))
179 178 report.close()
180 179 input("Hit <Enter> to quit (your terminal may close):")
181 180
182 181 def make_report(self,traceback):
183 182 """Return a string containing a crash report."""
184 183
185 184 sec_sep = self.section_sep
186 185
187 186 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
188 187 rpt_add = report.append
189 188 rpt_add(sys_info())
190 189
191 190 try:
192 191 config = pformat(self.app.config)
193 192 rpt_add(sec_sep)
194 193 rpt_add('Application name: %s\n\n' % self.app_name)
195 194 rpt_add('Current user configuration structure:\n\n')
196 195 rpt_add(config)
197 196 except:
198 197 pass
199 198 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
200 199
201 200 return ''.join(report)
202 201
203 202
204 203 def crash_handler_lite(etype, evalue, tb):
205 204 """a light excepthook, adding a small message to the usual traceback"""
206 205 traceback.print_exception(etype, evalue, tb)
207 206
208 207 from IPython.core.interactiveshell import InteractiveShell
209 208 if InteractiveShell.initialized():
210 209 # we are in a Shell environment, give %magic example
211 210 config = "%config "
212 211 else:
213 212 # we are not in a shell, show generic config
214 213 config = "c."
215 214 print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
216 215
@@ -1,630 +1,629 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Pdb debugger class.
4 4
5 5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 6 the command line completion of other programs which include this isn't
7 7 damaged.
8 8
9 9 In the future, this class will be expanded with improvements over the standard
10 10 pdb.
11 11
12 12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 13 changes. Licensing should therefore be under the standard Python terms. For
14 14 details on the PSF (Python Software Foundation) standard license, see:
15 15
16 16 http://www.python.org/2.2.3/license.html"""
17 17
18 18 #*****************************************************************************
19 19 #
20 20 # This file is licensed under the PSF license.
21 21 #
22 22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 24 #
25 25 #
26 26 #*****************************************************************************
27 from __future__ import print_function
28 27
29 28 import bdb
30 29 import functools
31 30 import inspect
32 31 import sys
33 32 import warnings
34 33
35 34 from IPython import get_ipython
36 35 from IPython.utils import PyColorize, ulinecache
37 36 from IPython.utils import coloransi, py3compat
38 37 from IPython.core.excolors import exception_colors
39 38 from IPython.testing.skipdoctest import skip_doctest
40 39
41 40
42 41 prompt = 'ipdb> '
43 42
44 43 #We have to check this directly from sys.argv, config struct not yet available
45 44 from pdb import Pdb as OldPdb
46 45
47 46 # Allow the set_trace code to operate outside of an ipython instance, even if
48 47 # it does so with some limitations. The rest of this support is implemented in
49 48 # the Tracer constructor.
50 49
51 50 def make_arrow(pad):
52 51 """generate the leading arrow in front of traceback or debugger"""
53 52 if pad >= 2:
54 53 return '-'*(pad-2) + '> '
55 54 elif pad == 1:
56 55 return '>'
57 56 return ''
58 57
59 58
60 59 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
61 60 """Exception hook which handles `BdbQuit` exceptions.
62 61
63 62 All other exceptions are processed using the `excepthook`
64 63 parameter.
65 64 """
66 65 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
67 66 DeprecationWarning)
68 67 if et==bdb.BdbQuit:
69 68 print('Exiting Debugger.')
70 69 elif excepthook is not None:
71 70 excepthook(et, ev, tb)
72 71 else:
73 72 # Backwards compatibility. Raise deprecation warning?
74 73 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
75 74
76 75
77 76 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
78 77 warnings.warn(
79 78 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
80 79 DeprecationWarning)
81 80 print('Exiting Debugger.')
82 81
83 82
84 83 class Tracer(object):
85 84 """
86 85 DEPRECATED
87 86
88 87 Class for local debugging, similar to pdb.set_trace.
89 88
90 89 Instances of this class, when called, behave like pdb.set_trace, but
91 90 providing IPython's enhanced capabilities.
92 91
93 92 This is implemented as a class which must be initialized in your own code
94 93 and not as a standalone function because we need to detect at runtime
95 94 whether IPython is already active or not. That detection is done in the
96 95 constructor, ensuring that this code plays nicely with a running IPython,
97 96 while functioning acceptably (though with limitations) if outside of it.
98 97 """
99 98
100 99 @skip_doctest
101 100 def __init__(self, colors=None):
102 101 """
103 102 DEPRECATED
104 103
105 104 Create a local debugger instance.
106 105
107 106 Parameters
108 107 ----------
109 108
110 109 colors : str, optional
111 110 The name of the color scheme to use, it must be one of IPython's
112 111 valid color schemes. If not given, the function will default to
113 112 the current IPython scheme when running inside IPython, and to
114 113 'NoColor' otherwise.
115 114
116 115 Examples
117 116 --------
118 117 ::
119 118
120 119 from IPython.core.debugger import Tracer; debug_here = Tracer()
121 120
122 121 Later in your code::
123 122
124 123 debug_here() # -> will open up the debugger at that point.
125 124
126 125 Once the debugger activates, you can use all of its regular commands to
127 126 step through code, set breakpoints, etc. See the pdb documentation
128 127 from the Python standard library for usage details.
129 128 """
130 129 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
131 130 "`IPython.core.debugger.Pdb.set_trace()`",
132 131 DeprecationWarning)
133 132
134 133 ip = get_ipython()
135 134 if ip is None:
136 135 # Outside of ipython, we set our own exception hook manually
137 136 sys.excepthook = functools.partial(BdbQuit_excepthook,
138 137 excepthook=sys.excepthook)
139 138 def_colors = 'NoColor'
140 139 else:
141 140 # In ipython, we use its custom exception handler mechanism
142 141 def_colors = ip.colors
143 142 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
144 143
145 144 if colors is None:
146 145 colors = def_colors
147 146
148 147 # The stdlib debugger internally uses a modified repr from the `repr`
149 148 # module, that limits the length of printed strings to a hardcoded
150 149 # limit of 30 characters. That much trimming is too aggressive, let's
151 150 # at least raise that limit to 80 chars, which should be enough for
152 151 # most interactive uses.
153 152 try:
154 153 try:
155 154 from reprlib import aRepr # Py 3
156 155 except ImportError:
157 156 from repr import aRepr # Py 2
158 157 aRepr.maxstring = 80
159 158 except:
160 159 # This is only a user-facing convenience, so any error we encounter
161 160 # here can be warned about but can be otherwise ignored. These
162 161 # printouts will tell us about problems if this API changes
163 162 import traceback
164 163 traceback.print_exc()
165 164
166 165 self.debugger = Pdb(colors)
167 166
168 167 def __call__(self):
169 168 """Starts an interactive debugger at the point where called.
170 169
171 170 This is similar to the pdb.set_trace() function from the std lib, but
172 171 using IPython's enhanced debugger."""
173 172
174 173 self.debugger.set_trace(sys._getframe().f_back)
175 174
176 175
177 176 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
178 177 """Make new_fn have old_fn's doc string. This is particularly useful
179 178 for the ``do_...`` commands that hook into the help system.
180 179 Adapted from from a comp.lang.python posting
181 180 by Duncan Booth."""
182 181 def wrapper(*args, **kw):
183 182 return new_fn(*args, **kw)
184 183 if old_fn.__doc__:
185 184 wrapper.__doc__ = old_fn.__doc__ + additional_text
186 185 return wrapper
187 186
188 187
189 188 def _file_lines(fname):
190 189 """Return the contents of a named file as a list of lines.
191 190
192 191 This function never raises an IOError exception: if the file can't be
193 192 read, it simply returns an empty list."""
194 193
195 194 try:
196 195 outfile = open(fname)
197 196 except IOError:
198 197 return []
199 198 else:
200 199 out = outfile.readlines()
201 200 outfile.close()
202 201 return out
203 202
204 203
205 204 class Pdb(OldPdb, object):
206 205 """Modified Pdb class, does not load readline.
207 206
208 207 for a standalone version that uses prompt_toolkit, see
209 208 `IPython.terminal.debugger.TerminalPdb` and
210 209 `IPython.terminal.debugger.set_trace()`
211 210 """
212 211
213 212 def __init__(self, color_scheme=None, completekey=None,
214 213 stdin=None, stdout=None, context=5):
215 214
216 215 # Parent constructor:
217 216 try:
218 217 self.context = int(context)
219 218 if self.context <= 0:
220 219 raise ValueError("Context must be a positive integer")
221 220 except (TypeError, ValueError):
222 221 raise ValueError("Context must be a positive integer")
223 222
224 223 OldPdb.__init__(self, completekey, stdin, stdout)
225 224
226 225 # IPython changes...
227 226 self.shell = get_ipython()
228 227
229 228 if self.shell is None:
230 229 save_main = sys.modules['__main__']
231 230 # No IPython instance running, we must create one
232 231 from IPython.terminal.interactiveshell import \
233 232 TerminalInteractiveShell
234 233 self.shell = TerminalInteractiveShell.instance()
235 234 # needed by any code which calls __import__("__main__") after
236 235 # the debugger was entered. See also #9941.
237 236 sys.modules['__main__'] = save_main
238 237
239 238 if color_scheme is not None:
240 239 warnings.warn(
241 240 "The `color_scheme` argument is deprecated since version 5.1",
242 241 DeprecationWarning, stacklevel=2)
243 242 else:
244 243 color_scheme = self.shell.colors
245 244
246 245 self.aliases = {}
247 246
248 247 # Create color table: we copy the default one from the traceback
249 248 # module and add a few attributes needed for debugging
250 249 self.color_scheme_table = exception_colors()
251 250
252 251 # shorthands
253 252 C = coloransi.TermColors
254 253 cst = self.color_scheme_table
255 254
256 255 cst['NoColor'].colors.prompt = C.NoColor
257 256 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
258 257 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
259 258
260 259 cst['Linux'].colors.prompt = C.Green
261 260 cst['Linux'].colors.breakpoint_enabled = C.LightRed
262 261 cst['Linux'].colors.breakpoint_disabled = C.Red
263 262
264 263 cst['LightBG'].colors.prompt = C.Blue
265 264 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
266 265 cst['LightBG'].colors.breakpoint_disabled = C.Red
267 266
268 267 cst['Neutral'].colors.prompt = C.Blue
269 268 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
270 269 cst['Neutral'].colors.breakpoint_disabled = C.Red
271 270
272 271
273 272 # Add a python parser so we can syntax highlight source while
274 273 # debugging.
275 274 self.parser = PyColorize.Parser(style=color_scheme)
276 275 self.set_colors(color_scheme)
277 276
278 277 # Set the prompt - the default prompt is '(Pdb)'
279 278 self.prompt = prompt
280 279
281 280 def set_colors(self, scheme):
282 281 """Shorthand access to the color table scheme selector method."""
283 282 self.color_scheme_table.set_active_scheme(scheme)
284 283 self.parser.style = scheme
285 284
286 285 def interaction(self, frame, traceback):
287 286 try:
288 287 OldPdb.interaction(self, frame, traceback)
289 288 except KeyboardInterrupt:
290 289 sys.stdout.write('\n' + self.shell.get_exception_only())
291 290
292 291 def parseline(self, line):
293 292 if line.startswith("!!"):
294 293 # Force standard behavior.
295 294 return super(Pdb, self).parseline(line[2:])
296 295 # "Smart command mode" from pdb++: don't execute commands if a variable
297 296 # with the same name exists.
298 297 cmd, arg, newline = super(Pdb, self).parseline(line)
299 298 # Fix for #9611: Do not trigger smart command if the command is `exit`
300 299 # or `quit` and it would resolve to their *global* value (the
301 300 # `ExitAutocall` object). Just checking that it is not present in the
302 301 # locals dict is not enough as locals and globals match at the
303 302 # toplevel.
304 303 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
305 304 and not (cmd in ["exit", "quit"]
306 305 and (self.curframe.f_locals is self.curframe.f_globals
307 306 or cmd not in self.curframe.f_locals))):
308 307 return super(Pdb, self).parseline("!" + line)
309 308 return super(Pdb, self).parseline(line)
310 309
311 310 def new_do_up(self, arg):
312 311 OldPdb.do_up(self, arg)
313 312 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
314 313
315 314 def new_do_down(self, arg):
316 315 OldPdb.do_down(self, arg)
317 316
318 317 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
319 318
320 319 def new_do_frame(self, arg):
321 320 OldPdb.do_frame(self, arg)
322 321
323 322 def new_do_quit(self, arg):
324 323
325 324 if hasattr(self, 'old_all_completions'):
326 325 self.shell.Completer.all_completions=self.old_all_completions
327 326
328 327 return OldPdb.do_quit(self, arg)
329 328
330 329 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
331 330
332 331 def new_do_restart(self, arg):
333 332 """Restart command. In the context of ipython this is exactly the same
334 333 thing as 'quit'."""
335 334 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
336 335 return self.do_quit(arg)
337 336
338 337 def print_stack_trace(self, context=None):
339 338 if context is None:
340 339 context = self.context
341 340 try:
342 341 context=int(context)
343 342 if context <= 0:
344 343 raise ValueError("Context must be a positive integer")
345 344 except (TypeError, ValueError):
346 345 raise ValueError("Context must be a positive integer")
347 346 try:
348 347 for frame_lineno in self.stack:
349 348 self.print_stack_entry(frame_lineno, context=context)
350 349 except KeyboardInterrupt:
351 350 pass
352 351
353 352 def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
354 353 context=None):
355 354 if context is None:
356 355 context = self.context
357 356 try:
358 357 context=int(context)
359 358 if context <= 0:
360 359 raise ValueError("Context must be a positive integer")
361 360 except (TypeError, ValueError):
362 361 raise ValueError("Context must be a positive integer")
363 362 print(self.format_stack_entry(frame_lineno, '', context))
364 363
365 364 # vds: >>
366 365 frame, lineno = frame_lineno
367 366 filename = frame.f_code.co_filename
368 367 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
369 368 # vds: <<
370 369
371 370 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
372 371 if context is None:
373 372 context = self.context
374 373 try:
375 374 context=int(context)
376 375 if context <= 0:
377 376 print("Context must be a positive integer")
378 377 except (TypeError, ValueError):
379 378 print("Context must be a positive integer")
380 379 try:
381 380 import reprlib # Py 3
382 381 except ImportError:
383 382 import repr as reprlib # Py 2
384 383
385 384 ret = []
386 385
387 386 Colors = self.color_scheme_table.active_colors
388 387 ColorsNormal = Colors.Normal
389 388 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
390 389 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
391 390 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
392 391 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
393 392 ColorsNormal)
394 393
395 394 frame, lineno = frame_lineno
396 395
397 396 return_value = ''
398 397 if '__return__' in frame.f_locals:
399 398 rv = frame.f_locals['__return__']
400 399 #return_value += '->'
401 400 return_value += reprlib.repr(rv) + '\n'
402 401 ret.append(return_value)
403 402
404 403 #s = filename + '(' + `lineno` + ')'
405 404 filename = self.canonic(frame.f_code.co_filename)
406 405 link = tpl_link % py3compat.cast_unicode(filename)
407 406
408 407 if frame.f_code.co_name:
409 408 func = frame.f_code.co_name
410 409 else:
411 410 func = "<lambda>"
412 411
413 412 call = ''
414 413 if func != '?':
415 414 if '__args__' in frame.f_locals:
416 415 args = reprlib.repr(frame.f_locals['__args__'])
417 416 else:
418 417 args = '()'
419 418 call = tpl_call % (func, args)
420 419
421 420 # The level info should be generated in the same format pdb uses, to
422 421 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
423 422 if frame is self.curframe:
424 423 ret.append('> ')
425 424 else:
426 425 ret.append(' ')
427 426 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
428 427
429 428 start = lineno - 1 - context//2
430 429 lines = ulinecache.getlines(filename)
431 430 start = min(start, len(lines) - context)
432 431 start = max(start, 0)
433 432 lines = lines[start : start + context]
434 433
435 434 for i,line in enumerate(lines):
436 435 show_arrow = (start + 1 + i == lineno)
437 436 linetpl = (frame is self.curframe or show_arrow) \
438 437 and tpl_line_em \
439 438 or tpl_line
440 439 ret.append(self.__format_line(linetpl, filename,
441 440 start + 1 + i, line,
442 441 arrow = show_arrow) )
443 442 return ''.join(ret)
444 443
445 444 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
446 445 bp_mark = ""
447 446 bp_mark_color = ""
448 447
449 448 new_line, err = self.parser.format2(line, 'str')
450 449 if not err:
451 450 line = new_line
452 451
453 452 bp = None
454 453 if lineno in self.get_file_breaks(filename):
455 454 bps = self.get_breaks(filename, lineno)
456 455 bp = bps[-1]
457 456
458 457 if bp:
459 458 Colors = self.color_scheme_table.active_colors
460 459 bp_mark = str(bp.number)
461 460 bp_mark_color = Colors.breakpoint_enabled
462 461 if not bp.enabled:
463 462 bp_mark_color = Colors.breakpoint_disabled
464 463
465 464 numbers_width = 7
466 465 if arrow:
467 466 # This is the line with the error
468 467 pad = numbers_width - len(str(lineno)) - len(bp_mark)
469 468 num = '%s%s' % (make_arrow(pad), str(lineno))
470 469 else:
471 470 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
472 471
473 472 return tpl_line % (bp_mark_color + bp_mark, num, line)
474 473
475 474
476 475 def print_list_lines(self, filename, first, last):
477 476 """The printing (as opposed to the parsing part of a 'list'
478 477 command."""
479 478 try:
480 479 Colors = self.color_scheme_table.active_colors
481 480 ColorsNormal = Colors.Normal
482 481 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
483 482 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
484 483 src = []
485 484 if filename == "<string>" and hasattr(self, "_exec_filename"):
486 485 filename = self._exec_filename
487 486
488 487 for lineno in range(first, last+1):
489 488 line = ulinecache.getline(filename, lineno)
490 489 if not line:
491 490 break
492 491
493 492 if lineno == self.curframe.f_lineno:
494 493 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
495 494 else:
496 495 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
497 496
498 497 src.append(line)
499 498 self.lineno = lineno
500 499
501 500 print(''.join(src))
502 501
503 502 except KeyboardInterrupt:
504 503 pass
505 504
506 505 def do_list(self, arg):
507 506 self.lastcmd = 'list'
508 507 last = None
509 508 if arg:
510 509 try:
511 510 x = eval(arg, {}, {})
512 511 if type(x) == type(()):
513 512 first, last = x
514 513 first = int(first)
515 514 last = int(last)
516 515 if last < first:
517 516 # Assume it's a count
518 517 last = first + last
519 518 else:
520 519 first = max(1, int(x) - 5)
521 520 except:
522 521 print('*** Error in argument:', repr(arg))
523 522 return
524 523 elif self.lineno is None:
525 524 first = max(1, self.curframe.f_lineno - 5)
526 525 else:
527 526 first = self.lineno + 1
528 527 if last is None:
529 528 last = first + 10
530 529 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
531 530
532 531 # vds: >>
533 532 lineno = first
534 533 filename = self.curframe.f_code.co_filename
535 534 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
536 535 # vds: <<
537 536
538 537 do_l = do_list
539 538
540 539 def getsourcelines(self, obj):
541 540 lines, lineno = inspect.findsource(obj)
542 541 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
543 542 # must be a module frame: do not try to cut a block out of it
544 543 return lines, 1
545 544 elif inspect.ismodule(obj):
546 545 return lines, 1
547 546 return inspect.getblock(lines[lineno:]), lineno+1
548 547
549 548 def do_longlist(self, arg):
550 549 self.lastcmd = 'longlist'
551 550 try:
552 551 lines, lineno = self.getsourcelines(self.curframe)
553 552 except OSError as err:
554 553 self.error(err)
555 554 return
556 555 last = lineno + len(lines)
557 556 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
558 557 do_ll = do_longlist
559 558
560 559 def do_pdef(self, arg):
561 560 """Print the call signature for any callable object.
562 561
563 562 The debugger interface to %pdef"""
564 563 namespaces = [('Locals', self.curframe.f_locals),
565 564 ('Globals', self.curframe.f_globals)]
566 565 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
567 566
568 567 def do_pdoc(self, arg):
569 568 """Print the docstring for an object.
570 569
571 570 The debugger interface to %pdoc."""
572 571 namespaces = [('Locals', self.curframe.f_locals),
573 572 ('Globals', self.curframe.f_globals)]
574 573 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
575 574
576 575 def do_pfile(self, arg):
577 576 """Print (or run through pager) the file where an object is defined.
578 577
579 578 The debugger interface to %pfile.
580 579 """
581 580 namespaces = [('Locals', self.curframe.f_locals),
582 581 ('Globals', self.curframe.f_globals)]
583 582 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
584 583
585 584 def do_pinfo(self, arg):
586 585 """Provide detailed information about an object.
587 586
588 587 The debugger interface to %pinfo, i.e., obj?."""
589 588 namespaces = [('Locals', self.curframe.f_locals),
590 589 ('Globals', self.curframe.f_globals)]
591 590 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
592 591
593 592 def do_pinfo2(self, arg):
594 593 """Provide extra detailed information about an object.
595 594
596 595 The debugger interface to %pinfo2, i.e., obj??."""
597 596 namespaces = [('Locals', self.curframe.f_locals),
598 597 ('Globals', self.curframe.f_globals)]
599 598 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
600 599
601 600 def do_psource(self, arg):
602 601 """Print (or run through pager) the source code for an object."""
603 602 namespaces = [('Locals', self.curframe.f_locals),
604 603 ('Globals', self.curframe.f_globals)]
605 604 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
606 605
607 606 def do_where(self, arg):
608 607 """w(here)
609 608 Print a stack trace, with the most recent frame at the bottom.
610 609 An arrow indicates the "current frame", which determines the
611 610 context of most commands. 'bt' is an alias for this command.
612 611
613 612 Take a number as argument as an (optional) number of context line to
614 613 print"""
615 614 if arg:
616 615 context = int(arg)
617 616 self.print_stack_trace(context)
618 617 else:
619 618 self.print_stack_trace()
620 619
621 620 do_w = do_where
622 621
623 622
624 623 def set_trace(frame=None):
625 624 """
626 625 Start debugging from `frame`.
627 626
628 627 If frame is not specified, debugging starts from caller's frame.
629 628 """
630 629 Pdb().set_trace(frame or sys._getframe().f_back)
@@ -1,1031 +1,1030 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Top-level display functions for displaying object in different formats."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 from __future__ import print_function
8 7
9 8 try:
10 9 from base64 import encodebytes as base64_encode
11 10 except ImportError:
12 11 from base64 import encodestring as base64_encode
13 12
14 13 import json
15 14 import mimetypes
16 15 import os
17 16 import struct
18 17 import sys
19 18 import warnings
20 19
21 20 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
22 21 unicode_type)
23 22 from IPython.testing.skipdoctest import skip_doctest
24 23
25 24 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
26 25 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
27 26 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
28 27 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript',
29 28 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
30 29 'publish_display_data']
31 30
32 31 #-----------------------------------------------------------------------------
33 32 # utility functions
34 33 #-----------------------------------------------------------------------------
35 34
36 35 def _safe_exists(path):
37 36 """Check path, but don't let exceptions raise"""
38 37 try:
39 38 return os.path.exists(path)
40 39 except Exception:
41 40 return False
42 41
43 42 def _merge(d1, d2):
44 43 """Like update, but merges sub-dicts instead of clobbering at the top level.
45 44
46 45 Updates d1 in-place
47 46 """
48 47
49 48 if not isinstance(d2, dict) or not isinstance(d1, dict):
50 49 return d2
51 50 for key, value in d2.items():
52 51 d1[key] = _merge(d1.get(key), value)
53 52 return d1
54 53
55 54 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
56 55 """internal implementation of all display_foo methods
57 56
58 57 Parameters
59 58 ----------
60 59 mimetype : str
61 60 The mimetype to be published (e.g. 'image/png')
62 61 objs : tuple of objects
63 62 The Python objects to display, or if raw=True raw text data to
64 63 display.
65 64 raw : bool
66 65 Are the data objects raw data or Python objects that need to be
67 66 formatted before display? [default: False]
68 67 metadata : dict (optional)
69 68 Metadata to be associated with the specific mimetype output.
70 69 """
71 70 if metadata:
72 71 metadata = {mimetype: metadata}
73 72 if raw:
74 73 # turn list of pngdata into list of { 'image/png': pngdata }
75 74 objs = [ {mimetype: obj} for obj in objs ]
76 75 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
77 76
78 77 #-----------------------------------------------------------------------------
79 78 # Main functions
80 79 #-----------------------------------------------------------------------------
81 80
82 81 def publish_display_data(data, metadata=None, source=None):
83 82 """Publish data and metadata to all frontends.
84 83
85 84 See the ``display_data`` message in the messaging documentation for
86 85 more details about this message type.
87 86
88 87 The following MIME types are currently implemented:
89 88
90 89 * text/plain
91 90 * text/html
92 91 * text/markdown
93 92 * text/latex
94 93 * application/json
95 94 * application/javascript
96 95 * image/png
97 96 * image/jpeg
98 97 * image/svg+xml
99 98
100 99 Parameters
101 100 ----------
102 101 data : dict
103 102 A dictionary having keys that are valid MIME types (like
104 103 'text/plain' or 'image/svg+xml') and values that are the data for
105 104 that MIME type. The data itself must be a JSON'able data
106 105 structure. Minimally all data should have the 'text/plain' data,
107 106 which can be displayed by all frontends. If more than the plain
108 107 text is given, it is up to the frontend to decide which
109 108 representation to use.
110 109 metadata : dict
111 110 A dictionary for metadata related to the data. This can contain
112 111 arbitrary key, value pairs that frontends can use to interpret
113 112 the data. mime-type keys matching those in data can be used
114 113 to specify metadata about particular representations.
115 114 source : str, deprecated
116 115 Unused.
117 116 """
118 117 from IPython.core.interactiveshell import InteractiveShell
119 118 InteractiveShell.instance().display_pub.publish(
120 119 data=data,
121 120 metadata=metadata,
122 121 )
123 122
124 123 def display(*objs, **kwargs):
125 124 """Display a Python object in all frontends.
126 125
127 126 By default all representations will be computed and sent to the frontends.
128 127 Frontends can decide which representation is used and how.
129 128
130 129 Parameters
131 130 ----------
132 131 objs : tuple of objects
133 132 The Python objects to display.
134 133 raw : bool, optional
135 134 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
136 135 or Python objects that need to be formatted before display? [default: False]
137 136 include : list or tuple, optional
138 137 A list of format type strings (MIME types) to include in the
139 138 format data dict. If this is set *only* the format types included
140 139 in this list will be computed.
141 140 exclude : list or tuple, optional
142 141 A list of format type strings (MIME types) to exclude in the format
143 142 data dict. If this is set all format types will be computed,
144 143 except for those included in this argument.
145 144 metadata : dict, optional
146 145 A dictionary of metadata to associate with the output.
147 146 mime-type keys in this dictionary will be associated with the individual
148 147 representation formats, if they exist.
149 148 """
150 149 raw = kwargs.get('raw', False)
151 150 include = kwargs.get('include')
152 151 exclude = kwargs.get('exclude')
153 152 metadata = kwargs.get('metadata')
154 153
155 154 from IPython.core.interactiveshell import InteractiveShell
156 155
157 156 if not raw:
158 157 format = InteractiveShell.instance().display_formatter.format
159 158
160 159 for obj in objs:
161 160 if raw:
162 161 publish_display_data(data=obj, metadata=metadata)
163 162 else:
164 163 format_dict, md_dict = format(obj, include=include, exclude=exclude)
165 164 if not format_dict:
166 165 # nothing to display (e.g. _ipython_display_ took over)
167 166 continue
168 167 if metadata:
169 168 # kwarg-specified metadata gets precedence
170 169 _merge(md_dict, metadata)
171 170 publish_display_data(data=format_dict, metadata=md_dict)
172 171
173 172
174 173 def display_pretty(*objs, **kwargs):
175 174 """Display the pretty (default) representation of an object.
176 175
177 176 Parameters
178 177 ----------
179 178 objs : tuple of objects
180 179 The Python objects to display, or if raw=True raw text data to
181 180 display.
182 181 raw : bool
183 182 Are the data objects raw data or Python objects that need to be
184 183 formatted before display? [default: False]
185 184 metadata : dict (optional)
186 185 Metadata to be associated with the specific mimetype output.
187 186 """
188 187 _display_mimetype('text/plain', objs, **kwargs)
189 188
190 189
191 190 def display_html(*objs, **kwargs):
192 191 """Display the HTML representation of an object.
193 192
194 193 Note: If raw=False and the object does not have a HTML
195 194 representation, no HTML will be shown.
196 195
197 196 Parameters
198 197 ----------
199 198 objs : tuple of objects
200 199 The Python objects to display, or if raw=True raw HTML data to
201 200 display.
202 201 raw : bool
203 202 Are the data objects raw data or Python objects that need to be
204 203 formatted before display? [default: False]
205 204 metadata : dict (optional)
206 205 Metadata to be associated with the specific mimetype output.
207 206 """
208 207 _display_mimetype('text/html', objs, **kwargs)
209 208
210 209
211 210 def display_markdown(*objs, **kwargs):
212 211 """Displays the Markdown representation of an object.
213 212
214 213 Parameters
215 214 ----------
216 215 objs : tuple of objects
217 216 The Python objects to display, or if raw=True raw markdown data to
218 217 display.
219 218 raw : bool
220 219 Are the data objects raw data or Python objects that need to be
221 220 formatted before display? [default: False]
222 221 metadata : dict (optional)
223 222 Metadata to be associated with the specific mimetype output.
224 223 """
225 224
226 225 _display_mimetype('text/markdown', objs, **kwargs)
227 226
228 227
229 228 def display_svg(*objs, **kwargs):
230 229 """Display the SVG representation of an object.
231 230
232 231 Parameters
233 232 ----------
234 233 objs : tuple of objects
235 234 The Python objects to display, or if raw=True raw svg data to
236 235 display.
237 236 raw : bool
238 237 Are the data objects raw data or Python objects that need to be
239 238 formatted before display? [default: False]
240 239 metadata : dict (optional)
241 240 Metadata to be associated with the specific mimetype output.
242 241 """
243 242 _display_mimetype('image/svg+xml', objs, **kwargs)
244 243
245 244
246 245 def display_png(*objs, **kwargs):
247 246 """Display the PNG representation of an object.
248 247
249 248 Parameters
250 249 ----------
251 250 objs : tuple of objects
252 251 The Python objects to display, or if raw=True raw png data to
253 252 display.
254 253 raw : bool
255 254 Are the data objects raw data or Python objects that need to be
256 255 formatted before display? [default: False]
257 256 metadata : dict (optional)
258 257 Metadata to be associated with the specific mimetype output.
259 258 """
260 259 _display_mimetype('image/png', objs, **kwargs)
261 260
262 261
263 262 def display_jpeg(*objs, **kwargs):
264 263 """Display the JPEG representation of an object.
265 264
266 265 Parameters
267 266 ----------
268 267 objs : tuple of objects
269 268 The Python objects to display, or if raw=True raw JPEG data to
270 269 display.
271 270 raw : bool
272 271 Are the data objects raw data or Python objects that need to be
273 272 formatted before display? [default: False]
274 273 metadata : dict (optional)
275 274 Metadata to be associated with the specific mimetype output.
276 275 """
277 276 _display_mimetype('image/jpeg', objs, **kwargs)
278 277
279 278
280 279 def display_latex(*objs, **kwargs):
281 280 """Display the LaTeX representation of an object.
282 281
283 282 Parameters
284 283 ----------
285 284 objs : tuple of objects
286 285 The Python objects to display, or if raw=True raw latex data to
287 286 display.
288 287 raw : bool
289 288 Are the data objects raw data or Python objects that need to be
290 289 formatted before display? [default: False]
291 290 metadata : dict (optional)
292 291 Metadata to be associated with the specific mimetype output.
293 292 """
294 293 _display_mimetype('text/latex', objs, **kwargs)
295 294
296 295
297 296 def display_json(*objs, **kwargs):
298 297 """Display the JSON representation of an object.
299 298
300 299 Note that not many frontends support displaying JSON.
301 300
302 301 Parameters
303 302 ----------
304 303 objs : tuple of objects
305 304 The Python objects to display, or if raw=True raw json data to
306 305 display.
307 306 raw : bool
308 307 Are the data objects raw data or Python objects that need to be
309 308 formatted before display? [default: False]
310 309 metadata : dict (optional)
311 310 Metadata to be associated with the specific mimetype output.
312 311 """
313 312 _display_mimetype('application/json', objs, **kwargs)
314 313
315 314
316 315 def display_javascript(*objs, **kwargs):
317 316 """Display the Javascript representation of an object.
318 317
319 318 Parameters
320 319 ----------
321 320 objs : tuple of objects
322 321 The Python objects to display, or if raw=True raw javascript data to
323 322 display.
324 323 raw : bool
325 324 Are the data objects raw data or Python objects that need to be
326 325 formatted before display? [default: False]
327 326 metadata : dict (optional)
328 327 Metadata to be associated with the specific mimetype output.
329 328 """
330 329 _display_mimetype('application/javascript', objs, **kwargs)
331 330
332 331
333 332 def display_pdf(*objs, **kwargs):
334 333 """Display the PDF representation of an object.
335 334
336 335 Parameters
337 336 ----------
338 337 objs : tuple of objects
339 338 The Python objects to display, or if raw=True raw javascript data to
340 339 display.
341 340 raw : bool
342 341 Are the data objects raw data or Python objects that need to be
343 342 formatted before display? [default: False]
344 343 metadata : dict (optional)
345 344 Metadata to be associated with the specific mimetype output.
346 345 """
347 346 _display_mimetype('application/pdf', objs, **kwargs)
348 347
349 348
350 349 #-----------------------------------------------------------------------------
351 350 # Smart classes
352 351 #-----------------------------------------------------------------------------
353 352
354 353
355 354 class DisplayObject(object):
356 355 """An object that wraps data to be displayed."""
357 356
358 357 _read_flags = 'r'
359 358 _show_mem_addr = False
360 359
361 360 def __init__(self, data=None, url=None, filename=None):
362 361 """Create a display object given raw data.
363 362
364 363 When this object is returned by an expression or passed to the
365 364 display function, it will result in the data being displayed
366 365 in the frontend. The MIME type of the data should match the
367 366 subclasses used, so the Png subclass should be used for 'image/png'
368 367 data. If the data is a URL, the data will first be downloaded
369 368 and then displayed. If
370 369
371 370 Parameters
372 371 ----------
373 372 data : unicode, str or bytes
374 373 The raw data or a URL or file to load the data from
375 374 url : unicode
376 375 A URL to download the data from.
377 376 filename : unicode
378 377 Path to a local file to load the data from.
379 378 """
380 379 if data is not None and isinstance(data, string_types):
381 380 if data.startswith('http') and url is None:
382 381 url = data
383 382 filename = None
384 383 data = None
385 384 elif _safe_exists(data) and filename is None:
386 385 url = None
387 386 filename = data
388 387 data = None
389 388
390 389 self.data = data
391 390 self.url = url
392 391 self.filename = None if filename is None else unicode_type(filename)
393 392
394 393 self.reload()
395 394 self._check_data()
396 395
397 396 def __repr__(self):
398 397 if not self._show_mem_addr:
399 398 cls = self.__class__
400 399 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
401 400 else:
402 401 r = super(DisplayObject, self).__repr__()
403 402 return r
404 403
405 404 def _check_data(self):
406 405 """Override in subclasses if there's something to check."""
407 406 pass
408 407
409 408 def reload(self):
410 409 """Reload the raw data from file or URL."""
411 410 if self.filename is not None:
412 411 with open(self.filename, self._read_flags) as f:
413 412 self.data = f.read()
414 413 elif self.url is not None:
415 414 try:
416 415 try:
417 416 from urllib.request import urlopen # Py3
418 417 except ImportError:
419 418 from urllib2 import urlopen
420 419 response = urlopen(self.url)
421 420 self.data = response.read()
422 421 # extract encoding from header, if there is one:
423 422 encoding = None
424 423 for sub in response.headers['content-type'].split(';'):
425 424 sub = sub.strip()
426 425 if sub.startswith('charset'):
427 426 encoding = sub.split('=')[-1].strip()
428 427 break
429 428 # decode data, if an encoding was specified
430 429 if encoding:
431 430 self.data = self.data.decode(encoding, 'replace')
432 431 except:
433 432 self.data = None
434 433
435 434 class TextDisplayObject(DisplayObject):
436 435 """Validate that display data is text"""
437 436 def _check_data(self):
438 437 if self.data is not None and not isinstance(self.data, string_types):
439 438 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
440 439
441 440 class Pretty(TextDisplayObject):
442 441
443 442 def _repr_pretty_(self):
444 443 return self.data
445 444
446 445
447 446 class HTML(TextDisplayObject):
448 447
449 448 def _repr_html_(self):
450 449 return self.data
451 450
452 451 def __html__(self):
453 452 """
454 453 This method exists to inform other HTML-using modules (e.g. Markupsafe,
455 454 htmltag, etc) that this object is HTML and does not need things like
456 455 special characters (<>&) escaped.
457 456 """
458 457 return self._repr_html_()
459 458
460 459
461 460 class Markdown(TextDisplayObject):
462 461
463 462 def _repr_markdown_(self):
464 463 return self.data
465 464
466 465
467 466 class Math(TextDisplayObject):
468 467
469 468 def _repr_latex_(self):
470 469 s = self.data.strip('$')
471 470 return "$$%s$$" % s
472 471
473 472
474 473 class Latex(TextDisplayObject):
475 474
476 475 def _repr_latex_(self):
477 476 return self.data
478 477
479 478
480 479 class SVG(DisplayObject):
481 480
482 481 # wrap data in a property, which extracts the <svg> tag, discarding
483 482 # document headers
484 483 _data = None
485 484
486 485 @property
487 486 def data(self):
488 487 return self._data
489 488
490 489 @data.setter
491 490 def data(self, svg):
492 491 if svg is None:
493 492 self._data = None
494 493 return
495 494 # parse into dom object
496 495 from xml.dom import minidom
497 496 svg = cast_bytes_py2(svg)
498 497 x = minidom.parseString(svg)
499 498 # get svg tag (should be 1)
500 499 found_svg = x.getElementsByTagName('svg')
501 500 if found_svg:
502 501 svg = found_svg[0].toxml()
503 502 else:
504 503 # fallback on the input, trust the user
505 504 # but this is probably an error.
506 505 pass
507 506 svg = cast_unicode(svg)
508 507 self._data = svg
509 508
510 509 def _repr_svg_(self):
511 510 return self.data
512 511
513 512
514 513 class JSON(DisplayObject):
515 514 """JSON expects a JSON-able dict or list
516 515
517 516 not an already-serialized JSON string.
518 517
519 518 Scalar types (None, number, string) are not allowed, only dict or list containers.
520 519 """
521 520 # wrap data in a property, which warns about passing already-serialized JSON
522 521 _data = None
523 522 def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None):
524 523 """Create a JSON display object given raw data.
525 524
526 525 Parameters
527 526 ----------
528 527 data : dict or list
529 528 JSON data to display. Not an already-serialized JSON string.
530 529 Scalar types (None, number, string) are not allowed, only dict
531 530 or list containers.
532 531 url : unicode
533 532 A URL to download the data from.
534 533 filename : unicode
535 534 Path to a local file to load the data from.
536 535 expanded : boolean
537 536 Metadata to control whether a JSON display component is expanded.
538 537 metadata: dict
539 538 Specify extra metadata to attach to the json display object.
540 539 """
541 540 self.expanded = expanded
542 541 self.metadata = metadata
543 542 super(JSON, self).__init__(data=data, url=url, filename=filename)
544 543
545 544 def _check_data(self):
546 545 if self.data is not None and not isinstance(self.data, (dict, list)):
547 546 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
548 547
549 548 @property
550 549 def data(self):
551 550 return self._data
552 551
553 552 @data.setter
554 553 def data(self, data):
555 554 if isinstance(data, string_types):
556 555 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
557 556 data = json.loads(data)
558 557 self._data = data
559 558
560 559 def _data_and_metadata(self):
561 560 md = {'expanded': self.expanded}
562 561 if self.metadata:
563 562 md.update(self.metadata)
564 563 return self.data, md
565 564
566 565 def _repr_json_(self):
567 566 return self._data_and_metadata()
568 567
569 568 css_t = """$("head").append($("<link/>").attr({
570 569 rel: "stylesheet",
571 570 type: "text/css",
572 571 href: "%s"
573 572 }));
574 573 """
575 574
576 575 lib_t1 = """$.getScript("%s", function () {
577 576 """
578 577 lib_t2 = """});
579 578 """
580 579
581 580 class Javascript(TextDisplayObject):
582 581
583 582 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
584 583 """Create a Javascript display object given raw data.
585 584
586 585 When this object is returned by an expression or passed to the
587 586 display function, it will result in the data being displayed
588 587 in the frontend. If the data is a URL, the data will first be
589 588 downloaded and then displayed.
590 589
591 590 In the Notebook, the containing element will be available as `element`,
592 591 and jQuery will be available. Content appended to `element` will be
593 592 visible in the output area.
594 593
595 594 Parameters
596 595 ----------
597 596 data : unicode, str or bytes
598 597 The Javascript source code or a URL to download it from.
599 598 url : unicode
600 599 A URL to download the data from.
601 600 filename : unicode
602 601 Path to a local file to load the data from.
603 602 lib : list or str
604 603 A sequence of Javascript library URLs to load asynchronously before
605 604 running the source code. The full URLs of the libraries should
606 605 be given. A single Javascript library URL can also be given as a
607 606 string.
608 607 css: : list or str
609 608 A sequence of css files to load before running the source code.
610 609 The full URLs of the css files should be given. A single css URL
611 610 can also be given as a string.
612 611 """
613 612 if isinstance(lib, string_types):
614 613 lib = [lib]
615 614 elif lib is None:
616 615 lib = []
617 616 if isinstance(css, string_types):
618 617 css = [css]
619 618 elif css is None:
620 619 css = []
621 620 if not isinstance(lib, (list,tuple)):
622 621 raise TypeError('expected sequence, got: %r' % lib)
623 622 if not isinstance(css, (list,tuple)):
624 623 raise TypeError('expected sequence, got: %r' % css)
625 624 self.lib = lib
626 625 self.css = css
627 626 super(Javascript, self).__init__(data=data, url=url, filename=filename)
628 627
629 628 def _repr_javascript_(self):
630 629 r = ''
631 630 for c in self.css:
632 631 r += css_t % c
633 632 for l in self.lib:
634 633 r += lib_t1 % l
635 634 r += self.data
636 635 r += lib_t2*len(self.lib)
637 636 return r
638 637
639 638 # constants for identifying png/jpeg data
640 639 _PNG = b'\x89PNG\r\n\x1a\n'
641 640 _JPEG = b'\xff\xd8'
642 641
643 642 def _pngxy(data):
644 643 """read the (width, height) from a PNG header"""
645 644 ihdr = data.index(b'IHDR')
646 645 # next 8 bytes are width/height
647 646 w4h4 = data[ihdr+4:ihdr+12]
648 647 return struct.unpack('>ii', w4h4)
649 648
650 649 def _jpegxy(data):
651 650 """read the (width, height) from a JPEG header"""
652 651 # adapted from http://www.64lines.com/jpeg-width-height
653 652
654 653 idx = 4
655 654 while True:
656 655 block_size = struct.unpack('>H', data[idx:idx+2])[0]
657 656 idx = idx + block_size
658 657 if data[idx:idx+2] == b'\xFF\xC0':
659 658 # found Start of Frame
660 659 iSOF = idx
661 660 break
662 661 else:
663 662 # read another block
664 663 idx += 2
665 664
666 665 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
667 666 return w, h
668 667
669 668 class Image(DisplayObject):
670 669
671 670 _read_flags = 'rb'
672 671 _FMT_JPEG = u'jpeg'
673 672 _FMT_PNG = u'png'
674 673 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
675 674
676 675 def __init__(self, data=None, url=None, filename=None, format=None,
677 676 embed=None, width=None, height=None, retina=False,
678 677 unconfined=False, metadata=None):
679 678 """Create a PNG/JPEG image object given raw data.
680 679
681 680 When this object is returned by an input cell or passed to the
682 681 display function, it will result in the image being displayed
683 682 in the frontend.
684 683
685 684 Parameters
686 685 ----------
687 686 data : unicode, str or bytes
688 687 The raw image data or a URL or filename to load the data from.
689 688 This always results in embedded image data.
690 689 url : unicode
691 690 A URL to download the data from. If you specify `url=`,
692 691 the image data will not be embedded unless you also specify `embed=True`.
693 692 filename : unicode
694 693 Path to a local file to load the data from.
695 694 Images from a file are always embedded.
696 695 format : unicode
697 696 The format of the image data (png/jpeg/jpg). If a filename or URL is given
698 697 for format will be inferred from the filename extension.
699 698 embed : bool
700 699 Should the image data be embedded using a data URI (True) or be
701 700 loaded using an <img> tag. Set this to True if you want the image
702 701 to be viewable later with no internet connection in the notebook.
703 702
704 703 Default is `True`, unless the keyword argument `url` is set, then
705 704 default value is `False`.
706 705
707 706 Note that QtConsole is not able to display images if `embed` is set to `False`
708 707 width : int
709 708 Width in pixels to which to constrain the image in html
710 709 height : int
711 710 Height in pixels to which to constrain the image in html
712 711 retina : bool
713 712 Automatically set the width and height to half of the measured
714 713 width and height.
715 714 This only works for embedded images because it reads the width/height
716 715 from image data.
717 716 For non-embedded images, you can just set the desired display width
718 717 and height directly.
719 718 unconfined: bool
720 719 Set unconfined=True to disable max-width confinement of the image.
721 720 metadata: dict
722 721 Specify extra metadata to attach to the image.
723 722
724 723 Examples
725 724 --------
726 725 # embedded image data, works in qtconsole and notebook
727 726 # when passed positionally, the first arg can be any of raw image data,
728 727 # a URL, or a filename from which to load image data.
729 728 # The result is always embedding image data for inline images.
730 729 Image('http://www.google.fr/images/srpr/logo3w.png')
731 730 Image('/path/to/image.jpg')
732 731 Image(b'RAW_PNG_DATA...')
733 732
734 733 # Specifying Image(url=...) does not embed the image data,
735 734 # it only generates `<img>` tag with a link to the source.
736 735 # This will not work in the qtconsole or offline.
737 736 Image(url='http://www.google.fr/images/srpr/logo3w.png')
738 737
739 738 """
740 739 if filename is not None:
741 740 ext = self._find_ext(filename)
742 741 elif url is not None:
743 742 ext = self._find_ext(url)
744 743 elif data is None:
745 744 raise ValueError("No image data found. Expecting filename, url, or data.")
746 745 elif isinstance(data, string_types) and (
747 746 data.startswith('http') or _safe_exists(data)
748 747 ):
749 748 ext = self._find_ext(data)
750 749 else:
751 750 ext = None
752 751
753 752 if format is None:
754 753 if ext is not None:
755 754 if ext == u'jpg' or ext == u'jpeg':
756 755 format = self._FMT_JPEG
757 756 if ext == u'png':
758 757 format = self._FMT_PNG
759 758 else:
760 759 format = ext.lower()
761 760 elif isinstance(data, bytes):
762 761 # infer image type from image data header,
763 762 # only if format has not been specified.
764 763 if data[:2] == _JPEG:
765 764 format = self._FMT_JPEG
766 765
767 766 # failed to detect format, default png
768 767 if format is None:
769 768 format = 'png'
770 769
771 770 if format.lower() == 'jpg':
772 771 # jpg->jpeg
773 772 format = self._FMT_JPEG
774 773
775 774 self.format = unicode_type(format).lower()
776 775 self.embed = embed if embed is not None else (url is None)
777 776
778 777 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
779 778 raise ValueError("Cannot embed the '%s' image format" % (self.format))
780 779 self.width = width
781 780 self.height = height
782 781 self.retina = retina
783 782 self.unconfined = unconfined
784 783 self.metadata = metadata
785 784 super(Image, self).__init__(data=data, url=url, filename=filename)
786 785
787 786 if retina:
788 787 self._retina_shape()
789 788
790 789 def _retina_shape(self):
791 790 """load pixel-doubled width and height from image data"""
792 791 if not self.embed:
793 792 return
794 793 if self.format == 'png':
795 794 w, h = _pngxy(self.data)
796 795 elif self.format == 'jpeg':
797 796 w, h = _jpegxy(self.data)
798 797 else:
799 798 # retina only supports png
800 799 return
801 800 self.width = w // 2
802 801 self.height = h // 2
803 802
804 803 def reload(self):
805 804 """Reload the raw data from file or URL."""
806 805 if self.embed:
807 806 super(Image,self).reload()
808 807 if self.retina:
809 808 self._retina_shape()
810 809
811 810 def _repr_html_(self):
812 811 if not self.embed:
813 812 width = height = klass = ''
814 813 if self.width:
815 814 width = ' width="%d"' % self.width
816 815 if self.height:
817 816 height = ' height="%d"' % self.height
818 817 if self.unconfined:
819 818 klass = ' class="unconfined"'
820 819 return u'<img src="{url}"{width}{height}{klass}/>'.format(
821 820 url=self.url,
822 821 width=width,
823 822 height=height,
824 823 klass=klass,
825 824 )
826 825
827 826 def _data_and_metadata(self):
828 827 """shortcut for returning metadata with shape information, if defined"""
829 828 md = {}
830 829 if self.width:
831 830 md['width'] = self.width
832 831 if self.height:
833 832 md['height'] = self.height
834 833 if self.unconfined:
835 834 md['unconfined'] = self.unconfined
836 835 if self.metadata:
837 836 md.update(self.metadata)
838 837 if md:
839 838 return self.data, md
840 839 else:
841 840 return self.data
842 841
843 842 def _repr_png_(self):
844 843 if self.embed and self.format == u'png':
845 844 return self._data_and_metadata()
846 845
847 846 def _repr_jpeg_(self):
848 847 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
849 848 return self._data_and_metadata()
850 849
851 850 def _find_ext(self, s):
852 851 return unicode_type(s.split('.')[-1].lower())
853 852
854 853 class Video(DisplayObject):
855 854
856 855 def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
857 856 """Create a video object given raw data or an URL.
858 857
859 858 When this object is returned by an input cell or passed to the
860 859 display function, it will result in the video being displayed
861 860 in the frontend.
862 861
863 862 Parameters
864 863 ----------
865 864 data : unicode, str or bytes
866 865 The raw video data or a URL or filename to load the data from.
867 866 Raw data will require passing `embed=True`.
868 867 url : unicode
869 868 A URL for the video. If you specify `url=`,
870 869 the image data will not be embedded.
871 870 filename : unicode
872 871 Path to a local file containing the video.
873 872 Will be interpreted as a local URL unless `embed=True`.
874 873 embed : bool
875 874 Should the video be embedded using a data URI (True) or be
876 875 loaded using a <video> tag (False).
877 876
878 877 Since videos are large, embedding them should be avoided, if possible.
879 878 You must confirm embedding as your intention by passing `embed=True`.
880 879
881 880 Local files can be displayed with URLs without embedding the content, via::
882 881
883 882 Video('./video.mp4')
884 883
885 884 mimetype: unicode
886 885 Specify the mimetype for embedded videos.
887 886 Default will be guessed from file extension, if available.
888 887
889 888 Examples
890 889 --------
891 890
892 891 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
893 892 Video('path/to/video.mp4')
894 893 Video('path/to/video.mp4', embed=True)
895 894 Video(b'raw-videodata', embed=True)
896 895 """
897 896 if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
898 897 url = data
899 898 data = None
900 899 elif os.path.exists(data):
901 900 filename = data
902 901 data = None
903 902
904 903 if data and not embed:
905 904 msg = ''.join([
906 905 "To embed videos, you must pass embed=True ",
907 906 "(this may make your notebook files huge)\n",
908 907 "Consider passing Video(url='...')",
909 908 ])
910 909 raise ValueError(msg)
911 910
912 911 self.mimetype = mimetype
913 912 self.embed = embed
914 913 super(Video, self).__init__(data=data, url=url, filename=filename)
915 914
916 915 def _repr_html_(self):
917 916 # External URLs and potentially local files are not embedded into the
918 917 # notebook output.
919 918 if not self.embed:
920 919 url = self.url if self.url is not None else self.filename
921 920 output = """<video src="{0}" controls>
922 921 Your browser does not support the <code>video</code> element.
923 922 </video>""".format(url)
924 923 return output
925 924
926 925 # Embedded videos are base64-encoded.
927 926 mimetype = self.mimetype
928 927 if self.filename is not None:
929 928 if not mimetype:
930 929 mimetype, _ = mimetypes.guess_type(self.filename)
931 930
932 931 with open(self.filename, 'rb') as f:
933 932 video = f.read()
934 933 else:
935 934 video = self.data
936 935 if isinstance(video, unicode_type):
937 936 # unicode input is already b64-encoded
938 937 b64_video = video
939 938 else:
940 939 b64_video = base64_encode(video).decode('ascii').rstrip()
941 940
942 941 output = """<video controls>
943 942 <source src="data:{0};base64,{1}" type="{0}">
944 943 Your browser does not support the video tag.
945 944 </video>""".format(mimetype, b64_video)
946 945 return output
947 946
948 947 def reload(self):
949 948 # TODO
950 949 pass
951 950
952 951 def _repr_png_(self):
953 952 # TODO
954 953 pass
955 954 def _repr_jpeg_(self):
956 955 # TODO
957 956 pass
958 957
959 958 def clear_output(wait=False):
960 959 """Clear the output of the current cell receiving output.
961 960
962 961 Parameters
963 962 ----------
964 963 wait : bool [default: false]
965 964 Wait to clear the output until new output is available to replace it."""
966 965 from IPython.core.interactiveshell import InteractiveShell
967 966 if InteractiveShell.initialized():
968 967 InteractiveShell.instance().display_pub.clear_output(wait)
969 968 else:
970 969 print('\033[2K\r', end='')
971 970 sys.stdout.flush()
972 971 print('\033[2K\r', end='')
973 972 sys.stderr.flush()
974 973
975 974
976 975 @skip_doctest
977 976 def set_matplotlib_formats(*formats, **kwargs):
978 977 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
979 978
980 979 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
981 980
982 981 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
983 982
984 983 To set this in your config files use the following::
985 984
986 985 c.InlineBackend.figure_formats = {'png', 'jpeg'}
987 986 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
988 987
989 988 Parameters
990 989 ----------
991 990 *formats : strs
992 991 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
993 992 **kwargs :
994 993 Keyword args will be relayed to ``figure.canvas.print_figure``.
995 994 """
996 995 from IPython.core.interactiveshell import InteractiveShell
997 996 from IPython.core.pylabtools import select_figure_formats
998 997 # build kwargs, starting with InlineBackend config
999 998 kw = {}
1000 999 from ipykernel.pylab.config import InlineBackend
1001 1000 cfg = InlineBackend.instance()
1002 1001 kw.update(cfg.print_figure_kwargs)
1003 1002 kw.update(**kwargs)
1004 1003 shell = InteractiveShell.instance()
1005 1004 select_figure_formats(shell, formats, **kw)
1006 1005
1007 1006 @skip_doctest
1008 1007 def set_matplotlib_close(close=True):
1009 1008 """Set whether the inline backend closes all figures automatically or not.
1010 1009
1011 1010 By default, the inline backend used in the IPython Notebook will close all
1012 1011 matplotlib figures automatically after each cell is run. This means that
1013 1012 plots in different cells won't interfere. Sometimes, you may want to make
1014 1013 a plot in one cell and then refine it in later cells. This can be accomplished
1015 1014 by::
1016 1015
1017 1016 In [1]: set_matplotlib_close(False)
1018 1017
1019 1018 To set this in your config files use the following::
1020 1019
1021 1020 c.InlineBackend.close_figures = False
1022 1021
1023 1022 Parameters
1024 1023 ----------
1025 1024 close : bool
1026 1025 Should all matplotlib figures be automatically closed after each cell is
1027 1026 run?
1028 1027 """
1029 1028 from ipykernel.pylab.config import InlineBackend
1030 1029 cfg = InlineBackend.instance()
1031 1030 cfg.close_figures = close
@@ -1,322 +1,321 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook for IPython.
3 3
4 4 This defines a callable class that IPython uses for `sys.displayhook`.
5 5 """
6 6
7 7 # Copyright (c) IPython Development Team.
8 8 # Distributed under the terms of the Modified BSD License.
9 9
10 from __future__ import print_function
11 10
12 11 import sys
13 12 import io as _io
14 13 import tokenize
15 14
16 15 from traitlets.config.configurable import Configurable
17 16 from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
18 17 from traitlets import Instance, Float
19 18 from warnings import warn
20 19
21 20 # TODO: Move the various attributes (cache_size, [others now moved]). Some
22 21 # of these are also attributes of InteractiveShell. They should be on ONE object
23 22 # only and the other objects should ask that one object for their values.
24 23
25 24 class DisplayHook(Configurable):
26 25 """The custom IPython displayhook to replace sys.displayhook.
27 26
28 27 This class does many things, but the basic idea is that it is a callable
29 28 that gets called anytime user code returns a value.
30 29 """
31 30
32 31 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
33 32 allow_none=True)
34 33 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
35 34 allow_none=True)
36 35 cull_fraction = Float(0.2)
37 36
38 37 def __init__(self, shell=None, cache_size=1000, **kwargs):
39 38 super(DisplayHook, self).__init__(shell=shell, **kwargs)
40 39 cache_size_min = 3
41 40 if cache_size <= 0:
42 41 self.do_full_cache = 0
43 42 cache_size = 0
44 43 elif cache_size < cache_size_min:
45 44 self.do_full_cache = 0
46 45 cache_size = 0
47 46 warn('caching was disabled (min value for cache size is %s).' %
48 47 cache_size_min,level=3)
49 48 else:
50 49 self.do_full_cache = 1
51 50
52 51 self.cache_size = cache_size
53 52
54 53 # we need a reference to the user-level namespace
55 54 self.shell = shell
56 55
57 56 self._,self.__,self.___ = '','',''
58 57
59 58 # these are deliberately global:
60 59 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
61 60 self.shell.user_ns.update(to_user_ns)
62 61
63 62 @property
64 63 def prompt_count(self):
65 64 return self.shell.execution_count
66 65
67 66 #-------------------------------------------------------------------------
68 67 # Methods used in __call__. Override these methods to modify the behavior
69 68 # of the displayhook.
70 69 #-------------------------------------------------------------------------
71 70
72 71 def check_for_underscore(self):
73 72 """Check if the user has set the '_' variable by hand."""
74 73 # If something injected a '_' variable in __builtin__, delete
75 74 # ipython's automatic one so we don't clobber that. gettext() in
76 75 # particular uses _, so we need to stay away from it.
77 76 if '_' in builtin_mod.__dict__:
78 77 try:
79 78 user_value = self.shell.user_ns['_']
80 79 if user_value is not self._:
81 80 return
82 81 del self.shell.user_ns['_']
83 82 except KeyError:
84 83 pass
85 84
86 85 def quiet(self):
87 86 """Should we silence the display hook because of ';'?"""
88 87 # do not print output if input ends in ';'
89 88
90 89 try:
91 90 cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
92 91 except IndexError:
93 92 # some uses of ipshellembed may fail here
94 93 return False
95 94
96 95 sio = _io.StringIO(cell)
97 96 tokens = list(tokenize.generate_tokens(sio.readline))
98 97
99 98 for token in reversed(tokens):
100 99 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
101 100 continue
102 101 if (token[0] == tokenize.OP) and (token[1] == ';'):
103 102 return True
104 103 else:
105 104 return False
106 105
107 106 def start_displayhook(self):
108 107 """Start the displayhook, initializing resources."""
109 108 pass
110 109
111 110 def write_output_prompt(self):
112 111 """Write the output prompt.
113 112
114 113 The default implementation simply writes the prompt to
115 114 ``sys.stdout``.
116 115 """
117 116 # Use write, not print which adds an extra space.
118 117 sys.stdout.write(self.shell.separate_out)
119 118 outprompt = 'Out[{}]: '.format(self.shell.execution_count)
120 119 if self.do_full_cache:
121 120 sys.stdout.write(outprompt)
122 121
123 122 def compute_format_data(self, result):
124 123 """Compute format data of the object to be displayed.
125 124
126 125 The format data is a generalization of the :func:`repr` of an object.
127 126 In the default implementation the format data is a :class:`dict` of
128 127 key value pair where the keys are valid MIME types and the values
129 128 are JSON'able data structure containing the raw data for that MIME
130 129 type. It is up to frontends to determine pick a MIME to to use and
131 130 display that data in an appropriate manner.
132 131
133 132 This method only computes the format data for the object and should
134 133 NOT actually print or write that to a stream.
135 134
136 135 Parameters
137 136 ----------
138 137 result : object
139 138 The Python object passed to the display hook, whose format will be
140 139 computed.
141 140
142 141 Returns
143 142 -------
144 143 (format_dict, md_dict) : dict
145 144 format_dict is a :class:`dict` whose keys are valid MIME types and values are
146 145 JSON'able raw data for that MIME type. It is recommended that
147 146 all return values of this should always include the "text/plain"
148 147 MIME type representation of the object.
149 148 md_dict is a :class:`dict` with the same MIME type keys
150 149 of metadata associated with each output.
151 150
152 151 """
153 152 return self.shell.display_formatter.format(result)
154 153
155 154 # This can be set to True by the write_output_prompt method in a subclass
156 155 prompt_end_newline = False
157 156
158 157 def write_format_data(self, format_dict, md_dict=None):
159 158 """Write the format data dict to the frontend.
160 159
161 160 This default version of this method simply writes the plain text
162 161 representation of the object to ``sys.stdout``. Subclasses should
163 162 override this method to send the entire `format_dict` to the
164 163 frontends.
165 164
166 165 Parameters
167 166 ----------
168 167 format_dict : dict
169 168 The format dict for the object passed to `sys.displayhook`.
170 169 md_dict : dict (optional)
171 170 The metadata dict to be associated with the display data.
172 171 """
173 172 if 'text/plain' not in format_dict:
174 173 # nothing to do
175 174 return
176 175 # We want to print because we want to always make sure we have a
177 176 # newline, even if all the prompt separators are ''. This is the
178 177 # standard IPython behavior.
179 178 result_repr = format_dict['text/plain']
180 179 if '\n' in result_repr:
181 180 # So that multi-line strings line up with the left column of
182 181 # the screen, instead of having the output prompt mess up
183 182 # their first line.
184 183 # We use the prompt template instead of the expanded prompt
185 184 # because the expansion may add ANSI escapes that will interfere
186 185 # with our ability to determine whether or not we should add
187 186 # a newline.
188 187 if not self.prompt_end_newline:
189 188 # But avoid extraneous empty lines.
190 189 result_repr = '\n' + result_repr
191 190
192 191 print(result_repr)
193 192
194 193 def update_user_ns(self, result):
195 194 """Update user_ns with various things like _, __, _1, etc."""
196 195
197 196 # Avoid recursive reference when displaying _oh/Out
198 197 if result is not self.shell.user_ns['_oh']:
199 198 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
200 199 self.cull_cache()
201 200
202 201 # Don't overwrite '_' and friends if '_' is in __builtin__
203 202 # (otherwise we cause buggy behavior for things like gettext). and
204 203 # do not overwrite _, __ or ___ if one of these has been assigned
205 204 # by the user.
206 205 update_unders = True
207 206 for unders in ['_'*i for i in range(1,4)]:
208 207 if not unders in self.shell.user_ns:
209 208 continue
210 209 if getattr(self, unders) is not self.shell.user_ns.get(unders):
211 210 update_unders = False
212 211
213 212 self.___ = self.__
214 213 self.__ = self._
215 214 self._ = result
216 215
217 216 if ('_' not in builtin_mod.__dict__) and (update_unders):
218 217 self.shell.push({'_':self._,
219 218 '__':self.__,
220 219 '___':self.___}, interactive=False)
221 220
222 221 # hackish access to top-level namespace to create _1,_2... dynamically
223 222 to_main = {}
224 223 if self.do_full_cache:
225 224 new_result = '_%s' % self.prompt_count
226 225 to_main[new_result] = result
227 226 self.shell.push(to_main, interactive=False)
228 227 self.shell.user_ns['_oh'][self.prompt_count] = result
229 228
230 229 def fill_exec_result(self, result):
231 230 if self.exec_result is not None:
232 231 self.exec_result.result = result
233 232
234 233 def log_output(self, format_dict):
235 234 """Log the output."""
236 235 if 'text/plain' not in format_dict:
237 236 # nothing to do
238 237 return
239 238 if self.shell.logger.log_output:
240 239 self.shell.logger.log_write(format_dict['text/plain'], 'output')
241 240 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
242 241 format_dict['text/plain']
243 242
244 243 def finish_displayhook(self):
245 244 """Finish up all displayhook activities."""
246 245 sys.stdout.write(self.shell.separate_out2)
247 246 sys.stdout.flush()
248 247
249 248 def __call__(self, result=None):
250 249 """Printing with history cache management.
251 250
252 251 This is invoked everytime the interpreter needs to print, and is
253 252 activated by setting the variable sys.displayhook to it.
254 253 """
255 254 self.check_for_underscore()
256 255 if result is not None and not self.quiet():
257 256 self.start_displayhook()
258 257 self.write_output_prompt()
259 258 format_dict, md_dict = self.compute_format_data(result)
260 259 self.update_user_ns(result)
261 260 self.fill_exec_result(result)
262 261 if format_dict:
263 262 self.write_format_data(format_dict, md_dict)
264 263 self.log_output(format_dict)
265 264 self.finish_displayhook()
266 265
267 266 def cull_cache(self):
268 267 """Output cache is full, cull the oldest entries"""
269 268 oh = self.shell.user_ns.get('_oh', {})
270 269 sz = len(oh)
271 270 cull_count = max(int(sz * self.cull_fraction), 2)
272 271 warn('Output cache limit (currently {sz} entries) hit.\n'
273 272 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
274 273
275 274 for i, n in enumerate(sorted(oh)):
276 275 if i >= cull_count:
277 276 break
278 277 self.shell.user_ns.pop('_%i' % n, None)
279 278 oh.pop(n, None)
280 279
281 280
282 281 def flush(self):
283 282 if not self.do_full_cache:
284 283 raise ValueError("You shouldn't have reached the cache flush "
285 284 "if full caching is not enabled!")
286 285 # delete auto-generated vars from global namespace
287 286
288 287 for n in range(1,self.prompt_count + 1):
289 288 key = '_'+repr(n)
290 289 try:
291 290 del self.shell.user_ns[key]
292 291 except: pass
293 292 # In some embedded circumstances, the user_ns doesn't have the
294 293 # '_oh' key set up.
295 294 oh = self.shell.user_ns.get('_oh', None)
296 295 if oh is not None:
297 296 oh.clear()
298 297
299 298 # Release our own references to objects:
300 299 self._, self.__, self.___ = '', '', ''
301 300
302 301 if '_' not in builtin_mod.__dict__:
303 302 self.shell.user_ns.update({'_':None,'__':None, '___':None})
304 303 import gc
305 304 # TODO: Is this really needed?
306 305 # IronPython blocks here forever
307 306 if sys.platform != "cli":
308 307 gc.collect()
309 308
310 309
311 310 class CapturingDisplayHook(object):
312 311 def __init__(self, shell, outputs=None):
313 312 self.shell = shell
314 313 if outputs is None:
315 314 outputs = []
316 315 self.outputs = outputs
317 316
318 317 def __call__(self, result=None):
319 318 if result is None:
320 319 return
321 320 format_dict, md_dict = self.shell.display_formatter.format(result)
322 321 self.outputs.append((format_dict, md_dict))
@@ -1,117 +1,116 b''
1 1 """An interface for publishing rich data to frontends.
2 2
3 3 There are two components of the display system:
4 4
5 5 * Display formatters, which take a Python object and compute the
6 6 representation of the object in various formats (text, HTML, SVG, etc.).
7 7 * The display publisher that is used to send the representation data to the
8 8 various frontends.
9 9
10 10 This module defines the logic display publishing. The display publisher uses
11 11 the ``display_data`` message type that is defined in the IPython messaging
12 12 spec.
13 13 """
14 14
15 15 # Copyright (c) IPython Development Team.
16 16 # Distributed under the terms of the Modified BSD License.
17 17
18 from __future__ import print_function
19 18
20 19 import sys
21 20
22 21 from traitlets.config.configurable import Configurable
23 22 from traitlets import List
24 23
25 24 # This used to be defined here - it is imported for backwards compatibility
26 25 from .display import publish_display_data
27 26
28 27 #-----------------------------------------------------------------------------
29 28 # Main payload class
30 29 #-----------------------------------------------------------------------------
31 30
32 31 class DisplayPublisher(Configurable):
33 32 """A traited class that publishes display data to frontends.
34 33
35 34 Instances of this class are created by the main IPython object and should
36 35 be accessed there.
37 36 """
38 37
39 38 def _validate_data(self, data, metadata=None):
40 39 """Validate the display data.
41 40
42 41 Parameters
43 42 ----------
44 43 data : dict
45 44 The formata data dictionary.
46 45 metadata : dict
47 46 Any metadata for the data.
48 47 """
49 48
50 49 if not isinstance(data, dict):
51 50 raise TypeError('data must be a dict, got: %r' % data)
52 51 if metadata is not None:
53 52 if not isinstance(metadata, dict):
54 53 raise TypeError('metadata must be a dict, got: %r' % data)
55 54
56 55 def publish(self, data, metadata=None, source=None):
57 56 """Publish data and metadata to all frontends.
58 57
59 58 See the ``display_data`` message in the messaging documentation for
60 59 more details about this message type.
61 60
62 61 The following MIME types are currently implemented:
63 62
64 63 * text/plain
65 64 * text/html
66 65 * text/markdown
67 66 * text/latex
68 67 * application/json
69 68 * application/javascript
70 69 * image/png
71 70 * image/jpeg
72 71 * image/svg+xml
73 72
74 73 Parameters
75 74 ----------
76 75 data : dict
77 76 A dictionary having keys that are valid MIME types (like
78 77 'text/plain' or 'image/svg+xml') and values that are the data for
79 78 that MIME type. The data itself must be a JSON'able data
80 79 structure. Minimally all data should have the 'text/plain' data,
81 80 which can be displayed by all frontends. If more than the plain
82 81 text is given, it is up to the frontend to decide which
83 82 representation to use.
84 83 metadata : dict
85 84 A dictionary for metadata related to the data. This can contain
86 85 arbitrary key, value pairs that frontends can use to interpret
87 86 the data. Metadata specific to each mime-type can be specified
88 87 in the metadata dict with the same mime-type keys as
89 88 the data itself.
90 89 source : str, deprecated
91 90 Unused.
92 91 """
93 92
94 93 # The default is to simply write the plain text data using sys.stdout.
95 94 if 'text/plain' in data:
96 95 print(data['text/plain'])
97 96
98 97 def clear_output(self, wait=False):
99 98 """Clear the output of the cell receiving output."""
100 99 print('\033[2K\r', end='')
101 100 sys.stdout.flush()
102 101 print('\033[2K\r', end='')
103 102 sys.stderr.flush()
104 103
105 104
106 105 class CapturingDisplayPublisher(DisplayPublisher):
107 106 """A DisplayPublisher that stores"""
108 107 outputs = List()
109 108
110 109 def publish(self, data, metadata=None, source=None):
111 110 self.outputs.append((data, metadata))
112 111
113 112 def clear_output(self, wait=False):
114 113 super(CapturingDisplayPublisher, self).clear_output(wait)
115 114
116 115 # empty the list, *do not* reassign a new list
117 116 del self.outputs[:]
@@ -1,131 +1,130 b''
1 1 """Infrastructure for registering and firing callbacks on application events.
2 2
3 3 Unlike :mod:`IPython.core.hooks`, which lets end users set single functions to
4 4 be called at specific times, or a collection of alternative methods to try,
5 5 callbacks are designed to be used by extension authors. A number of callbacks
6 6 can be registered for the same event without needing to be aware of one another.
7 7
8 8 The functions defined in this module are no-ops indicating the names of available
9 9 events and the arguments which will be passed to them.
10 10
11 11 .. note::
12 12
13 13 This API is experimental in IPython 2.0, and may be revised in future versions.
14 14 """
15 from __future__ import print_function
16 15
17 16 class EventManager(object):
18 17 """Manage a collection of events and a sequence of callbacks for each.
19 18
20 19 This is attached to :class:`~IPython.core.interactiveshell.InteractiveShell`
21 20 instances as an ``events`` attribute.
22 21
23 22 .. note::
24 23
25 24 This API is experimental in IPython 2.0, and may be revised in future versions.
26 25 """
27 26 def __init__(self, shell, available_events):
28 27 """Initialise the :class:`CallbackManager`.
29 28
30 29 Parameters
31 30 ----------
32 31 shell
33 32 The :class:`~IPython.core.interactiveshell.InteractiveShell` instance
34 33 available_callbacks
35 34 An iterable of names for callback events.
36 35 """
37 36 self.shell = shell
38 37 self.callbacks = {n:[] for n in available_events}
39 38
40 39 def register(self, event, function):
41 40 """Register a new event callback
42 41
43 42 Parameters
44 43 ----------
45 44 event : str
46 45 The event for which to register this callback.
47 46 function : callable
48 47 A function to be called on the given event. It should take the same
49 48 parameters as the appropriate callback prototype.
50 49
51 50 Raises
52 51 ------
53 52 TypeError
54 53 If ``function`` is not callable.
55 54 KeyError
56 55 If ``event`` is not one of the known events.
57 56 """
58 57 if not callable(function):
59 58 raise TypeError('Need a callable, got %r' % function)
60 59 self.callbacks[event].append(function)
61 60
62 61 def unregister(self, event, function):
63 62 """Remove a callback from the given event."""
64 63 self.callbacks[event].remove(function)
65 64
66 65 def trigger(self, event, *args, **kwargs):
67 66 """Call callbacks for ``event``.
68 67
69 68 Any additional arguments are passed to all callbacks registered for this
70 69 event. Exceptions raised by callbacks are caught, and a message printed.
71 70 """
72 71 for func in self.callbacks[event][:]:
73 72 try:
74 73 func(*args, **kwargs)
75 74 except Exception:
76 75 print("Error in callback {} (for {}):".format(func, event))
77 76 self.shell.showtraceback()
78 77
79 78 # event_name -> prototype mapping
80 79 available_events = {}
81 80
82 81 def _define_event(callback_proto):
83 82 available_events[callback_proto.__name__] = callback_proto
84 83 return callback_proto
85 84
86 85 # ------------------------------------------------------------------------------
87 86 # Callback prototypes
88 87 #
89 88 # No-op functions which describe the names of available events and the
90 89 # signatures of callbacks for those events.
91 90 # ------------------------------------------------------------------------------
92 91
93 92 @_define_event
94 93 def pre_execute():
95 94 """Fires before code is executed in response to user/frontend action.
96 95
97 96 This includes comm and widget messages and silent execution, as well as user
98 97 code cells."""
99 98 pass
100 99
101 100 @_define_event
102 101 def pre_run_cell():
103 102 """Fires before user-entered code runs."""
104 103 pass
105 104
106 105 @_define_event
107 106 def post_execute():
108 107 """Fires after code is executed in response to user/frontend action.
109 108
110 109 This includes comm and widget messages and silent execution, as well as user
111 110 code cells."""
112 111 pass
113 112
114 113 @_define_event
115 114 def post_run_cell():
116 115 """Fires after user-entered code runs."""
117 116 pass
118 117
119 118 @_define_event
120 119 def shell_initialized(ip):
121 120 """Fires after initialisation of :class:`~IPython.core.interactiveshell.InteractiveShell`.
122 121
123 122 This is before extensions and startup scripts are loaded, so it can only be
124 123 set by subclassing.
125 124
126 125 Parameters
127 126 ----------
128 127 ip : :class:`~IPython.core.interactiveshell.InteractiveShell`
129 128 The newly initialised shell.
130 129 """
131 130 pass
@@ -1,911 +1,910 b''
1 1 """ History related magics and functionality """
2 2
3 3 # Copyright (c) IPython Development Team.
4 4 # Distributed under the terms of the Modified BSD License.
5 5
6 from __future__ import print_function
7 6
8 7 import atexit
9 8 import datetime
10 9 import os
11 10 import re
12 11 try:
13 12 import sqlite3
14 13 except ImportError:
15 14 try:
16 15 from pysqlite2 import dbapi2 as sqlite3
17 16 except ImportError:
18 17 sqlite3 = None
19 18 import threading
20 19
21 20 from traitlets.config.configurable import LoggingConfigurable
22 21 from decorator import decorator
23 22 from IPython.utils.decorators import undoc
24 23 from IPython.utils.path import locate_profile
25 24 from IPython.utils import py3compat
26 25 from traitlets import (
27 26 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
28 27 default, observe,
29 28 )
30 29 from warnings import warn
31 30
32 31 #-----------------------------------------------------------------------------
33 32 # Classes and functions
34 33 #-----------------------------------------------------------------------------
35 34
36 35 @undoc
37 36 class DummyDB(object):
38 37 """Dummy DB that will act as a black hole for history.
39 38
40 39 Only used in the absence of sqlite"""
41 40 def execute(*args, **kwargs):
42 41 return []
43 42
44 43 def commit(self, *args, **kwargs):
45 44 pass
46 45
47 46 def __enter__(self, *args, **kwargs):
48 47 pass
49 48
50 49 def __exit__(self, *args, **kwargs):
51 50 pass
52 51
53 52
54 53 @decorator
55 54 def needs_sqlite(f, self, *a, **kw):
56 55 """Decorator: return an empty list in the absence of sqlite."""
57 56 if sqlite3 is None or not self.enabled:
58 57 return []
59 58 else:
60 59 return f(self, *a, **kw)
61 60
62 61
63 62 if sqlite3 is not None:
64 63 DatabaseError = sqlite3.DatabaseError
65 64 OperationalError = sqlite3.OperationalError
66 65 else:
67 66 @undoc
68 67 class DatabaseError(Exception):
69 68 "Dummy exception when sqlite could not be imported. Should never occur."
70 69
71 70 @undoc
72 71 class OperationalError(Exception):
73 72 "Dummy exception when sqlite could not be imported. Should never occur."
74 73
75 74 # use 16kB as threshold for whether a corrupt history db should be saved
76 75 # that should be at least 100 entries or so
77 76 _SAVE_DB_SIZE = 16384
78 77
79 78 @decorator
80 79 def catch_corrupt_db(f, self, *a, **kw):
81 80 """A decorator which wraps HistoryAccessor method calls to catch errors from
82 81 a corrupt SQLite database, move the old database out of the way, and create
83 82 a new one.
84 83
85 84 We avoid clobbering larger databases because this may be triggered due to filesystem issues,
86 85 not just a corrupt file.
87 86 """
88 87 try:
89 88 return f(self, *a, **kw)
90 89 except (DatabaseError, OperationalError) as e:
91 90 self._corrupt_db_counter += 1
92 91 self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
93 92 if self.hist_file != ':memory:':
94 93 if self._corrupt_db_counter > self._corrupt_db_limit:
95 94 self.hist_file = ':memory:'
96 95 self.log.error("Failed to load history too many times, history will not be saved.")
97 96 elif os.path.isfile(self.hist_file):
98 97 # move the file out of the way
99 98 base, ext = os.path.splitext(self.hist_file)
100 99 size = os.stat(self.hist_file).st_size
101 100 if size >= _SAVE_DB_SIZE:
102 101 # if there's significant content, avoid clobbering
103 102 now = datetime.datetime.now().isoformat().replace(':', '.')
104 103 newpath = base + '-corrupt-' + now + ext
105 104 # don't clobber previous corrupt backups
106 105 for i in range(100):
107 106 if not os.path.isfile(newpath):
108 107 break
109 108 else:
110 109 newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
111 110 else:
112 111 # not much content, possibly empty; don't worry about clobbering
113 112 # maybe we should just delete it?
114 113 newpath = base + '-corrupt' + ext
115 114 os.rename(self.hist_file, newpath)
116 115 self.log.error("History file was moved to %s and a new file created.", newpath)
117 116 self.init_db()
118 117 return []
119 118 else:
120 119 # Failed with :memory:, something serious is wrong
121 120 raise
122 121
123 122 class HistoryAccessorBase(LoggingConfigurable):
124 123 """An abstract class for History Accessors """
125 124
126 125 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
127 126 raise NotImplementedError
128 127
129 128 def search(self, pattern="*", raw=True, search_raw=True,
130 129 output=False, n=None, unique=False):
131 130 raise NotImplementedError
132 131
133 132 def get_range(self, session, start=1, stop=None, raw=True,output=False):
134 133 raise NotImplementedError
135 134
136 135 def get_range_by_str(self, rangestr, raw=True, output=False):
137 136 raise NotImplementedError
138 137
139 138
140 139 class HistoryAccessor(HistoryAccessorBase):
141 140 """Access the history database without adding to it.
142 141
143 142 This is intended for use by standalone history tools. IPython shells use
144 143 HistoryManager, below, which is a subclass of this."""
145 144
146 145 # counter for init_db retries, so we don't keep trying over and over
147 146 _corrupt_db_counter = 0
148 147 # after two failures, fallback on :memory:
149 148 _corrupt_db_limit = 2
150 149
151 150 # String holding the path to the history file
152 151 hist_file = Unicode(
153 152 help="""Path to file to use for SQLite history database.
154 153
155 154 By default, IPython will put the history database in the IPython
156 155 profile directory. If you would rather share one history among
157 156 profiles, you can set this value in each, so that they are consistent.
158 157
159 158 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
160 159 mounts. If you see IPython hanging, try setting this to something on a
161 160 local disk, e.g::
162 161
163 162 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
164 163
165 164 you can also use the specific value `:memory:` (including the colon
166 165 at both end but not the back ticks), to avoid creating an history file.
167 166
168 167 """).tag(config=True)
169 168
170 169 enabled = Bool(True,
171 170 help="""enable the SQLite history
172 171
173 172 set enabled=False to disable the SQLite history,
174 173 in which case there will be no stored history, no SQLite connection,
175 174 and no background saving thread. This may be necessary in some
176 175 threaded environments where IPython is embedded.
177 176 """
178 177 ).tag(config=True)
179 178
180 179 connection_options = Dict(
181 180 help="""Options for configuring the SQLite connection
182 181
183 182 These options are passed as keyword args to sqlite3.connect
184 183 when establishing database conenctions.
185 184 """
186 185 ).tag(config=True)
187 186
188 187 # The SQLite database
189 188 db = Any()
190 189 @observe('db')
191 190 def _db_changed(self, change):
192 191 """validate the db, since it can be an Instance of two different types"""
193 192 new = change['new']
194 193 connection_types = (DummyDB,)
195 194 if sqlite3 is not None:
196 195 connection_types = (DummyDB, sqlite3.Connection)
197 196 if not isinstance(new, connection_types):
198 197 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
199 198 (self.__class__.__name__, new)
200 199 raise TraitError(msg)
201 200
202 201 def __init__(self, profile='default', hist_file=u'', **traits):
203 202 """Create a new history accessor.
204 203
205 204 Parameters
206 205 ----------
207 206 profile : str
208 207 The name of the profile from which to open history.
209 208 hist_file : str
210 209 Path to an SQLite history database stored by IPython. If specified,
211 210 hist_file overrides profile.
212 211 config : :class:`~traitlets.config.loader.Config`
213 212 Config object. hist_file can also be set through this.
214 213 """
215 214 # We need a pointer back to the shell for various tasks.
216 215 super(HistoryAccessor, self).__init__(**traits)
217 216 # defer setting hist_file from kwarg until after init,
218 217 # otherwise the default kwarg value would clobber any value
219 218 # set by config
220 219 if hist_file:
221 220 self.hist_file = hist_file
222 221
223 222 if self.hist_file == u'':
224 223 # No one has set the hist_file, yet.
225 224 self.hist_file = self._get_hist_file_name(profile)
226 225
227 226 if sqlite3 is None and self.enabled:
228 227 warn("IPython History requires SQLite, your history will not be saved")
229 228 self.enabled = False
230 229
231 230 self.init_db()
232 231
233 232 def _get_hist_file_name(self, profile='default'):
234 233 """Find the history file for the given profile name.
235 234
236 235 This is overridden by the HistoryManager subclass, to use the shell's
237 236 active profile.
238 237
239 238 Parameters
240 239 ----------
241 240 profile : str
242 241 The name of a profile which has a history file.
243 242 """
244 243 return os.path.join(locate_profile(profile), 'history.sqlite')
245 244
246 245 @catch_corrupt_db
247 246 def init_db(self):
248 247 """Connect to the database, and create tables if necessary."""
249 248 if not self.enabled:
250 249 self.db = DummyDB()
251 250 return
252 251
253 252 # use detect_types so that timestamps return datetime objects
254 253 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
255 254 kwargs.update(self.connection_options)
256 255 self.db = sqlite3.connect(self.hist_file, **kwargs)
257 256 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
258 257 primary key autoincrement, start timestamp,
259 258 end timestamp, num_cmds integer, remark text)""")
260 259 self.db.execute("""CREATE TABLE IF NOT EXISTS history
261 260 (session integer, line integer, source text, source_raw text,
262 261 PRIMARY KEY (session, line))""")
263 262 # Output history is optional, but ensure the table's there so it can be
264 263 # enabled later.
265 264 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
266 265 (session integer, line integer, output text,
267 266 PRIMARY KEY (session, line))""")
268 267 self.db.commit()
269 268 # success! reset corrupt db count
270 269 self._corrupt_db_counter = 0
271 270
272 271 def writeout_cache(self):
273 272 """Overridden by HistoryManager to dump the cache before certain
274 273 database lookups."""
275 274 pass
276 275
277 276 ## -------------------------------
278 277 ## Methods for retrieving history:
279 278 ## -------------------------------
280 279 def _run_sql(self, sql, params, raw=True, output=False):
281 280 """Prepares and runs an SQL query for the history database.
282 281
283 282 Parameters
284 283 ----------
285 284 sql : str
286 285 Any filtering expressions to go after SELECT ... FROM ...
287 286 params : tuple
288 287 Parameters passed to the SQL query (to replace "?")
289 288 raw, output : bool
290 289 See :meth:`get_range`
291 290
292 291 Returns
293 292 -------
294 293 Tuples as :meth:`get_range`
295 294 """
296 295 toget = 'source_raw' if raw else 'source'
297 296 sqlfrom = "history"
298 297 if output:
299 298 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
300 299 toget = "history.%s, output_history.output" % toget
301 300 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
302 301 (toget, sqlfrom) + sql, params)
303 302 if output: # Regroup into 3-tuples, and parse JSON
304 303 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
305 304 return cur
306 305
307 306 @needs_sqlite
308 307 @catch_corrupt_db
309 308 def get_session_info(self, session):
310 309 """Get info about a session.
311 310
312 311 Parameters
313 312 ----------
314 313
315 314 session : int
316 315 Session number to retrieve.
317 316
318 317 Returns
319 318 -------
320 319
321 320 session_id : int
322 321 Session ID number
323 322 start : datetime
324 323 Timestamp for the start of the session.
325 324 end : datetime
326 325 Timestamp for the end of the session, or None if IPython crashed.
327 326 num_cmds : int
328 327 Number of commands run, or None if IPython crashed.
329 328 remark : unicode
330 329 A manually set description.
331 330 """
332 331 query = "SELECT * from sessions where session == ?"
333 332 return self.db.execute(query, (session,)).fetchone()
334 333
335 334 @catch_corrupt_db
336 335 def get_last_session_id(self):
337 336 """Get the last session ID currently in the database.
338 337
339 338 Within IPython, this should be the same as the value stored in
340 339 :attr:`HistoryManager.session_number`.
341 340 """
342 341 for record in self.get_tail(n=1, include_latest=True):
343 342 return record[0]
344 343
345 344 @catch_corrupt_db
346 345 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
347 346 """Get the last n lines from the history database.
348 347
349 348 Parameters
350 349 ----------
351 350 n : int
352 351 The number of lines to get
353 352 raw, output : bool
354 353 See :meth:`get_range`
355 354 include_latest : bool
356 355 If False (default), n+1 lines are fetched, and the latest one
357 356 is discarded. This is intended to be used where the function
358 357 is called by a user command, which it should not return.
359 358
360 359 Returns
361 360 -------
362 361 Tuples as :meth:`get_range`
363 362 """
364 363 self.writeout_cache()
365 364 if not include_latest:
366 365 n += 1
367 366 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
368 367 (n,), raw=raw, output=output)
369 368 if not include_latest:
370 369 return reversed(list(cur)[1:])
371 370 return reversed(list(cur))
372 371
373 372 @catch_corrupt_db
374 373 def search(self, pattern="*", raw=True, search_raw=True,
375 374 output=False, n=None, unique=False):
376 375 """Search the database using unix glob-style matching (wildcards
377 376 * and ?).
378 377
379 378 Parameters
380 379 ----------
381 380 pattern : str
382 381 The wildcarded pattern to match when searching
383 382 search_raw : bool
384 383 If True, search the raw input, otherwise, the parsed input
385 384 raw, output : bool
386 385 See :meth:`get_range`
387 386 n : None or int
388 387 If an integer is given, it defines the limit of
389 388 returned entries.
390 389 unique : bool
391 390 When it is true, return only unique entries.
392 391
393 392 Returns
394 393 -------
395 394 Tuples as :meth:`get_range`
396 395 """
397 396 tosearch = "source_raw" if search_raw else "source"
398 397 if output:
399 398 tosearch = "history." + tosearch
400 399 self.writeout_cache()
401 400 sqlform = "WHERE %s GLOB ?" % tosearch
402 401 params = (pattern,)
403 402 if unique:
404 403 sqlform += ' GROUP BY {0}'.format(tosearch)
405 404 if n is not None:
406 405 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
407 406 params += (n,)
408 407 elif unique:
409 408 sqlform += " ORDER BY session, line"
410 409 cur = self._run_sql(sqlform, params, raw=raw, output=output)
411 410 if n is not None:
412 411 return reversed(list(cur))
413 412 return cur
414 413
415 414 @catch_corrupt_db
416 415 def get_range(self, session, start=1, stop=None, raw=True,output=False):
417 416 """Retrieve input by session.
418 417
419 418 Parameters
420 419 ----------
421 420 session : int
422 421 Session number to retrieve.
423 422 start : int
424 423 First line to retrieve.
425 424 stop : int
426 425 End of line range (excluded from output itself). If None, retrieve
427 426 to the end of the session.
428 427 raw : bool
429 428 If True, return untranslated input
430 429 output : bool
431 430 If True, attempt to include output. This will be 'real' Python
432 431 objects for the current session, or text reprs from previous
433 432 sessions if db_log_output was enabled at the time. Where no output
434 433 is found, None is used.
435 434
436 435 Returns
437 436 -------
438 437 entries
439 438 An iterator over the desired lines. Each line is a 3-tuple, either
440 439 (session, line, input) if output is False, or
441 440 (session, line, (input, output)) if output is True.
442 441 """
443 442 if stop:
444 443 lineclause = "line >= ? AND line < ?"
445 444 params = (session, start, stop)
446 445 else:
447 446 lineclause = "line>=?"
448 447 params = (session, start)
449 448
450 449 return self._run_sql("WHERE session==? AND %s" % lineclause,
451 450 params, raw=raw, output=output)
452 451
453 452 def get_range_by_str(self, rangestr, raw=True, output=False):
454 453 """Get lines of history from a string of ranges, as used by magic
455 454 commands %hist, %save, %macro, etc.
456 455
457 456 Parameters
458 457 ----------
459 458 rangestr : str
460 459 A string specifying ranges, e.g. "5 ~2/1-4". See
461 460 :func:`magic_history` for full details.
462 461 raw, output : bool
463 462 As :meth:`get_range`
464 463
465 464 Returns
466 465 -------
467 466 Tuples as :meth:`get_range`
468 467 """
469 468 for sess, s, e in extract_hist_ranges(rangestr):
470 469 for line in self.get_range(sess, s, e, raw=raw, output=output):
471 470 yield line
472 471
473 472
474 473 class HistoryManager(HistoryAccessor):
475 474 """A class to organize all history-related functionality in one place.
476 475 """
477 476 # Public interface
478 477
479 478 # An instance of the IPython shell we are attached to
480 479 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
481 480 allow_none=True)
482 481 # Lists to hold processed and raw history. These start with a blank entry
483 482 # so that we can index them starting from 1
484 483 input_hist_parsed = List([""])
485 484 input_hist_raw = List([""])
486 485 # A list of directories visited during session
487 486 dir_hist = List()
488 487 @default('dir_hist')
489 488 def _dir_hist_default(self):
490 489 try:
491 490 return [py3compat.getcwd()]
492 491 except OSError:
493 492 return []
494 493
495 494 # A dict of output history, keyed with ints from the shell's
496 495 # execution count.
497 496 output_hist = Dict()
498 497 # The text/plain repr of outputs.
499 498 output_hist_reprs = Dict()
500 499
501 500 # The number of the current session in the history database
502 501 session_number = Integer()
503 502
504 503 db_log_output = Bool(False,
505 504 help="Should the history database include output? (default: no)"
506 505 ).tag(config=True)
507 506 db_cache_size = Integer(0,
508 507 help="Write to database every x commands (higher values save disk access & power).\n"
509 508 "Values of 1 or less effectively disable caching."
510 509 ).tag(config=True)
511 510 # The input and output caches
512 511 db_input_cache = List()
513 512 db_output_cache = List()
514 513
515 514 # History saving in separate thread
516 515 save_thread = Instance('IPython.core.history.HistorySavingThread',
517 516 allow_none=True)
518 517 try: # Event is a function returning an instance of _Event...
519 518 save_flag = Instance(threading._Event, allow_none=True)
520 519 except AttributeError: # ...until Python 3.3, when it's a class.
521 520 save_flag = Instance(threading.Event, allow_none=True)
522 521
523 522 # Private interface
524 523 # Variables used to store the three last inputs from the user. On each new
525 524 # history update, we populate the user's namespace with these, shifted as
526 525 # necessary.
527 526 _i00 = Unicode(u'')
528 527 _i = Unicode(u'')
529 528 _ii = Unicode(u'')
530 529 _iii = Unicode(u'')
531 530
532 531 # A regex matching all forms of the exit command, so that we don't store
533 532 # them in the history (it's annoying to rewind the first entry and land on
534 533 # an exit call).
535 534 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
536 535
537 536 def __init__(self, shell=None, config=None, **traits):
538 537 """Create a new history manager associated with a shell instance.
539 538 """
540 539 # We need a pointer back to the shell for various tasks.
541 540 super(HistoryManager, self).__init__(shell=shell, config=config,
542 541 **traits)
543 542 self.save_flag = threading.Event()
544 543 self.db_input_cache_lock = threading.Lock()
545 544 self.db_output_cache_lock = threading.Lock()
546 545
547 546 try:
548 547 self.new_session()
549 548 except OperationalError:
550 549 self.log.error("Failed to create history session in %s. History will not be saved.",
551 550 self.hist_file, exc_info=True)
552 551 self.hist_file = ':memory:'
553 552
554 553 if self.enabled and self.hist_file != ':memory:':
555 554 self.save_thread = HistorySavingThread(self)
556 555 self.save_thread.start()
557 556
558 557 def _get_hist_file_name(self, profile=None):
559 558 """Get default history file name based on the Shell's profile.
560 559
561 560 The profile parameter is ignored, but must exist for compatibility with
562 561 the parent class."""
563 562 profile_dir = self.shell.profile_dir.location
564 563 return os.path.join(profile_dir, 'history.sqlite')
565 564
566 565 @needs_sqlite
567 566 def new_session(self, conn=None):
568 567 """Get a new session number."""
569 568 if conn is None:
570 569 conn = self.db
571 570
572 571 with conn:
573 572 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
574 573 NULL, "") """, (datetime.datetime.now(),))
575 574 self.session_number = cur.lastrowid
576 575
577 576 def end_session(self):
578 577 """Close the database session, filling in the end time and line count."""
579 578 self.writeout_cache()
580 579 with self.db:
581 580 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
582 581 session==?""", (datetime.datetime.now(),
583 582 len(self.input_hist_parsed)-1, self.session_number))
584 583 self.session_number = 0
585 584
586 585 def name_session(self, name):
587 586 """Give the current session a name in the history database."""
588 587 with self.db:
589 588 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
590 589 (name, self.session_number))
591 590
592 591 def reset(self, new_session=True):
593 592 """Clear the session history, releasing all object references, and
594 593 optionally open a new session."""
595 594 self.output_hist.clear()
596 595 # The directory history can't be completely empty
597 596 self.dir_hist[:] = [py3compat.getcwd()]
598 597
599 598 if new_session:
600 599 if self.session_number:
601 600 self.end_session()
602 601 self.input_hist_parsed[:] = [""]
603 602 self.input_hist_raw[:] = [""]
604 603 self.new_session()
605 604
606 605 # ------------------------------
607 606 # Methods for retrieving history
608 607 # ------------------------------
609 608 def get_session_info(self, session=0):
610 609 """Get info about a session.
611 610
612 611 Parameters
613 612 ----------
614 613
615 614 session : int
616 615 Session number to retrieve. The current session is 0, and negative
617 616 numbers count back from current session, so -1 is the previous session.
618 617
619 618 Returns
620 619 -------
621 620
622 621 session_id : int
623 622 Session ID number
624 623 start : datetime
625 624 Timestamp for the start of the session.
626 625 end : datetime
627 626 Timestamp for the end of the session, or None if IPython crashed.
628 627 num_cmds : int
629 628 Number of commands run, or None if IPython crashed.
630 629 remark : unicode
631 630 A manually set description.
632 631 """
633 632 if session <= 0:
634 633 session += self.session_number
635 634
636 635 return super(HistoryManager, self).get_session_info(session=session)
637 636
638 637 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
639 638 """Get input and output history from the current session. Called by
640 639 get_range, and takes similar parameters."""
641 640 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
642 641
643 642 n = len(input_hist)
644 643 if start < 0:
645 644 start += n
646 645 if not stop or (stop > n):
647 646 stop = n
648 647 elif stop < 0:
649 648 stop += n
650 649
651 650 for i in range(start, stop):
652 651 if output:
653 652 line = (input_hist[i], self.output_hist_reprs.get(i))
654 653 else:
655 654 line = input_hist[i]
656 655 yield (0, i, line)
657 656
658 657 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
659 658 """Retrieve input by session.
660 659
661 660 Parameters
662 661 ----------
663 662 session : int
664 663 Session number to retrieve. The current session is 0, and negative
665 664 numbers count back from current session, so -1 is previous session.
666 665 start : int
667 666 First line to retrieve.
668 667 stop : int
669 668 End of line range (excluded from output itself). If None, retrieve
670 669 to the end of the session.
671 670 raw : bool
672 671 If True, return untranslated input
673 672 output : bool
674 673 If True, attempt to include output. This will be 'real' Python
675 674 objects for the current session, or text reprs from previous
676 675 sessions if db_log_output was enabled at the time. Where no output
677 676 is found, None is used.
678 677
679 678 Returns
680 679 -------
681 680 entries
682 681 An iterator over the desired lines. Each line is a 3-tuple, either
683 682 (session, line, input) if output is False, or
684 683 (session, line, (input, output)) if output is True.
685 684 """
686 685 if session <= 0:
687 686 session += self.session_number
688 687 if session==self.session_number: # Current session
689 688 return self._get_range_session(start, stop, raw, output)
690 689 return super(HistoryManager, self).get_range(session, start, stop, raw,
691 690 output)
692 691
693 692 ## ----------------------------
694 693 ## Methods for storing history:
695 694 ## ----------------------------
696 695 def store_inputs(self, line_num, source, source_raw=None):
697 696 """Store source and raw input in history and create input cache
698 697 variables ``_i*``.
699 698
700 699 Parameters
701 700 ----------
702 701 line_num : int
703 702 The prompt number of this input.
704 703
705 704 source : str
706 705 Python input.
707 706
708 707 source_raw : str, optional
709 708 If given, this is the raw input without any IPython transformations
710 709 applied to it. If not given, ``source`` is used.
711 710 """
712 711 if source_raw is None:
713 712 source_raw = source
714 713 source = source.rstrip('\n')
715 714 source_raw = source_raw.rstrip('\n')
716 715
717 716 # do not store exit/quit commands
718 717 if self._exit_re.match(source_raw.strip()):
719 718 return
720 719
721 720 self.input_hist_parsed.append(source)
722 721 self.input_hist_raw.append(source_raw)
723 722
724 723 with self.db_input_cache_lock:
725 724 self.db_input_cache.append((line_num, source, source_raw))
726 725 # Trigger to flush cache and write to DB.
727 726 if len(self.db_input_cache) >= self.db_cache_size:
728 727 self.save_flag.set()
729 728
730 729 # update the auto _i variables
731 730 self._iii = self._ii
732 731 self._ii = self._i
733 732 self._i = self._i00
734 733 self._i00 = source_raw
735 734
736 735 # hackish access to user namespace to create _i1,_i2... dynamically
737 736 new_i = '_i%s' % line_num
738 737 to_main = {'_i': self._i,
739 738 '_ii': self._ii,
740 739 '_iii': self._iii,
741 740 new_i : self._i00 }
742 741
743 742 if self.shell is not None:
744 743 self.shell.push(to_main, interactive=False)
745 744
746 745 def store_output(self, line_num):
747 746 """If database output logging is enabled, this saves all the
748 747 outputs from the indicated prompt number to the database. It's
749 748 called by run_cell after code has been executed.
750 749
751 750 Parameters
752 751 ----------
753 752 line_num : int
754 753 The line number from which to save outputs
755 754 """
756 755 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
757 756 return
758 757 output = self.output_hist_reprs[line_num]
759 758
760 759 with self.db_output_cache_lock:
761 760 self.db_output_cache.append((line_num, output))
762 761 if self.db_cache_size <= 1:
763 762 self.save_flag.set()
764 763
765 764 def _writeout_input_cache(self, conn):
766 765 with conn:
767 766 for line in self.db_input_cache:
768 767 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
769 768 (self.session_number,)+line)
770 769
771 770 def _writeout_output_cache(self, conn):
772 771 with conn:
773 772 for line in self.db_output_cache:
774 773 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
775 774 (self.session_number,)+line)
776 775
777 776 @needs_sqlite
778 777 def writeout_cache(self, conn=None):
779 778 """Write any entries in the cache to the database."""
780 779 if conn is None:
781 780 conn = self.db
782 781
783 782 with self.db_input_cache_lock:
784 783 try:
785 784 self._writeout_input_cache(conn)
786 785 except sqlite3.IntegrityError:
787 786 self.new_session(conn)
788 787 print("ERROR! Session/line number was not unique in",
789 788 "database. History logging moved to new session",
790 789 self.session_number)
791 790 try:
792 791 # Try writing to the new session. If this fails, don't
793 792 # recurse
794 793 self._writeout_input_cache(conn)
795 794 except sqlite3.IntegrityError:
796 795 pass
797 796 finally:
798 797 self.db_input_cache = []
799 798
800 799 with self.db_output_cache_lock:
801 800 try:
802 801 self._writeout_output_cache(conn)
803 802 except sqlite3.IntegrityError:
804 803 print("!! Session/line number for output was not unique",
805 804 "in database. Output will not be stored.")
806 805 finally:
807 806 self.db_output_cache = []
808 807
809 808
810 809 class HistorySavingThread(threading.Thread):
811 810 """This thread takes care of writing history to the database, so that
812 811 the UI isn't held up while that happens.
813 812
814 813 It waits for the HistoryManager's save_flag to be set, then writes out
815 814 the history cache. The main thread is responsible for setting the flag when
816 815 the cache size reaches a defined threshold."""
817 816 daemon = True
818 817 stop_now = False
819 818 enabled = True
820 819 def __init__(self, history_manager):
821 820 super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
822 821 self.history_manager = history_manager
823 822 self.enabled = history_manager.enabled
824 823 atexit.register(self.stop)
825 824
826 825 @needs_sqlite
827 826 def run(self):
828 827 # We need a separate db connection per thread:
829 828 try:
830 829 self.db = sqlite3.connect(self.history_manager.hist_file,
831 830 **self.history_manager.connection_options
832 831 )
833 832 while True:
834 833 self.history_manager.save_flag.wait()
835 834 if self.stop_now:
836 835 self.db.close()
837 836 return
838 837 self.history_manager.save_flag.clear()
839 838 self.history_manager.writeout_cache(self.db)
840 839 except Exception as e:
841 840 print(("The history saving thread hit an unexpected error (%s)."
842 841 "History will not be written to the database.") % repr(e))
843 842
844 843 def stop(self):
845 844 """This can be called from the main thread to safely stop this thread.
846 845
847 846 Note that it does not attempt to write out remaining history before
848 847 exiting. That should be done by calling the HistoryManager's
849 848 end_session method."""
850 849 self.stop_now = True
851 850 self.history_manager.save_flag.set()
852 851 self.join()
853 852
854 853
855 854 # To match, e.g. ~5/8-~2/3
856 855 range_re = re.compile(r"""
857 856 ((?P<startsess>~?\d+)/)?
858 857 (?P<start>\d+)?
859 858 ((?P<sep>[\-:])
860 859 ((?P<endsess>~?\d+)/)?
861 860 (?P<end>\d+))?
862 861 $""", re.VERBOSE)
863 862
864 863
865 864 def extract_hist_ranges(ranges_str):
866 865 """Turn a string of history ranges into 3-tuples of (session, start, stop).
867 866
868 867 Examples
869 868 --------
870 869 >>> list(extract_hist_ranges("~8/5-~7/4 2"))
871 870 [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
872 871 """
873 872 for range_str in ranges_str.split():
874 873 rmatch = range_re.match(range_str)
875 874 if not rmatch:
876 875 continue
877 876 start = rmatch.group("start")
878 877 if start:
879 878 start = int(start)
880 879 end = rmatch.group("end")
881 880 # If no end specified, get (a, a + 1)
882 881 end = int(end) if end else start + 1
883 882 else: # start not specified
884 883 if not rmatch.group('startsess'): # no startsess
885 884 continue
886 885 start = 1
887 886 end = None # provide the entire session hist
888 887
889 888 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
890 889 end += 1
891 890 startsess = rmatch.group("startsess") or "0"
892 891 endsess = rmatch.group("endsess") or startsess
893 892 startsess = int(startsess.replace("~","-"))
894 893 endsess = int(endsess.replace("~","-"))
895 894 assert endsess >= startsess, "start session must be earlier than end session"
896 895
897 896 if endsess == startsess:
898 897 yield (startsess, start, end)
899 898 continue
900 899 # Multiple sessions in one range:
901 900 yield (startsess, start, None)
902 901 for sess in range(startsess+1, endsess):
903 902 yield (sess, 1, None)
904 903 yield (endsess, 1, end)
905 904
906 905
907 906 def _format_lineno(session, line):
908 907 """Helper function to format line numbers properly."""
909 908 if session == 0:
910 909 return str(line)
911 910 return "%s#%s" % (session, line)
@@ -1,162 +1,161 b''
1 1 # encoding: utf-8
2 2 """
3 3 An application for managing IPython history.
4 4
5 5 To be invoked as the `ipython history` subcommand.
6 6 """
7 from __future__ import print_function
8 7
9 8 import os
10 9 import sqlite3
11 10
12 11 from traitlets.config.application import Application
13 12 from IPython.core.application import BaseIPythonApplication
14 13 from traitlets import Bool, Int, Dict
15 14 from IPython.utils.io import ask_yes_no
16 15
17 16 trim_hist_help = """Trim the IPython history database to the last 1000 entries.
18 17
19 18 This actually copies the last 1000 entries to a new database, and then replaces
20 19 the old file with the new. Use the `--keep=` argument to specify a number
21 20 other than 1000.
22 21 """
23 22
24 23 clear_hist_help = """Clear the IPython history database, deleting all entries.
25 24
26 25 Because this is a destructive operation, IPython will prompt the user if they
27 26 really want to do this. Passing a `-f` flag will force clearing without a
28 27 prompt.
29 28
30 29 This is an handy alias to `ipython history trim --keep=0`
31 30 """
32 31
33 32
34 33 class HistoryTrim(BaseIPythonApplication):
35 34 description = trim_hist_help
36 35
37 36 backup = Bool(False,
38 37 help="Keep the old history file as history.sqlite.<N>"
39 38 ).tag(config=True)
40 39
41 40 keep = Int(1000,
42 41 help="Number of recent lines to keep in the database."
43 42 ).tag(config=True)
44 43
45 44 flags = Dict(dict(
46 45 backup = ({'HistoryTrim' : {'backup' : True}},
47 46 backup.help
48 47 )
49 48 ))
50 49
51 50 aliases=Dict(dict(
52 51 keep = 'HistoryTrim.keep'
53 52 ))
54 53
55 54 def start(self):
56 55 profile_dir = self.profile_dir.location
57 56 hist_file = os.path.join(profile_dir, 'history.sqlite')
58 57 con = sqlite3.connect(hist_file)
59 58
60 59 # Grab the recent history from the current database.
61 60 inputs = list(con.execute('SELECT session, line, source, source_raw FROM '
62 61 'history ORDER BY session DESC, line DESC LIMIT ?', (self.keep+1,)))
63 62 if len(inputs) <= self.keep:
64 63 print("There are already at most %d entries in the history database." % self.keep)
65 64 print("Not doing anything. Use --keep= argument to keep fewer entries")
66 65 return
67 66
68 67 print("Trimming history to the most recent %d entries." % self.keep)
69 68
70 69 inputs.pop() # Remove the extra element we got to check the length.
71 70 inputs.reverse()
72 71 if inputs:
73 72 first_session = inputs[0][0]
74 73 outputs = list(con.execute('SELECT session, line, output FROM '
75 74 'output_history WHERE session >= ?', (first_session,)))
76 75 sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM '
77 76 'sessions WHERE session >= ?', (first_session,)))
78 77 con.close()
79 78
80 79 # Create the new history database.
81 80 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new')
82 81 i = 0
83 82 while os.path.exists(new_hist_file):
84 83 # Make sure we don't interfere with an existing file.
85 84 i += 1
86 85 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new'+str(i))
87 86 new_db = sqlite3.connect(new_hist_file)
88 87 new_db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
89 88 primary key autoincrement, start timestamp,
90 89 end timestamp, num_cmds integer, remark text)""")
91 90 new_db.execute("""CREATE TABLE IF NOT EXISTS history
92 91 (session integer, line integer, source text, source_raw text,
93 92 PRIMARY KEY (session, line))""")
94 93 new_db.execute("""CREATE TABLE IF NOT EXISTS output_history
95 94 (session integer, line integer, output text,
96 95 PRIMARY KEY (session, line))""")
97 96 new_db.commit()
98 97
99 98
100 99 if inputs:
101 100 with new_db:
102 101 # Add the recent history into the new database.
103 102 new_db.executemany('insert into sessions values (?,?,?,?,?)', sessions)
104 103 new_db.executemany('insert into history values (?,?,?,?)', inputs)
105 104 new_db.executemany('insert into output_history values (?,?,?)', outputs)
106 105 new_db.close()
107 106
108 107 if self.backup:
109 108 i = 1
110 109 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
111 110 while os.path.exists(backup_hist_file):
112 111 i += 1
113 112 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
114 113 os.rename(hist_file, backup_hist_file)
115 114 print("Backed up longer history file to", backup_hist_file)
116 115 else:
117 116 os.remove(hist_file)
118 117
119 118 os.rename(new_hist_file, hist_file)
120 119
121 120 class HistoryClear(HistoryTrim):
122 121 description = clear_hist_help
123 122 keep = Int(0,
124 123 help="Number of recent lines to keep in the database.")
125 124
126 125 force = Bool(False,
127 126 help="Don't prompt user for confirmation"
128 127 ).tag(config=True)
129 128
130 129 flags = Dict(dict(
131 130 force = ({'HistoryClear' : {'force' : True}},
132 131 force.help),
133 132 f = ({'HistoryTrim' : {'force' : True}},
134 133 force.help
135 134 )
136 135 ))
137 136 aliases = Dict()
138 137
139 138 def start(self):
140 139 if self.force or ask_yes_no("Really delete all ipython history? ",
141 140 default="no", interrupt="no"):
142 141 HistoryTrim.start(self)
143 142
144 143 class HistoryApp(Application):
145 144 name = u'ipython-history'
146 145 description = "Manage the IPython history database."
147 146
148 147 subcommands = Dict(dict(
149 148 trim = (HistoryTrim, HistoryTrim.description.splitlines()[0]),
150 149 clear = (HistoryClear, HistoryClear.description.splitlines()[0]),
151 150 ))
152 151
153 152 def start(self):
154 153 if self.subapp is None:
155 154 print("No subcommand specified. Must specify one of: %s" % \
156 155 (self.subcommands.keys()))
157 156 print()
158 157 self.print_description()
159 158 self.print_subcommands()
160 159 self.exit(1)
161 160 else:
162 161 return self.subapp.start()
@@ -1,3226 +1,3225 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 from __future__ import absolute_import, print_function
14 13
15 14 import __future__
16 15 import abc
17 16 import ast
18 17 import atexit
19 18 import functools
20 19 import os
21 20 import re
22 21 import runpy
23 22 import sys
24 23 import tempfile
25 24 import traceback
26 25 import types
27 26 import subprocess
28 27 import warnings
29 28 from io import open as io_open
30 29
31 30 from pickleshare import PickleShareDB
32 31
33 32 from traitlets.config.configurable import SingletonConfigurable
34 33 from IPython.core import oinspect
35 34 from IPython.core import magic
36 35 from IPython.core import page
37 36 from IPython.core import prefilter
38 37 from IPython.core import shadowns
39 38 from IPython.core import ultratb
40 39 from IPython.core.alias import Alias, AliasManager
41 40 from IPython.core.autocall import ExitAutocall
42 41 from IPython.core.builtin_trap import BuiltinTrap
43 42 from IPython.core.events import EventManager, available_events
44 43 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 44 from IPython.core.debugger import Pdb
46 45 from IPython.core.display_trap import DisplayTrap
47 46 from IPython.core.displayhook import DisplayHook
48 47 from IPython.core.displaypub import DisplayPublisher
49 48 from IPython.core.error import InputRejected, UsageError
50 49 from IPython.core.extensions import ExtensionManager
51 50 from IPython.core.formatters import DisplayFormatter
52 51 from IPython.core.history import HistoryManager
53 52 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
54 53 from IPython.core.logger import Logger
55 54 from IPython.core.macro import Macro
56 55 from IPython.core.payload import PayloadManager
57 56 from IPython.core.prefilter import PrefilterManager
58 57 from IPython.core.profiledir import ProfileDir
59 58 from IPython.core.usage import default_banner
60 59 from IPython.testing.skipdoctest import skip_doctest
61 60 from IPython.utils import PyColorize
62 61 from IPython.utils import io
63 62 from IPython.utils import py3compat
64 63 from IPython.utils import openpy
65 64 from IPython.utils.decorators import undoc
66 65 from IPython.utils.io import ask_yes_no
67 66 from IPython.utils.ipstruct import Struct
68 67 from IPython.paths import get_ipython_dir
69 68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
70 69 from IPython.utils.process import system, getoutput
71 70 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 71 with_metaclass, iteritems)
73 72 from IPython.utils.strdispatch import StrDispatch
74 73 from IPython.utils.syspathcontext import prepended_to_syspath
75 74 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 75 from IPython.utils.tempdir import TemporaryDirectory
77 76 from traitlets import (
78 77 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 78 observe, default,
80 79 )
81 80 from warnings import warn
82 81 from logging import error
83 82 import IPython.core.hooks
84 83
85 84 # NoOpContext is deprecated, but ipykernel imports it from here.
86 85 # See https://github.com/ipython/ipykernel/issues/157
87 86 from IPython.utils.contexts import NoOpContext
88 87
89 88 try:
90 89 import docrepr.sphinxify as sphx
91 90
92 91 def sphinxify(doc):
93 92 with TemporaryDirectory() as dirname:
94 93 return {
95 94 'text/html': sphx.sphinxify(doc, dirname),
96 95 'text/plain': doc
97 96 }
98 97 except ImportError:
99 98 sphinxify = None
100 99
101 100
102 101 class ProvisionalWarning(DeprecationWarning):
103 102 """
104 103 Warning class for unstable features
105 104 """
106 105 pass
107 106
108 107 #-----------------------------------------------------------------------------
109 108 # Globals
110 109 #-----------------------------------------------------------------------------
111 110
112 111 # compiled regexps for autoindent management
113 112 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
114 113
115 114 #-----------------------------------------------------------------------------
116 115 # Utilities
117 116 #-----------------------------------------------------------------------------
118 117
119 118 @undoc
120 119 def softspace(file, newvalue):
121 120 """Copied from code.py, to remove the dependency"""
122 121
123 122 oldvalue = 0
124 123 try:
125 124 oldvalue = file.softspace
126 125 except AttributeError:
127 126 pass
128 127 try:
129 128 file.softspace = newvalue
130 129 except (AttributeError, TypeError):
131 130 # "attribute-less object" or "read-only attributes"
132 131 pass
133 132 return oldvalue
134 133
135 134 @undoc
136 135 def no_op(*a, **kw): pass
137 136
138 137
139 138 class SpaceInInput(Exception): pass
140 139
141 140
142 141 def get_default_colors():
143 142 "DEPRECATED"
144 143 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
145 144 DeprecationWarning, stacklevel=2)
146 145 return 'Neutral'
147 146
148 147
149 148 class SeparateUnicode(Unicode):
150 149 r"""A Unicode subclass to validate separate_in, separate_out, etc.
151 150
152 151 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
153 152 """
154 153
155 154 def validate(self, obj, value):
156 155 if value == '0': value = ''
157 156 value = value.replace('\\n','\n')
158 157 return super(SeparateUnicode, self).validate(obj, value)
159 158
160 159
161 160 @undoc
162 161 class DummyMod(object):
163 162 """A dummy module used for IPython's interactive module when
164 163 a namespace must be assigned to the module's __dict__."""
165 164 pass
166 165
167 166
168 167 class ExecutionResult(object):
169 168 """The result of a call to :meth:`InteractiveShell.run_cell`
170 169
171 170 Stores information about what took place.
172 171 """
173 172 execution_count = None
174 173 error_before_exec = None
175 174 error_in_exec = None
176 175 result = None
177 176
178 177 @property
179 178 def success(self):
180 179 return (self.error_before_exec is None) and (self.error_in_exec is None)
181 180
182 181 def raise_error(self):
183 182 """Reraises error if `success` is `False`, otherwise does nothing"""
184 183 if self.error_before_exec is not None:
185 184 raise self.error_before_exec
186 185 if self.error_in_exec is not None:
187 186 raise self.error_in_exec
188 187
189 188 def __repr__(self):
190 189 name = self.__class__.__qualname__
191 190 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
192 191 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
193 192
194 193
195 194 class InteractiveShell(SingletonConfigurable):
196 195 """An enhanced, interactive shell for Python."""
197 196
198 197 _instance = None
199 198
200 199 ast_transformers = List([], help=
201 200 """
202 201 A list of ast.NodeTransformer subclass instances, which will be applied
203 202 to user input before code is run.
204 203 """
205 204 ).tag(config=True)
206 205
207 206 autocall = Enum((0,1,2), default_value=0, help=
208 207 """
209 208 Make IPython automatically call any callable object even if you didn't
210 209 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
211 210 automatically. The value can be '0' to disable the feature, '1' for
212 211 'smart' autocall, where it is not applied if there are no more
213 212 arguments on the line, and '2' for 'full' autocall, where all callable
214 213 objects are automatically called (even if no arguments are present).
215 214 """
216 215 ).tag(config=True)
217 216 # TODO: remove all autoindent logic and put into frontends.
218 217 # We can't do this yet because even runlines uses the autoindent.
219 218 autoindent = Bool(True, help=
220 219 """
221 220 Autoindent IPython code entered interactively.
222 221 """
223 222 ).tag(config=True)
224 223
225 224 automagic = Bool(True, help=
226 225 """
227 226 Enable magic commands to be called without the leading %.
228 227 """
229 228 ).tag(config=True)
230 229
231 230 banner1 = Unicode(default_banner,
232 231 help="""The part of the banner to be printed before the profile"""
233 232 ).tag(config=True)
234 233 banner2 = Unicode('',
235 234 help="""The part of the banner to be printed after the profile"""
236 235 ).tag(config=True)
237 236
238 237 cache_size = Integer(1000, help=
239 238 """
240 239 Set the size of the output cache. The default is 1000, you can
241 240 change it permanently in your config file. Setting it to 0 completely
242 241 disables the caching system, and the minimum value accepted is 20 (if
243 242 you provide a value less than 20, it is reset to 0 and a warning is
244 243 issued). This limit is defined because otherwise you'll spend more
245 244 time re-flushing a too small cache than working
246 245 """
247 246 ).tag(config=True)
248 247 color_info = Bool(True, help=
249 248 """
250 249 Use colors for displaying information about objects. Because this
251 250 information is passed through a pager (like 'less'), and some pagers
252 251 get confused with color codes, this capability can be turned off.
253 252 """
254 253 ).tag(config=True)
255 254 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
256 255 default_value='Neutral',
257 256 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
258 257 ).tag(config=True)
259 258 debug = Bool(False).tag(config=True)
260 259 disable_failing_post_execute = Bool(False,
261 260 help="Don't call post-execute functions that have failed in the past."
262 261 ).tag(config=True)
263 262 display_formatter = Instance(DisplayFormatter, allow_none=True)
264 263 displayhook_class = Type(DisplayHook)
265 264 display_pub_class = Type(DisplayPublisher)
266 265
267 266 sphinxify_docstring = Bool(False, help=
268 267 """
269 268 Enables rich html representation of docstrings. (This requires the
270 269 docrepr module).
271 270 """).tag(config=True)
272 271
273 272 @observe("sphinxify_docstring")
274 273 def _sphinxify_docstring_changed(self, change):
275 274 if change['new']:
276 275 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
277 276
278 277 enable_html_pager = Bool(False, help=
279 278 """
280 279 (Provisional API) enables html representation in mime bundles sent
281 280 to pagers.
282 281 """).tag(config=True)
283 282
284 283 @observe("enable_html_pager")
285 284 def _enable_html_pager_changed(self, change):
286 285 if change['new']:
287 286 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
288 287
289 288 data_pub_class = None
290 289
291 290 exit_now = Bool(False)
292 291 exiter = Instance(ExitAutocall)
293 292 @default('exiter')
294 293 def _exiter_default(self):
295 294 return ExitAutocall(self)
296 295 # Monotonically increasing execution counter
297 296 execution_count = Integer(1)
298 297 filename = Unicode("<ipython console>")
299 298 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
300 299
301 300 # Input splitter, to transform input line by line and detect when a block
302 301 # is ready to be executed.
303 302 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
304 303 (), {'line_input_checker': True})
305 304
306 305 # This InputSplitter instance is used to transform completed cells before
307 306 # running them. It allows cell magics to contain blank lines.
308 307 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
309 308 (), {'line_input_checker': False})
310 309
311 310 logstart = Bool(False, help=
312 311 """
313 312 Start logging to the default log file in overwrite mode.
314 313 Use `logappend` to specify a log file to **append** logs to.
315 314 """
316 315 ).tag(config=True)
317 316 logfile = Unicode('', help=
318 317 """
319 318 The name of the logfile to use.
320 319 """
321 320 ).tag(config=True)
322 321 logappend = Unicode('', help=
323 322 """
324 323 Start logging to the given file in append mode.
325 324 Use `logfile` to specify a log file to **overwrite** logs to.
326 325 """
327 326 ).tag(config=True)
328 327 object_info_string_level = Enum((0,1,2), default_value=0,
329 328 ).tag(config=True)
330 329 pdb = Bool(False, help=
331 330 """
332 331 Automatically call the pdb debugger after every exception.
333 332 """
334 333 ).tag(config=True)
335 334 display_page = Bool(False,
336 335 help="""If True, anything that would be passed to the pager
337 336 will be displayed as regular output instead."""
338 337 ).tag(config=True)
339 338
340 339 # deprecated prompt traits:
341 340
342 341 prompt_in1 = Unicode('In [\\#]: ',
343 342 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
344 343 ).tag(config=True)
345 344 prompt_in2 = Unicode(' .\\D.: ',
346 345 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
347 346 ).tag(config=True)
348 347 prompt_out = Unicode('Out[\\#]: ',
349 348 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
350 349 ).tag(config=True)
351 350 prompts_pad_left = Bool(True,
352 351 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
353 352 ).tag(config=True)
354 353
355 354 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
356 355 def _prompt_trait_changed(self, change):
357 356 name = change['name']
358 357 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
359 358 name=name)
360 359 )
361 360 # protect against weird cases where self.config may not exist:
362 361
363 362 show_rewritten_input = Bool(True,
364 363 help="Show rewritten input, e.g. for autocall."
365 364 ).tag(config=True)
366 365
367 366 quiet = Bool(False).tag(config=True)
368 367
369 368 history_length = Integer(10000,
370 369 help='Total length of command history'
371 370 ).tag(config=True)
372 371
373 372 history_load_length = Integer(1000, help=
374 373 """
375 374 The number of saved history entries to be loaded
376 375 into the history buffer at startup.
377 376 """
378 377 ).tag(config=True)
379 378
380 379 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
381 380 default_value='last_expr',
382 381 help="""
383 382 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
384 383 run interactively (displaying output from expressions)."""
385 384 ).tag(config=True)
386 385
387 386 # TODO: this part of prompt management should be moved to the frontends.
388 387 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
389 388 separate_in = SeparateUnicode('\n').tag(config=True)
390 389 separate_out = SeparateUnicode('').tag(config=True)
391 390 separate_out2 = SeparateUnicode('').tag(config=True)
392 391 wildcards_case_sensitive = Bool(True).tag(config=True)
393 392 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
394 393 default_value='Context').tag(config=True)
395 394
396 395 # Subcomponents of InteractiveShell
397 396 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
398 397 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
399 398 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
400 399 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
401 400 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
402 401 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
403 402 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
404 403 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
405 404
406 405 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
407 406 @property
408 407 def profile(self):
409 408 if self.profile_dir is not None:
410 409 name = os.path.basename(self.profile_dir.location)
411 410 return name.replace('profile_','')
412 411
413 412
414 413 # Private interface
415 414 _post_execute = Dict()
416 415
417 416 # Tracks any GUI loop loaded for pylab
418 417 pylab_gui_select = None
419 418
420 419 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
421 420
422 421 def __init__(self, ipython_dir=None, profile_dir=None,
423 422 user_module=None, user_ns=None,
424 423 custom_exceptions=((), None), **kwargs):
425 424
426 425 # This is where traits with a config_key argument are updated
427 426 # from the values on config.
428 427 super(InteractiveShell, self).__init__(**kwargs)
429 428 if 'PromptManager' in self.config:
430 429 warn('As of IPython 5.0 `PromptManager` config will have no effect'
431 430 ' and has been replaced by TerminalInteractiveShell.prompts_class')
432 431 self.configurables = [self]
433 432
434 433 # These are relatively independent and stateless
435 434 self.init_ipython_dir(ipython_dir)
436 435 self.init_profile_dir(profile_dir)
437 436 self.init_instance_attrs()
438 437 self.init_environment()
439 438
440 439 # Check if we're in a virtualenv, and set up sys.path.
441 440 self.init_virtualenv()
442 441
443 442 # Create namespaces (user_ns, user_global_ns, etc.)
444 443 self.init_create_namespaces(user_module, user_ns)
445 444 # This has to be done after init_create_namespaces because it uses
446 445 # something in self.user_ns, but before init_sys_modules, which
447 446 # is the first thing to modify sys.
448 447 # TODO: When we override sys.stdout and sys.stderr before this class
449 448 # is created, we are saving the overridden ones here. Not sure if this
450 449 # is what we want to do.
451 450 self.save_sys_module_state()
452 451 self.init_sys_modules()
453 452
454 453 # While we're trying to have each part of the code directly access what
455 454 # it needs without keeping redundant references to objects, we have too
456 455 # much legacy code that expects ip.db to exist.
457 456 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
458 457
459 458 self.init_history()
460 459 self.init_encoding()
461 460 self.init_prefilter()
462 461
463 462 self.init_syntax_highlighting()
464 463 self.init_hooks()
465 464 self.init_events()
466 465 self.init_pushd_popd_magic()
467 466 self.init_user_ns()
468 467 self.init_logger()
469 468 self.init_builtins()
470 469
471 470 # The following was in post_config_initialization
472 471 self.init_inspector()
473 472 self.raw_input_original = input
474 473 self.init_completer()
475 474 # TODO: init_io() needs to happen before init_traceback handlers
476 475 # because the traceback handlers hardcode the stdout/stderr streams.
477 476 # This logic in in debugger.Pdb and should eventually be changed.
478 477 self.init_io()
479 478 self.init_traceback_handlers(custom_exceptions)
480 479 self.init_prompts()
481 480 self.init_display_formatter()
482 481 self.init_display_pub()
483 482 self.init_data_pub()
484 483 self.init_displayhook()
485 484 self.init_magics()
486 485 self.init_alias()
487 486 self.init_logstart()
488 487 self.init_pdb()
489 488 self.init_extension_manager()
490 489 self.init_payload()
491 490 self.init_deprecation_warnings()
492 491 self.hooks.late_startup_hook()
493 492 self.events.trigger('shell_initialized', self)
494 493 atexit.register(self.atexit_operations)
495 494
496 495 def get_ipython(self):
497 496 """Return the currently running IPython instance."""
498 497 return self
499 498
500 499 #-------------------------------------------------------------------------
501 500 # Trait changed handlers
502 501 #-------------------------------------------------------------------------
503 502 @observe('ipython_dir')
504 503 def _ipython_dir_changed(self, change):
505 504 ensure_dir_exists(change['new'])
506 505
507 506 def set_autoindent(self,value=None):
508 507 """Set the autoindent flag.
509 508
510 509 If called with no arguments, it acts as a toggle."""
511 510 if value is None:
512 511 self.autoindent = not self.autoindent
513 512 else:
514 513 self.autoindent = value
515 514
516 515 #-------------------------------------------------------------------------
517 516 # init_* methods called by __init__
518 517 #-------------------------------------------------------------------------
519 518
520 519 def init_ipython_dir(self, ipython_dir):
521 520 if ipython_dir is not None:
522 521 self.ipython_dir = ipython_dir
523 522 return
524 523
525 524 self.ipython_dir = get_ipython_dir()
526 525
527 526 def init_profile_dir(self, profile_dir):
528 527 if profile_dir is not None:
529 528 self.profile_dir = profile_dir
530 529 return
531 530 self.profile_dir =\
532 531 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
533 532
534 533 def init_instance_attrs(self):
535 534 self.more = False
536 535
537 536 # command compiler
538 537 self.compile = CachingCompiler()
539 538
540 539 # Make an empty namespace, which extension writers can rely on both
541 540 # existing and NEVER being used by ipython itself. This gives them a
542 541 # convenient location for storing additional information and state
543 542 # their extensions may require, without fear of collisions with other
544 543 # ipython names that may develop later.
545 544 self.meta = Struct()
546 545
547 546 # Temporary files used for various purposes. Deleted at exit.
548 547 self.tempfiles = []
549 548 self.tempdirs = []
550 549
551 550 # keep track of where we started running (mainly for crash post-mortem)
552 551 # This is not being used anywhere currently.
553 552 self.starting_dir = py3compat.getcwd()
554 553
555 554 # Indentation management
556 555 self.indent_current_nsp = 0
557 556
558 557 # Dict to track post-execution functions that have been registered
559 558 self._post_execute = {}
560 559
561 560 def init_environment(self):
562 561 """Any changes we need to make to the user's environment."""
563 562 pass
564 563
565 564 def init_encoding(self):
566 565 # Get system encoding at startup time. Certain terminals (like Emacs
567 566 # under Win32 have it set to None, and we need to have a known valid
568 567 # encoding to use in the raw_input() method
569 568 try:
570 569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
571 570 except AttributeError:
572 571 self.stdin_encoding = 'ascii'
573 572
574 573
575 574 @observe('colors')
576 575 def init_syntax_highlighting(self, changes=None):
577 576 # Python source parser/formatter for syntax highlighting
578 577 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
579 578 self.pycolorize = lambda src: pyformat(src,'str')
580 579
581 580 def refresh_style(self):
582 581 # No-op here, used in subclass
583 582 pass
584 583
585 584 def init_pushd_popd_magic(self):
586 585 # for pushd/popd management
587 586 self.home_dir = get_home_dir()
588 587
589 588 self.dir_stack = []
590 589
591 590 def init_logger(self):
592 591 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
593 592 logmode='rotate')
594 593
595 594 def init_logstart(self):
596 595 """Initialize logging in case it was requested at the command line.
597 596 """
598 597 if self.logappend:
599 598 self.magic('logstart %s append' % self.logappend)
600 599 elif self.logfile:
601 600 self.magic('logstart %s' % self.logfile)
602 601 elif self.logstart:
603 602 self.magic('logstart')
604 603
605 604 def init_deprecation_warnings(self):
606 605 """
607 606 register default filter for deprecation warning.
608 607
609 608 This will allow deprecation warning of function used interactively to show
610 609 warning to users, and still hide deprecation warning from libraries import.
611 610 """
612 611 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
613 612
614 613 def init_builtins(self):
615 614 # A single, static flag that we set to True. Its presence indicates
616 615 # that an IPython shell has been created, and we make no attempts at
617 616 # removing on exit or representing the existence of more than one
618 617 # IPython at a time.
619 618 builtin_mod.__dict__['__IPYTHON__'] = True
620 619
621 620 self.builtin_trap = BuiltinTrap(shell=self)
622 621
623 622 def init_inspector(self):
624 623 # Object inspector
625 624 self.inspector = oinspect.Inspector(oinspect.InspectColors,
626 625 PyColorize.ANSICodeColors,
627 626 'NoColor',
628 627 self.object_info_string_level)
629 628
630 629 def init_io(self):
631 630 # This will just use sys.stdout and sys.stderr. If you want to
632 631 # override sys.stdout and sys.stderr themselves, you need to do that
633 632 # *before* instantiating this class, because io holds onto
634 633 # references to the underlying streams.
635 634 # io.std* are deprecated, but don't show our own deprecation warnings
636 635 # during initialization of the deprecated API.
637 636 with warnings.catch_warnings():
638 637 warnings.simplefilter('ignore', DeprecationWarning)
639 638 io.stdout = io.IOStream(sys.stdout)
640 639 io.stderr = io.IOStream(sys.stderr)
641 640
642 641 def init_prompts(self):
643 642 # Set system prompts, so that scripts can decide if they are running
644 643 # interactively.
645 644 sys.ps1 = 'In : '
646 645 sys.ps2 = '...: '
647 646 sys.ps3 = 'Out: '
648 647
649 648 def init_display_formatter(self):
650 649 self.display_formatter = DisplayFormatter(parent=self)
651 650 self.configurables.append(self.display_formatter)
652 651
653 652 def init_display_pub(self):
654 653 self.display_pub = self.display_pub_class(parent=self)
655 654 self.configurables.append(self.display_pub)
656 655
657 656 def init_data_pub(self):
658 657 if not self.data_pub_class:
659 658 self.data_pub = None
660 659 return
661 660 self.data_pub = self.data_pub_class(parent=self)
662 661 self.configurables.append(self.data_pub)
663 662
664 663 def init_displayhook(self):
665 664 # Initialize displayhook, set in/out prompts and printing system
666 665 self.displayhook = self.displayhook_class(
667 666 parent=self,
668 667 shell=self,
669 668 cache_size=self.cache_size,
670 669 )
671 670 self.configurables.append(self.displayhook)
672 671 # This is a context manager that installs/revmoes the displayhook at
673 672 # the appropriate time.
674 673 self.display_trap = DisplayTrap(hook=self.displayhook)
675 674
676 675 def init_virtualenv(self):
677 676 """Add a virtualenv to sys.path so the user can import modules from it.
678 677 This isn't perfect: it doesn't use the Python interpreter with which the
679 678 virtualenv was built, and it ignores the --no-site-packages option. A
680 679 warning will appear suggesting the user installs IPython in the
681 680 virtualenv, but for many cases, it probably works well enough.
682 681
683 682 Adapted from code snippets online.
684 683
685 684 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
686 685 """
687 686 if 'VIRTUAL_ENV' not in os.environ:
688 687 # Not in a virtualenv
689 688 return
690 689
691 690 # venv detection:
692 691 # stdlib venv may symlink sys.executable, so we can't use realpath.
693 692 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
694 693 # So we just check every item in the symlink tree (generally <= 3)
695 694 p = os.path.normcase(sys.executable)
696 695 paths = [p]
697 696 while os.path.islink(p):
698 697 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
699 698 paths.append(p)
700 699 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
701 700 if any(p.startswith(p_venv) for p in paths):
702 701 # Running properly in the virtualenv, don't need to do anything
703 702 return
704 703
705 704 warn("Attempting to work in a virtualenv. If you encounter problems, please "
706 705 "install IPython inside the virtualenv.")
707 706 if sys.platform == "win32":
708 707 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
709 708 else:
710 709 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
711 710 'python%d.%d' % sys.version_info[:2], 'site-packages')
712 711
713 712 import site
714 713 sys.path.insert(0, virtual_env)
715 714 site.addsitedir(virtual_env)
716 715
717 716 #-------------------------------------------------------------------------
718 717 # Things related to injections into the sys module
719 718 #-------------------------------------------------------------------------
720 719
721 720 def save_sys_module_state(self):
722 721 """Save the state of hooks in the sys module.
723 722
724 723 This has to be called after self.user_module is created.
725 724 """
726 725 self._orig_sys_module_state = {'stdin': sys.stdin,
727 726 'stdout': sys.stdout,
728 727 'stderr': sys.stderr,
729 728 'excepthook': sys.excepthook}
730 729 self._orig_sys_modules_main_name = self.user_module.__name__
731 730 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
732 731
733 732 def restore_sys_module_state(self):
734 733 """Restore the state of the sys module."""
735 734 try:
736 735 for k, v in iteritems(self._orig_sys_module_state):
737 736 setattr(sys, k, v)
738 737 except AttributeError:
739 738 pass
740 739 # Reset what what done in self.init_sys_modules
741 740 if self._orig_sys_modules_main_mod is not None:
742 741 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
743 742
744 743 #-------------------------------------------------------------------------
745 744 # Things related to the banner
746 745 #-------------------------------------------------------------------------
747 746
748 747 @property
749 748 def banner(self):
750 749 banner = self.banner1
751 750 if self.profile and self.profile != 'default':
752 751 banner += '\nIPython profile: %s\n' % self.profile
753 752 if self.banner2:
754 753 banner += '\n' + self.banner2
755 754 return banner
756 755
757 756 def show_banner(self, banner=None):
758 757 if banner is None:
759 758 banner = self.banner
760 759 sys.stdout.write(banner)
761 760
762 761 #-------------------------------------------------------------------------
763 762 # Things related to hooks
764 763 #-------------------------------------------------------------------------
765 764
766 765 def init_hooks(self):
767 766 # hooks holds pointers used for user-side customizations
768 767 self.hooks = Struct()
769 768
770 769 self.strdispatchers = {}
771 770
772 771 # Set all default hooks, defined in the IPython.hooks module.
773 772 hooks = IPython.core.hooks
774 773 for hook_name in hooks.__all__:
775 774 # default hooks have priority 100, i.e. low; user hooks should have
776 775 # 0-100 priority
777 776 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
778 777
779 778 if self.display_page:
780 779 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
781 780
782 781 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
783 782 _warn_deprecated=True):
784 783 """set_hook(name,hook) -> sets an internal IPython hook.
785 784
786 785 IPython exposes some of its internal API as user-modifiable hooks. By
787 786 adding your function to one of these hooks, you can modify IPython's
788 787 behavior to call at runtime your own routines."""
789 788
790 789 # At some point in the future, this should validate the hook before it
791 790 # accepts it. Probably at least check that the hook takes the number
792 791 # of args it's supposed to.
793 792
794 793 f = types.MethodType(hook,self)
795 794
796 795 # check if the hook is for strdispatcher first
797 796 if str_key is not None:
798 797 sdp = self.strdispatchers.get(name, StrDispatch())
799 798 sdp.add_s(str_key, f, priority )
800 799 self.strdispatchers[name] = sdp
801 800 return
802 801 if re_key is not None:
803 802 sdp = self.strdispatchers.get(name, StrDispatch())
804 803 sdp.add_re(re.compile(re_key), f, priority )
805 804 self.strdispatchers[name] = sdp
806 805 return
807 806
808 807 dp = getattr(self.hooks, name, None)
809 808 if name not in IPython.core.hooks.__all__:
810 809 print("Warning! Hook '%s' is not one of %s" % \
811 810 (name, IPython.core.hooks.__all__ ))
812 811
813 812 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
814 813 alternative = IPython.core.hooks.deprecated[name]
815 814 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
816 815
817 816 if not dp:
818 817 dp = IPython.core.hooks.CommandChainDispatcher()
819 818
820 819 try:
821 820 dp.add(f,priority)
822 821 except AttributeError:
823 822 # it was not commandchain, plain old func - replace
824 823 dp = f
825 824
826 825 setattr(self.hooks,name, dp)
827 826
828 827 #-------------------------------------------------------------------------
829 828 # Things related to events
830 829 #-------------------------------------------------------------------------
831 830
832 831 def init_events(self):
833 832 self.events = EventManager(self, available_events)
834 833
835 834 self.events.register("pre_execute", self._clear_warning_registry)
836 835
837 836 def register_post_execute(self, func):
838 837 """DEPRECATED: Use ip.events.register('post_run_cell', func)
839 838
840 839 Register a function for calling after code execution.
841 840 """
842 841 warn("ip.register_post_execute is deprecated, use "
843 842 "ip.events.register('post_run_cell', func) instead.")
844 843 self.events.register('post_run_cell', func)
845 844
846 845 def _clear_warning_registry(self):
847 846 # clear the warning registry, so that different code blocks with
848 847 # overlapping line number ranges don't cause spurious suppression of
849 848 # warnings (see gh-6611 for details)
850 849 if "__warningregistry__" in self.user_global_ns:
851 850 del self.user_global_ns["__warningregistry__"]
852 851
853 852 #-------------------------------------------------------------------------
854 853 # Things related to the "main" module
855 854 #-------------------------------------------------------------------------
856 855
857 856 def new_main_mod(self, filename, modname):
858 857 """Return a new 'main' module object for user code execution.
859 858
860 859 ``filename`` should be the path of the script which will be run in the
861 860 module. Requests with the same filename will get the same module, with
862 861 its namespace cleared.
863 862
864 863 ``modname`` should be the module name - normally either '__main__' or
865 864 the basename of the file without the extension.
866 865
867 866 When scripts are executed via %run, we must keep a reference to their
868 867 __main__ module around so that Python doesn't
869 868 clear it, rendering references to module globals useless.
870 869
871 870 This method keeps said reference in a private dict, keyed by the
872 871 absolute path of the script. This way, for multiple executions of the
873 872 same script we only keep one copy of the namespace (the last one),
874 873 thus preventing memory leaks from old references while allowing the
875 874 objects from the last execution to be accessible.
876 875 """
877 876 filename = os.path.abspath(filename)
878 877 try:
879 878 main_mod = self._main_mod_cache[filename]
880 879 except KeyError:
881 880 main_mod = self._main_mod_cache[filename] = types.ModuleType(
882 881 py3compat.cast_bytes_py2(modname),
883 882 doc="Module created for script run in IPython")
884 883 else:
885 884 main_mod.__dict__.clear()
886 885 main_mod.__name__ = modname
887 886
888 887 main_mod.__file__ = filename
889 888 # It seems pydoc (and perhaps others) needs any module instance to
890 889 # implement a __nonzero__ method
891 890 main_mod.__nonzero__ = lambda : True
892 891
893 892 return main_mod
894 893
895 894 def clear_main_mod_cache(self):
896 895 """Clear the cache of main modules.
897 896
898 897 Mainly for use by utilities like %reset.
899 898
900 899 Examples
901 900 --------
902 901
903 902 In [15]: import IPython
904 903
905 904 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
906 905
907 906 In [17]: len(_ip._main_mod_cache) > 0
908 907 Out[17]: True
909 908
910 909 In [18]: _ip.clear_main_mod_cache()
911 910
912 911 In [19]: len(_ip._main_mod_cache) == 0
913 912 Out[19]: True
914 913 """
915 914 self._main_mod_cache.clear()
916 915
917 916 #-------------------------------------------------------------------------
918 917 # Things related to debugging
919 918 #-------------------------------------------------------------------------
920 919
921 920 def init_pdb(self):
922 921 # Set calling of pdb on exceptions
923 922 # self.call_pdb is a property
924 923 self.call_pdb = self.pdb
925 924
926 925 def _get_call_pdb(self):
927 926 return self._call_pdb
928 927
929 928 def _set_call_pdb(self,val):
930 929
931 930 if val not in (0,1,False,True):
932 931 raise ValueError('new call_pdb value must be boolean')
933 932
934 933 # store value in instance
935 934 self._call_pdb = val
936 935
937 936 # notify the actual exception handlers
938 937 self.InteractiveTB.call_pdb = val
939 938
940 939 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
941 940 'Control auto-activation of pdb at exceptions')
942 941
943 942 def debugger(self,force=False):
944 943 """Call the pdb debugger.
945 944
946 945 Keywords:
947 946
948 947 - force(False): by default, this routine checks the instance call_pdb
949 948 flag and does not actually invoke the debugger if the flag is false.
950 949 The 'force' option forces the debugger to activate even if the flag
951 950 is false.
952 951 """
953 952
954 953 if not (force or self.call_pdb):
955 954 return
956 955
957 956 if not hasattr(sys,'last_traceback'):
958 957 error('No traceback has been produced, nothing to debug.')
959 958 return
960 959
961 960 self.InteractiveTB.debugger(force=True)
962 961
963 962 #-------------------------------------------------------------------------
964 963 # Things related to IPython's various namespaces
965 964 #-------------------------------------------------------------------------
966 965 default_user_namespaces = True
967 966
968 967 def init_create_namespaces(self, user_module=None, user_ns=None):
969 968 # Create the namespace where the user will operate. user_ns is
970 969 # normally the only one used, and it is passed to the exec calls as
971 970 # the locals argument. But we do carry a user_global_ns namespace
972 971 # given as the exec 'globals' argument, This is useful in embedding
973 972 # situations where the ipython shell opens in a context where the
974 973 # distinction between locals and globals is meaningful. For
975 974 # non-embedded contexts, it is just the same object as the user_ns dict.
976 975
977 976 # FIXME. For some strange reason, __builtins__ is showing up at user
978 977 # level as a dict instead of a module. This is a manual fix, but I
979 978 # should really track down where the problem is coming from. Alex
980 979 # Schmolck reported this problem first.
981 980
982 981 # A useful post by Alex Martelli on this topic:
983 982 # Re: inconsistent value from __builtins__
984 983 # Von: Alex Martelli <aleaxit@yahoo.com>
985 984 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
986 985 # Gruppen: comp.lang.python
987 986
988 987 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
989 988 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
990 989 # > <type 'dict'>
991 990 # > >>> print type(__builtins__)
992 991 # > <type 'module'>
993 992 # > Is this difference in return value intentional?
994 993
995 994 # Well, it's documented that '__builtins__' can be either a dictionary
996 995 # or a module, and it's been that way for a long time. Whether it's
997 996 # intentional (or sensible), I don't know. In any case, the idea is
998 997 # that if you need to access the built-in namespace directly, you
999 998 # should start with "import __builtin__" (note, no 's') which will
1000 999 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1001 1000
1002 1001 # These routines return a properly built module and dict as needed by
1003 1002 # the rest of the code, and can also be used by extension writers to
1004 1003 # generate properly initialized namespaces.
1005 1004 if (user_ns is not None) or (user_module is not None):
1006 1005 self.default_user_namespaces = False
1007 1006 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1008 1007
1009 1008 # A record of hidden variables we have added to the user namespace, so
1010 1009 # we can list later only variables defined in actual interactive use.
1011 1010 self.user_ns_hidden = {}
1012 1011
1013 1012 # Now that FakeModule produces a real module, we've run into a nasty
1014 1013 # problem: after script execution (via %run), the module where the user
1015 1014 # code ran is deleted. Now that this object is a true module (needed
1016 1015 # so doctest and other tools work correctly), the Python module
1017 1016 # teardown mechanism runs over it, and sets to None every variable
1018 1017 # present in that module. Top-level references to objects from the
1019 1018 # script survive, because the user_ns is updated with them. However,
1020 1019 # calling functions defined in the script that use other things from
1021 1020 # the script will fail, because the function's closure had references
1022 1021 # to the original objects, which are now all None. So we must protect
1023 1022 # these modules from deletion by keeping a cache.
1024 1023 #
1025 1024 # To avoid keeping stale modules around (we only need the one from the
1026 1025 # last run), we use a dict keyed with the full path to the script, so
1027 1026 # only the last version of the module is held in the cache. Note,
1028 1027 # however, that we must cache the module *namespace contents* (their
1029 1028 # __dict__). Because if we try to cache the actual modules, old ones
1030 1029 # (uncached) could be destroyed while still holding references (such as
1031 1030 # those held by GUI objects that tend to be long-lived)>
1032 1031 #
1033 1032 # The %reset command will flush this cache. See the cache_main_mod()
1034 1033 # and clear_main_mod_cache() methods for details on use.
1035 1034
1036 1035 # This is the cache used for 'main' namespaces
1037 1036 self._main_mod_cache = {}
1038 1037
1039 1038 # A table holding all the namespaces IPython deals with, so that
1040 1039 # introspection facilities can search easily.
1041 1040 self.ns_table = {'user_global':self.user_module.__dict__,
1042 1041 'user_local':self.user_ns,
1043 1042 'builtin':builtin_mod.__dict__
1044 1043 }
1045 1044
1046 1045 @property
1047 1046 def user_global_ns(self):
1048 1047 return self.user_module.__dict__
1049 1048
1050 1049 def prepare_user_module(self, user_module=None, user_ns=None):
1051 1050 """Prepare the module and namespace in which user code will be run.
1052 1051
1053 1052 When IPython is started normally, both parameters are None: a new module
1054 1053 is created automatically, and its __dict__ used as the namespace.
1055 1054
1056 1055 If only user_module is provided, its __dict__ is used as the namespace.
1057 1056 If only user_ns is provided, a dummy module is created, and user_ns
1058 1057 becomes the global namespace. If both are provided (as they may be
1059 1058 when embedding), user_ns is the local namespace, and user_module
1060 1059 provides the global namespace.
1061 1060
1062 1061 Parameters
1063 1062 ----------
1064 1063 user_module : module, optional
1065 1064 The current user module in which IPython is being run. If None,
1066 1065 a clean module will be created.
1067 1066 user_ns : dict, optional
1068 1067 A namespace in which to run interactive commands.
1069 1068
1070 1069 Returns
1071 1070 -------
1072 1071 A tuple of user_module and user_ns, each properly initialised.
1073 1072 """
1074 1073 if user_module is None and user_ns is not None:
1075 1074 user_ns.setdefault("__name__", "__main__")
1076 1075 user_module = DummyMod()
1077 1076 user_module.__dict__ = user_ns
1078 1077
1079 1078 if user_module is None:
1080 1079 user_module = types.ModuleType("__main__",
1081 1080 doc="Automatically created module for IPython interactive environment")
1082 1081
1083 1082 # We must ensure that __builtin__ (without the final 's') is always
1084 1083 # available and pointing to the __builtin__ *module*. For more details:
1085 1084 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1086 1085 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1087 1086 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1088 1087
1089 1088 if user_ns is None:
1090 1089 user_ns = user_module.__dict__
1091 1090
1092 1091 return user_module, user_ns
1093 1092
1094 1093 def init_sys_modules(self):
1095 1094 # We need to insert into sys.modules something that looks like a
1096 1095 # module but which accesses the IPython namespace, for shelve and
1097 1096 # pickle to work interactively. Normally they rely on getting
1098 1097 # everything out of __main__, but for embedding purposes each IPython
1099 1098 # instance has its own private namespace, so we can't go shoving
1100 1099 # everything into __main__.
1101 1100
1102 1101 # note, however, that we should only do this for non-embedded
1103 1102 # ipythons, which really mimic the __main__.__dict__ with their own
1104 1103 # namespace. Embedded instances, on the other hand, should not do
1105 1104 # this because they need to manage the user local/global namespaces
1106 1105 # only, but they live within a 'normal' __main__ (meaning, they
1107 1106 # shouldn't overtake the execution environment of the script they're
1108 1107 # embedded in).
1109 1108
1110 1109 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1111 1110 main_name = self.user_module.__name__
1112 1111 sys.modules[main_name] = self.user_module
1113 1112
1114 1113 def init_user_ns(self):
1115 1114 """Initialize all user-visible namespaces to their minimum defaults.
1116 1115
1117 1116 Certain history lists are also initialized here, as they effectively
1118 1117 act as user namespaces.
1119 1118
1120 1119 Notes
1121 1120 -----
1122 1121 All data structures here are only filled in, they are NOT reset by this
1123 1122 method. If they were not empty before, data will simply be added to
1124 1123 therm.
1125 1124 """
1126 1125 # This function works in two parts: first we put a few things in
1127 1126 # user_ns, and we sync that contents into user_ns_hidden so that these
1128 1127 # initial variables aren't shown by %who. After the sync, we add the
1129 1128 # rest of what we *do* want the user to see with %who even on a new
1130 1129 # session (probably nothing, so they really only see their own stuff)
1131 1130
1132 1131 # The user dict must *always* have a __builtin__ reference to the
1133 1132 # Python standard __builtin__ namespace, which must be imported.
1134 1133 # This is so that certain operations in prompt evaluation can be
1135 1134 # reliably executed with builtins. Note that we can NOT use
1136 1135 # __builtins__ (note the 's'), because that can either be a dict or a
1137 1136 # module, and can even mutate at runtime, depending on the context
1138 1137 # (Python makes no guarantees on it). In contrast, __builtin__ is
1139 1138 # always a module object, though it must be explicitly imported.
1140 1139
1141 1140 # For more details:
1142 1141 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1143 1142 ns = dict()
1144 1143
1145 1144 # make global variables for user access to the histories
1146 1145 ns['_ih'] = self.history_manager.input_hist_parsed
1147 1146 ns['_oh'] = self.history_manager.output_hist
1148 1147 ns['_dh'] = self.history_manager.dir_hist
1149 1148
1150 1149 ns['_sh'] = shadowns
1151 1150
1152 1151 # user aliases to input and output histories. These shouldn't show up
1153 1152 # in %who, as they can have very large reprs.
1154 1153 ns['In'] = self.history_manager.input_hist_parsed
1155 1154 ns['Out'] = self.history_manager.output_hist
1156 1155
1157 1156 # Store myself as the public api!!!
1158 1157 ns['get_ipython'] = self.get_ipython
1159 1158
1160 1159 ns['exit'] = self.exiter
1161 1160 ns['quit'] = self.exiter
1162 1161
1163 1162 # Sync what we've added so far to user_ns_hidden so these aren't seen
1164 1163 # by %who
1165 1164 self.user_ns_hidden.update(ns)
1166 1165
1167 1166 # Anything put into ns now would show up in %who. Think twice before
1168 1167 # putting anything here, as we really want %who to show the user their
1169 1168 # stuff, not our variables.
1170 1169
1171 1170 # Finally, update the real user's namespace
1172 1171 self.user_ns.update(ns)
1173 1172
1174 1173 @property
1175 1174 def all_ns_refs(self):
1176 1175 """Get a list of references to all the namespace dictionaries in which
1177 1176 IPython might store a user-created object.
1178 1177
1179 1178 Note that this does not include the displayhook, which also caches
1180 1179 objects from the output."""
1181 1180 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1182 1181 [m.__dict__ for m in self._main_mod_cache.values()]
1183 1182
1184 1183 def reset(self, new_session=True):
1185 1184 """Clear all internal namespaces, and attempt to release references to
1186 1185 user objects.
1187 1186
1188 1187 If new_session is True, a new history session will be opened.
1189 1188 """
1190 1189 # Clear histories
1191 1190 self.history_manager.reset(new_session)
1192 1191 # Reset counter used to index all histories
1193 1192 if new_session:
1194 1193 self.execution_count = 1
1195 1194
1196 1195 # Flush cached output items
1197 1196 if self.displayhook.do_full_cache:
1198 1197 self.displayhook.flush()
1199 1198
1200 1199 # The main execution namespaces must be cleared very carefully,
1201 1200 # skipping the deletion of the builtin-related keys, because doing so
1202 1201 # would cause errors in many object's __del__ methods.
1203 1202 if self.user_ns is not self.user_global_ns:
1204 1203 self.user_ns.clear()
1205 1204 ns = self.user_global_ns
1206 1205 drop_keys = set(ns.keys())
1207 1206 drop_keys.discard('__builtin__')
1208 1207 drop_keys.discard('__builtins__')
1209 1208 drop_keys.discard('__name__')
1210 1209 for k in drop_keys:
1211 1210 del ns[k]
1212 1211
1213 1212 self.user_ns_hidden.clear()
1214 1213
1215 1214 # Restore the user namespaces to minimal usability
1216 1215 self.init_user_ns()
1217 1216
1218 1217 # Restore the default and user aliases
1219 1218 self.alias_manager.clear_aliases()
1220 1219 self.alias_manager.init_aliases()
1221 1220
1222 1221 # Flush the private list of module references kept for script
1223 1222 # execution protection
1224 1223 self.clear_main_mod_cache()
1225 1224
1226 1225 def del_var(self, varname, by_name=False):
1227 1226 """Delete a variable from the various namespaces, so that, as
1228 1227 far as possible, we're not keeping any hidden references to it.
1229 1228
1230 1229 Parameters
1231 1230 ----------
1232 1231 varname : str
1233 1232 The name of the variable to delete.
1234 1233 by_name : bool
1235 1234 If True, delete variables with the given name in each
1236 1235 namespace. If False (default), find the variable in the user
1237 1236 namespace, and delete references to it.
1238 1237 """
1239 1238 if varname in ('__builtin__', '__builtins__'):
1240 1239 raise ValueError("Refusing to delete %s" % varname)
1241 1240
1242 1241 ns_refs = self.all_ns_refs
1243 1242
1244 1243 if by_name: # Delete by name
1245 1244 for ns in ns_refs:
1246 1245 try:
1247 1246 del ns[varname]
1248 1247 except KeyError:
1249 1248 pass
1250 1249 else: # Delete by object
1251 1250 try:
1252 1251 obj = self.user_ns[varname]
1253 1252 except KeyError:
1254 1253 raise NameError("name '%s' is not defined" % varname)
1255 1254 # Also check in output history
1256 1255 ns_refs.append(self.history_manager.output_hist)
1257 1256 for ns in ns_refs:
1258 1257 to_delete = [n for n, o in iteritems(ns) if o is obj]
1259 1258 for name in to_delete:
1260 1259 del ns[name]
1261 1260
1262 1261 # displayhook keeps extra references, but not in a dictionary
1263 1262 for name in ('_', '__', '___'):
1264 1263 if getattr(self.displayhook, name) is obj:
1265 1264 setattr(self.displayhook, name, None)
1266 1265
1267 1266 def reset_selective(self, regex=None):
1268 1267 """Clear selective variables from internal namespaces based on a
1269 1268 specified regular expression.
1270 1269
1271 1270 Parameters
1272 1271 ----------
1273 1272 regex : string or compiled pattern, optional
1274 1273 A regular expression pattern that will be used in searching
1275 1274 variable names in the users namespaces.
1276 1275 """
1277 1276 if regex is not None:
1278 1277 try:
1279 1278 m = re.compile(regex)
1280 1279 except TypeError:
1281 1280 raise TypeError('regex must be a string or compiled pattern')
1282 1281 # Search for keys in each namespace that match the given regex
1283 1282 # If a match is found, delete the key/value pair.
1284 1283 for ns in self.all_ns_refs:
1285 1284 for var in ns:
1286 1285 if m.search(var):
1287 1286 del ns[var]
1288 1287
1289 1288 def push(self, variables, interactive=True):
1290 1289 """Inject a group of variables into the IPython user namespace.
1291 1290
1292 1291 Parameters
1293 1292 ----------
1294 1293 variables : dict, str or list/tuple of str
1295 1294 The variables to inject into the user's namespace. If a dict, a
1296 1295 simple update is done. If a str, the string is assumed to have
1297 1296 variable names separated by spaces. A list/tuple of str can also
1298 1297 be used to give the variable names. If just the variable names are
1299 1298 give (list/tuple/str) then the variable values looked up in the
1300 1299 callers frame.
1301 1300 interactive : bool
1302 1301 If True (default), the variables will be listed with the ``who``
1303 1302 magic.
1304 1303 """
1305 1304 vdict = None
1306 1305
1307 1306 # We need a dict of name/value pairs to do namespace updates.
1308 1307 if isinstance(variables, dict):
1309 1308 vdict = variables
1310 1309 elif isinstance(variables, string_types+(list, tuple)):
1311 1310 if isinstance(variables, string_types):
1312 1311 vlist = variables.split()
1313 1312 else:
1314 1313 vlist = variables
1315 1314 vdict = {}
1316 1315 cf = sys._getframe(1)
1317 1316 for name in vlist:
1318 1317 try:
1319 1318 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1320 1319 except:
1321 1320 print('Could not get variable %s from %s' %
1322 1321 (name,cf.f_code.co_name))
1323 1322 else:
1324 1323 raise ValueError('variables must be a dict/str/list/tuple')
1325 1324
1326 1325 # Propagate variables to user namespace
1327 1326 self.user_ns.update(vdict)
1328 1327
1329 1328 # And configure interactive visibility
1330 1329 user_ns_hidden = self.user_ns_hidden
1331 1330 if interactive:
1332 1331 for name in vdict:
1333 1332 user_ns_hidden.pop(name, None)
1334 1333 else:
1335 1334 user_ns_hidden.update(vdict)
1336 1335
1337 1336 def drop_by_id(self, variables):
1338 1337 """Remove a dict of variables from the user namespace, if they are the
1339 1338 same as the values in the dictionary.
1340 1339
1341 1340 This is intended for use by extensions: variables that they've added can
1342 1341 be taken back out if they are unloaded, without removing any that the
1343 1342 user has overwritten.
1344 1343
1345 1344 Parameters
1346 1345 ----------
1347 1346 variables : dict
1348 1347 A dictionary mapping object names (as strings) to the objects.
1349 1348 """
1350 1349 for name, obj in iteritems(variables):
1351 1350 if name in self.user_ns and self.user_ns[name] is obj:
1352 1351 del self.user_ns[name]
1353 1352 self.user_ns_hidden.pop(name, None)
1354 1353
1355 1354 #-------------------------------------------------------------------------
1356 1355 # Things related to object introspection
1357 1356 #-------------------------------------------------------------------------
1358 1357
1359 1358 def _ofind(self, oname, namespaces=None):
1360 1359 """Find an object in the available namespaces.
1361 1360
1362 1361 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1363 1362
1364 1363 Has special code to detect magic functions.
1365 1364 """
1366 1365 oname = oname.strip()
1367 1366 #print '1- oname: <%r>' % oname # dbg
1368 1367 if not oname.startswith(ESC_MAGIC) and \
1369 1368 not oname.startswith(ESC_MAGIC2) and \
1370 1369 not py3compat.isidentifier(oname, dotted=True):
1371 1370 return dict(found=False)
1372 1371
1373 1372 if namespaces is None:
1374 1373 # Namespaces to search in:
1375 1374 # Put them in a list. The order is important so that we
1376 1375 # find things in the same order that Python finds them.
1377 1376 namespaces = [ ('Interactive', self.user_ns),
1378 1377 ('Interactive (global)', self.user_global_ns),
1379 1378 ('Python builtin', builtin_mod.__dict__),
1380 1379 ]
1381 1380
1382 1381 # initialize results to 'null'
1383 1382 found = False; obj = None; ospace = None;
1384 1383 ismagic = False; isalias = False; parent = None
1385 1384
1386 1385 # We need to special-case 'print', which as of python2.6 registers as a
1387 1386 # function but should only be treated as one if print_function was
1388 1387 # loaded with a future import. In this case, just bail.
1389 1388 if (oname == 'print' and not py3compat.PY3 and not \
1390 1389 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1391 1390 return {'found':found, 'obj':obj, 'namespace':ospace,
1392 1391 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1393 1392
1394 1393 # Look for the given name by splitting it in parts. If the head is
1395 1394 # found, then we look for all the remaining parts as members, and only
1396 1395 # declare success if we can find them all.
1397 1396 oname_parts = oname.split('.')
1398 1397 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1399 1398 for nsname,ns in namespaces:
1400 1399 try:
1401 1400 obj = ns[oname_head]
1402 1401 except KeyError:
1403 1402 continue
1404 1403 else:
1405 1404 #print 'oname_rest:', oname_rest # dbg
1406 1405 for idx, part in enumerate(oname_rest):
1407 1406 try:
1408 1407 parent = obj
1409 1408 # The last part is looked up in a special way to avoid
1410 1409 # descriptor invocation as it may raise or have side
1411 1410 # effects.
1412 1411 if idx == len(oname_rest) - 1:
1413 1412 obj = self._getattr_property(obj, part)
1414 1413 else:
1415 1414 obj = getattr(obj, part)
1416 1415 except:
1417 1416 # Blanket except b/c some badly implemented objects
1418 1417 # allow __getattr__ to raise exceptions other than
1419 1418 # AttributeError, which then crashes IPython.
1420 1419 break
1421 1420 else:
1422 1421 # If we finish the for loop (no break), we got all members
1423 1422 found = True
1424 1423 ospace = nsname
1425 1424 break # namespace loop
1426 1425
1427 1426 # Try to see if it's magic
1428 1427 if not found:
1429 1428 obj = None
1430 1429 if oname.startswith(ESC_MAGIC2):
1431 1430 oname = oname.lstrip(ESC_MAGIC2)
1432 1431 obj = self.find_cell_magic(oname)
1433 1432 elif oname.startswith(ESC_MAGIC):
1434 1433 oname = oname.lstrip(ESC_MAGIC)
1435 1434 obj = self.find_line_magic(oname)
1436 1435 else:
1437 1436 # search without prefix, so run? will find %run?
1438 1437 obj = self.find_line_magic(oname)
1439 1438 if obj is None:
1440 1439 obj = self.find_cell_magic(oname)
1441 1440 if obj is not None:
1442 1441 found = True
1443 1442 ospace = 'IPython internal'
1444 1443 ismagic = True
1445 1444 isalias = isinstance(obj, Alias)
1446 1445
1447 1446 # Last try: special-case some literals like '', [], {}, etc:
1448 1447 if not found and oname_head in ["''",'""','[]','{}','()']:
1449 1448 obj = eval(oname_head)
1450 1449 found = True
1451 1450 ospace = 'Interactive'
1452 1451
1453 1452 return {'found':found, 'obj':obj, 'namespace':ospace,
1454 1453 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1455 1454
1456 1455 @staticmethod
1457 1456 def _getattr_property(obj, attrname):
1458 1457 """Property-aware getattr to use in object finding.
1459 1458
1460 1459 If attrname represents a property, return it unevaluated (in case it has
1461 1460 side effects or raises an error.
1462 1461
1463 1462 """
1464 1463 if not isinstance(obj, type):
1465 1464 try:
1466 1465 # `getattr(type(obj), attrname)` is not guaranteed to return
1467 1466 # `obj`, but does so for property:
1468 1467 #
1469 1468 # property.__get__(self, None, cls) -> self
1470 1469 #
1471 1470 # The universal alternative is to traverse the mro manually
1472 1471 # searching for attrname in class dicts.
1473 1472 attr = getattr(type(obj), attrname)
1474 1473 except AttributeError:
1475 1474 pass
1476 1475 else:
1477 1476 # This relies on the fact that data descriptors (with both
1478 1477 # __get__ & __set__ magic methods) take precedence over
1479 1478 # instance-level attributes:
1480 1479 #
1481 1480 # class A(object):
1482 1481 # @property
1483 1482 # def foobar(self): return 123
1484 1483 # a = A()
1485 1484 # a.__dict__['foobar'] = 345
1486 1485 # a.foobar # == 123
1487 1486 #
1488 1487 # So, a property may be returned right away.
1489 1488 if isinstance(attr, property):
1490 1489 return attr
1491 1490
1492 1491 # Nothing helped, fall back.
1493 1492 return getattr(obj, attrname)
1494 1493
1495 1494 def _object_find(self, oname, namespaces=None):
1496 1495 """Find an object and return a struct with info about it."""
1497 1496 return Struct(self._ofind(oname, namespaces))
1498 1497
1499 1498 def _inspect(self, meth, oname, namespaces=None, **kw):
1500 1499 """Generic interface to the inspector system.
1501 1500
1502 1501 This function is meant to be called by pdef, pdoc & friends.
1503 1502 """
1504 1503 info = self._object_find(oname, namespaces)
1505 1504 docformat = sphinxify if self.sphinxify_docstring else None
1506 1505 if info.found:
1507 1506 pmethod = getattr(self.inspector, meth)
1508 1507 # TODO: only apply format_screen to the plain/text repr of the mime
1509 1508 # bundle.
1510 1509 formatter = format_screen if info.ismagic else docformat
1511 1510 if meth == 'pdoc':
1512 1511 pmethod(info.obj, oname, formatter)
1513 1512 elif meth == 'pinfo':
1514 1513 pmethod(info.obj, oname, formatter, info,
1515 1514 enable_html_pager=self.enable_html_pager, **kw)
1516 1515 else:
1517 1516 pmethod(info.obj, oname)
1518 1517 else:
1519 1518 print('Object `%s` not found.' % oname)
1520 1519 return 'not found' # so callers can take other action
1521 1520
1522 1521 def object_inspect(self, oname, detail_level=0):
1523 1522 """Get object info about oname"""
1524 1523 with self.builtin_trap:
1525 1524 info = self._object_find(oname)
1526 1525 if info.found:
1527 1526 return self.inspector.info(info.obj, oname, info=info,
1528 1527 detail_level=detail_level
1529 1528 )
1530 1529 else:
1531 1530 return oinspect.object_info(name=oname, found=False)
1532 1531
1533 1532 def object_inspect_text(self, oname, detail_level=0):
1534 1533 """Get object info as formatted text"""
1535 1534 return self.object_inspect_mime(oname, detail_level)['text/plain']
1536 1535
1537 1536 def object_inspect_mime(self, oname, detail_level=0):
1538 1537 """Get object info as a mimebundle of formatted representations.
1539 1538
1540 1539 A mimebundle is a dictionary, keyed by mime-type.
1541 1540 It must always have the key `'text/plain'`.
1542 1541 """
1543 1542 with self.builtin_trap:
1544 1543 info = self._object_find(oname)
1545 1544 if info.found:
1546 1545 return self.inspector._get_info(info.obj, oname, info=info,
1547 1546 detail_level=detail_level
1548 1547 )
1549 1548 else:
1550 1549 raise KeyError(oname)
1551 1550
1552 1551 #-------------------------------------------------------------------------
1553 1552 # Things related to history management
1554 1553 #-------------------------------------------------------------------------
1555 1554
1556 1555 def init_history(self):
1557 1556 """Sets up the command history, and starts regular autosaves."""
1558 1557 self.history_manager = HistoryManager(shell=self, parent=self)
1559 1558 self.configurables.append(self.history_manager)
1560 1559
1561 1560 #-------------------------------------------------------------------------
1562 1561 # Things related to exception handling and tracebacks (not debugging)
1563 1562 #-------------------------------------------------------------------------
1564 1563
1565 1564 debugger_cls = Pdb
1566 1565
1567 1566 def init_traceback_handlers(self, custom_exceptions):
1568 1567 # Syntax error handler.
1569 1568 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1570 1569
1571 1570 # The interactive one is initialized with an offset, meaning we always
1572 1571 # want to remove the topmost item in the traceback, which is our own
1573 1572 # internal code. Valid modes: ['Plain','Context','Verbose']
1574 1573 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1575 1574 color_scheme='NoColor',
1576 1575 tb_offset = 1,
1577 1576 check_cache=check_linecache_ipython,
1578 1577 debugger_cls=self.debugger_cls, parent=self)
1579 1578
1580 1579 # The instance will store a pointer to the system-wide exception hook,
1581 1580 # so that runtime code (such as magics) can access it. This is because
1582 1581 # during the read-eval loop, it may get temporarily overwritten.
1583 1582 self.sys_excepthook = sys.excepthook
1584 1583
1585 1584 # and add any custom exception handlers the user may have specified
1586 1585 self.set_custom_exc(*custom_exceptions)
1587 1586
1588 1587 # Set the exception mode
1589 1588 self.InteractiveTB.set_mode(mode=self.xmode)
1590 1589
1591 1590 def set_custom_exc(self, exc_tuple, handler):
1592 1591 """set_custom_exc(exc_tuple, handler)
1593 1592
1594 1593 Set a custom exception handler, which will be called if any of the
1595 1594 exceptions in exc_tuple occur in the mainloop (specifically, in the
1596 1595 run_code() method).
1597 1596
1598 1597 Parameters
1599 1598 ----------
1600 1599
1601 1600 exc_tuple : tuple of exception classes
1602 1601 A *tuple* of exception classes, for which to call the defined
1603 1602 handler. It is very important that you use a tuple, and NOT A
1604 1603 LIST here, because of the way Python's except statement works. If
1605 1604 you only want to trap a single exception, use a singleton tuple::
1606 1605
1607 1606 exc_tuple == (MyCustomException,)
1608 1607
1609 1608 handler : callable
1610 1609 handler must have the following signature::
1611 1610
1612 1611 def my_handler(self, etype, value, tb, tb_offset=None):
1613 1612 ...
1614 1613 return structured_traceback
1615 1614
1616 1615 Your handler must return a structured traceback (a list of strings),
1617 1616 or None.
1618 1617
1619 1618 This will be made into an instance method (via types.MethodType)
1620 1619 of IPython itself, and it will be called if any of the exceptions
1621 1620 listed in the exc_tuple are caught. If the handler is None, an
1622 1621 internal basic one is used, which just prints basic info.
1623 1622
1624 1623 To protect IPython from crashes, if your handler ever raises an
1625 1624 exception or returns an invalid result, it will be immediately
1626 1625 disabled.
1627 1626
1628 1627 WARNING: by putting in your own exception handler into IPython's main
1629 1628 execution loop, you run a very good chance of nasty crashes. This
1630 1629 facility should only be used if you really know what you are doing."""
1631 1630
1632 1631 assert type(exc_tuple)==type(()) , \
1633 1632 "The custom exceptions must be given AS A TUPLE."
1634 1633
1635 1634 def dummy_handler(self, etype, value, tb, tb_offset=None):
1636 1635 print('*** Simple custom exception handler ***')
1637 1636 print('Exception type :',etype)
1638 1637 print('Exception value:',value)
1639 1638 print('Traceback :',tb)
1640 1639 #print 'Source code :','\n'.join(self.buffer)
1641 1640
1642 1641 def validate_stb(stb):
1643 1642 """validate structured traceback return type
1644 1643
1645 1644 return type of CustomTB *should* be a list of strings, but allow
1646 1645 single strings or None, which are harmless.
1647 1646
1648 1647 This function will *always* return a list of strings,
1649 1648 and will raise a TypeError if stb is inappropriate.
1650 1649 """
1651 1650 msg = "CustomTB must return list of strings, not %r" % stb
1652 1651 if stb is None:
1653 1652 return []
1654 1653 elif isinstance(stb, string_types):
1655 1654 return [stb]
1656 1655 elif not isinstance(stb, list):
1657 1656 raise TypeError(msg)
1658 1657 # it's a list
1659 1658 for line in stb:
1660 1659 # check every element
1661 1660 if not isinstance(line, string_types):
1662 1661 raise TypeError(msg)
1663 1662 return stb
1664 1663
1665 1664 if handler is None:
1666 1665 wrapped = dummy_handler
1667 1666 else:
1668 1667 def wrapped(self,etype,value,tb,tb_offset=None):
1669 1668 """wrap CustomTB handler, to protect IPython from user code
1670 1669
1671 1670 This makes it harder (but not impossible) for custom exception
1672 1671 handlers to crash IPython.
1673 1672 """
1674 1673 try:
1675 1674 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1676 1675 return validate_stb(stb)
1677 1676 except:
1678 1677 # clear custom handler immediately
1679 1678 self.set_custom_exc((), None)
1680 1679 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1681 1680 # show the exception in handler first
1682 1681 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1683 1682 print(self.InteractiveTB.stb2text(stb))
1684 1683 print("The original exception:")
1685 1684 stb = self.InteractiveTB.structured_traceback(
1686 1685 (etype,value,tb), tb_offset=tb_offset
1687 1686 )
1688 1687 return stb
1689 1688
1690 1689 self.CustomTB = types.MethodType(wrapped,self)
1691 1690 self.custom_exceptions = exc_tuple
1692 1691
1693 1692 def excepthook(self, etype, value, tb):
1694 1693 """One more defense for GUI apps that call sys.excepthook.
1695 1694
1696 1695 GUI frameworks like wxPython trap exceptions and call
1697 1696 sys.excepthook themselves. I guess this is a feature that
1698 1697 enables them to keep running after exceptions that would
1699 1698 otherwise kill their mainloop. This is a bother for IPython
1700 1699 which excepts to catch all of the program exceptions with a try:
1701 1700 except: statement.
1702 1701
1703 1702 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1704 1703 any app directly invokes sys.excepthook, it will look to the user like
1705 1704 IPython crashed. In order to work around this, we can disable the
1706 1705 CrashHandler and replace it with this excepthook instead, which prints a
1707 1706 regular traceback using our InteractiveTB. In this fashion, apps which
1708 1707 call sys.excepthook will generate a regular-looking exception from
1709 1708 IPython, and the CrashHandler will only be triggered by real IPython
1710 1709 crashes.
1711 1710
1712 1711 This hook should be used sparingly, only in places which are not likely
1713 1712 to be true IPython errors.
1714 1713 """
1715 1714 self.showtraceback((etype, value, tb), tb_offset=0)
1716 1715
1717 1716 def _get_exc_info(self, exc_tuple=None):
1718 1717 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1719 1718
1720 1719 Ensures sys.last_type,value,traceback hold the exc_info we found,
1721 1720 from whichever source.
1722 1721
1723 1722 raises ValueError if none of these contain any information
1724 1723 """
1725 1724 if exc_tuple is None:
1726 1725 etype, value, tb = sys.exc_info()
1727 1726 else:
1728 1727 etype, value, tb = exc_tuple
1729 1728
1730 1729 if etype is None:
1731 1730 if hasattr(sys, 'last_type'):
1732 1731 etype, value, tb = sys.last_type, sys.last_value, \
1733 1732 sys.last_traceback
1734 1733
1735 1734 if etype is None:
1736 1735 raise ValueError("No exception to find")
1737 1736
1738 1737 # Now store the exception info in sys.last_type etc.
1739 1738 # WARNING: these variables are somewhat deprecated and not
1740 1739 # necessarily safe to use in a threaded environment, but tools
1741 1740 # like pdb depend on their existence, so let's set them. If we
1742 1741 # find problems in the field, we'll need to revisit their use.
1743 1742 sys.last_type = etype
1744 1743 sys.last_value = value
1745 1744 sys.last_traceback = tb
1746 1745
1747 1746 return etype, value, tb
1748 1747
1749 1748 def show_usage_error(self, exc):
1750 1749 """Show a short message for UsageErrors
1751 1750
1752 1751 These are special exceptions that shouldn't show a traceback.
1753 1752 """
1754 1753 print("UsageError: %s" % exc, file=sys.stderr)
1755 1754
1756 1755 def get_exception_only(self, exc_tuple=None):
1757 1756 """
1758 1757 Return as a string (ending with a newline) the exception that
1759 1758 just occurred, without any traceback.
1760 1759 """
1761 1760 etype, value, tb = self._get_exc_info(exc_tuple)
1762 1761 msg = traceback.format_exception_only(etype, value)
1763 1762 return ''.join(msg)
1764 1763
1765 1764 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1766 1765 exception_only=False):
1767 1766 """Display the exception that just occurred.
1768 1767
1769 1768 If nothing is known about the exception, this is the method which
1770 1769 should be used throughout the code for presenting user tracebacks,
1771 1770 rather than directly invoking the InteractiveTB object.
1772 1771
1773 1772 A specific showsyntaxerror() also exists, but this method can take
1774 1773 care of calling it if needed, so unless you are explicitly catching a
1775 1774 SyntaxError exception, don't try to analyze the stack manually and
1776 1775 simply call this method."""
1777 1776
1778 1777 try:
1779 1778 try:
1780 1779 etype, value, tb = self._get_exc_info(exc_tuple)
1781 1780 except ValueError:
1782 1781 print('No traceback available to show.', file=sys.stderr)
1783 1782 return
1784 1783
1785 1784 if issubclass(etype, SyntaxError):
1786 1785 # Though this won't be called by syntax errors in the input
1787 1786 # line, there may be SyntaxError cases with imported code.
1788 1787 self.showsyntaxerror(filename)
1789 1788 elif etype is UsageError:
1790 1789 self.show_usage_error(value)
1791 1790 else:
1792 1791 if exception_only:
1793 1792 stb = ['An exception has occurred, use %tb to see '
1794 1793 'the full traceback.\n']
1795 1794 stb.extend(self.InteractiveTB.get_exception_only(etype,
1796 1795 value))
1797 1796 else:
1798 1797 try:
1799 1798 # Exception classes can customise their traceback - we
1800 1799 # use this in IPython.parallel for exceptions occurring
1801 1800 # in the engines. This should return a list of strings.
1802 1801 stb = value._render_traceback_()
1803 1802 except Exception:
1804 1803 stb = self.InteractiveTB.structured_traceback(etype,
1805 1804 value, tb, tb_offset=tb_offset)
1806 1805
1807 1806 self._showtraceback(etype, value, stb)
1808 1807 if self.call_pdb:
1809 1808 # drop into debugger
1810 1809 self.debugger(force=True)
1811 1810 return
1812 1811
1813 1812 # Actually show the traceback
1814 1813 self._showtraceback(etype, value, stb)
1815 1814
1816 1815 except KeyboardInterrupt:
1817 1816 print('\n' + self.get_exception_only(), file=sys.stderr)
1818 1817
1819 1818 def _showtraceback(self, etype, evalue, stb):
1820 1819 """Actually show a traceback.
1821 1820
1822 1821 Subclasses may override this method to put the traceback on a different
1823 1822 place, like a side channel.
1824 1823 """
1825 1824 print(self.InteractiveTB.stb2text(stb))
1826 1825
1827 1826 def showsyntaxerror(self, filename=None):
1828 1827 """Display the syntax error that just occurred.
1829 1828
1830 1829 This doesn't display a stack trace because there isn't one.
1831 1830
1832 1831 If a filename is given, it is stuffed in the exception instead
1833 1832 of what was there before (because Python's parser always uses
1834 1833 "<string>" when reading from a string).
1835 1834 """
1836 1835 etype, value, last_traceback = self._get_exc_info()
1837 1836
1838 1837 if filename and issubclass(etype, SyntaxError):
1839 1838 try:
1840 1839 value.filename = filename
1841 1840 except:
1842 1841 # Not the format we expect; leave it alone
1843 1842 pass
1844 1843
1845 1844 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1846 1845 self._showtraceback(etype, value, stb)
1847 1846
1848 1847 # This is overridden in TerminalInteractiveShell to show a message about
1849 1848 # the %paste magic.
1850 1849 def showindentationerror(self):
1851 1850 """Called by run_cell when there's an IndentationError in code entered
1852 1851 at the prompt.
1853 1852
1854 1853 This is overridden in TerminalInteractiveShell to show a message about
1855 1854 the %paste magic."""
1856 1855 self.showsyntaxerror()
1857 1856
1858 1857 #-------------------------------------------------------------------------
1859 1858 # Things related to readline
1860 1859 #-------------------------------------------------------------------------
1861 1860
1862 1861 def init_readline(self):
1863 1862 """DEPRECATED
1864 1863
1865 1864 Moved to terminal subclass, here only to simplify the init logic."""
1866 1865 # Set a number of methods that depend on readline to be no-op
1867 1866 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1868 1867 DeprecationWarning, stacklevel=2)
1869 1868 self.set_custom_completer = no_op
1870 1869
1871 1870 @skip_doctest
1872 1871 def set_next_input(self, s, replace=False):
1873 1872 """ Sets the 'default' input string for the next command line.
1874 1873
1875 1874 Example::
1876 1875
1877 1876 In [1]: _ip.set_next_input("Hello Word")
1878 1877 In [2]: Hello Word_ # cursor is here
1879 1878 """
1880 1879 self.rl_next_input = py3compat.cast_bytes_py2(s)
1881 1880
1882 1881 def _indent_current_str(self):
1883 1882 """return the current level of indentation as a string"""
1884 1883 return self.input_splitter.indent_spaces * ' '
1885 1884
1886 1885 #-------------------------------------------------------------------------
1887 1886 # Things related to text completion
1888 1887 #-------------------------------------------------------------------------
1889 1888
1890 1889 def init_completer(self):
1891 1890 """Initialize the completion machinery.
1892 1891
1893 1892 This creates completion machinery that can be used by client code,
1894 1893 either interactively in-process (typically triggered by the readline
1895 1894 library), programmatically (such as in test suites) or out-of-process
1896 1895 (typically over the network by remote frontends).
1897 1896 """
1898 1897 from IPython.core.completer import IPCompleter
1899 1898 from IPython.core.completerlib import (module_completer,
1900 1899 magic_run_completer, cd_completer, reset_completer)
1901 1900
1902 1901 self.Completer = IPCompleter(shell=self,
1903 1902 namespace=self.user_ns,
1904 1903 global_namespace=self.user_global_ns,
1905 1904 parent=self,
1906 1905 )
1907 1906 self.configurables.append(self.Completer)
1908 1907
1909 1908 # Add custom completers to the basic ones built into IPCompleter
1910 1909 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1911 1910 self.strdispatchers['complete_command'] = sdisp
1912 1911 self.Completer.custom_completers = sdisp
1913 1912
1914 1913 self.set_hook('complete_command', module_completer, str_key = 'import')
1915 1914 self.set_hook('complete_command', module_completer, str_key = 'from')
1916 1915 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1917 1916 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1918 1917 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1919 1918 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1920 1919
1921 1920
1922 1921 def complete(self, text, line=None, cursor_pos=None):
1923 1922 """Return the completed text and a list of completions.
1924 1923
1925 1924 Parameters
1926 1925 ----------
1927 1926
1928 1927 text : string
1929 1928 A string of text to be completed on. It can be given as empty and
1930 1929 instead a line/position pair are given. In this case, the
1931 1930 completer itself will split the line like readline does.
1932 1931
1933 1932 line : string, optional
1934 1933 The complete line that text is part of.
1935 1934
1936 1935 cursor_pos : int, optional
1937 1936 The position of the cursor on the input line.
1938 1937
1939 1938 Returns
1940 1939 -------
1941 1940 text : string
1942 1941 The actual text that was completed.
1943 1942
1944 1943 matches : list
1945 1944 A sorted list with all possible completions.
1946 1945
1947 1946 The optional arguments allow the completion to take more context into
1948 1947 account, and are part of the low-level completion API.
1949 1948
1950 1949 This is a wrapper around the completion mechanism, similar to what
1951 1950 readline does at the command line when the TAB key is hit. By
1952 1951 exposing it as a method, it can be used by other non-readline
1953 1952 environments (such as GUIs) for text completion.
1954 1953
1955 1954 Simple usage example:
1956 1955
1957 1956 In [1]: x = 'hello'
1958 1957
1959 1958 In [2]: _ip.complete('x.l')
1960 1959 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1961 1960 """
1962 1961
1963 1962 # Inject names into __builtin__ so we can complete on the added names.
1964 1963 with self.builtin_trap:
1965 1964 return self.Completer.complete(text, line, cursor_pos)
1966 1965
1967 1966 def set_custom_completer(self, completer, pos=0):
1968 1967 """Adds a new custom completer function.
1969 1968
1970 1969 The position argument (defaults to 0) is the index in the completers
1971 1970 list where you want the completer to be inserted."""
1972 1971
1973 1972 newcomp = types.MethodType(completer,self.Completer)
1974 1973 self.Completer.matchers.insert(pos,newcomp)
1975 1974
1976 1975 def set_completer_frame(self, frame=None):
1977 1976 """Set the frame of the completer."""
1978 1977 if frame:
1979 1978 self.Completer.namespace = frame.f_locals
1980 1979 self.Completer.global_namespace = frame.f_globals
1981 1980 else:
1982 1981 self.Completer.namespace = self.user_ns
1983 1982 self.Completer.global_namespace = self.user_global_ns
1984 1983
1985 1984 #-------------------------------------------------------------------------
1986 1985 # Things related to magics
1987 1986 #-------------------------------------------------------------------------
1988 1987
1989 1988 def init_magics(self):
1990 1989 from IPython.core import magics as m
1991 1990 self.magics_manager = magic.MagicsManager(shell=self,
1992 1991 parent=self,
1993 1992 user_magics=m.UserMagics(self))
1994 1993 self.configurables.append(self.magics_manager)
1995 1994
1996 1995 # Expose as public API from the magics manager
1997 1996 self.register_magics = self.magics_manager.register
1998 1997
1999 1998 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2000 1999 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2001 2000 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2002 2001 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2003 2002 )
2004 2003
2005 2004 # Register Magic Aliases
2006 2005 mman = self.magics_manager
2007 2006 # FIXME: magic aliases should be defined by the Magics classes
2008 2007 # or in MagicsManager, not here
2009 2008 mman.register_alias('ed', 'edit')
2010 2009 mman.register_alias('hist', 'history')
2011 2010 mman.register_alias('rep', 'recall')
2012 2011 mman.register_alias('SVG', 'svg', 'cell')
2013 2012 mman.register_alias('HTML', 'html', 'cell')
2014 2013 mman.register_alias('file', 'writefile', 'cell')
2015 2014
2016 2015 # FIXME: Move the color initialization to the DisplayHook, which
2017 2016 # should be split into a prompt manager and displayhook. We probably
2018 2017 # even need a centralize colors management object.
2019 2018 self.magic('colors %s' % self.colors)
2020 2019
2021 2020 # Defined here so that it's included in the documentation
2022 2021 @functools.wraps(magic.MagicsManager.register_function)
2023 2022 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2024 2023 self.magics_manager.register_function(func,
2025 2024 magic_kind=magic_kind, magic_name=magic_name)
2026 2025
2027 2026 def run_line_magic(self, magic_name, line):
2028 2027 """Execute the given line magic.
2029 2028
2030 2029 Parameters
2031 2030 ----------
2032 2031 magic_name : str
2033 2032 Name of the desired magic function, without '%' prefix.
2034 2033
2035 2034 line : str
2036 2035 The rest of the input line as a single string.
2037 2036 """
2038 2037 fn = self.find_line_magic(magic_name)
2039 2038 if fn is None:
2040 2039 cm = self.find_cell_magic(magic_name)
2041 2040 etpl = "Line magic function `%%%s` not found%s."
2042 2041 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2043 2042 'did you mean that instead?)' % magic_name )
2044 2043 error(etpl % (magic_name, extra))
2045 2044 else:
2046 2045 # Note: this is the distance in the stack to the user's frame.
2047 2046 # This will need to be updated if the internal calling logic gets
2048 2047 # refactored, or else we'll be expanding the wrong variables.
2049 2048 stack_depth = 2
2050 2049 magic_arg_s = self.var_expand(line, stack_depth)
2051 2050 # Put magic args in a list so we can call with f(*a) syntax
2052 2051 args = [magic_arg_s]
2053 2052 kwargs = {}
2054 2053 # Grab local namespace if we need it:
2055 2054 if getattr(fn, "needs_local_scope", False):
2056 2055 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2057 2056 with self.builtin_trap:
2058 2057 result = fn(*args,**kwargs)
2059 2058 return result
2060 2059
2061 2060 def run_cell_magic(self, magic_name, line, cell):
2062 2061 """Execute the given cell magic.
2063 2062
2064 2063 Parameters
2065 2064 ----------
2066 2065 magic_name : str
2067 2066 Name of the desired magic function, without '%' prefix.
2068 2067
2069 2068 line : str
2070 2069 The rest of the first input line as a single string.
2071 2070
2072 2071 cell : str
2073 2072 The body of the cell as a (possibly multiline) string.
2074 2073 """
2075 2074 fn = self.find_cell_magic(magic_name)
2076 2075 if fn is None:
2077 2076 lm = self.find_line_magic(magic_name)
2078 2077 etpl = "Cell magic `%%{0}` not found{1}."
2079 2078 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2080 2079 'did you mean that instead?)'.format(magic_name))
2081 2080 error(etpl.format(magic_name, extra))
2082 2081 elif cell == '':
2083 2082 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2084 2083 if self.find_line_magic(magic_name) is not None:
2085 2084 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2086 2085 raise UsageError(message)
2087 2086 else:
2088 2087 # Note: this is the distance in the stack to the user's frame.
2089 2088 # This will need to be updated if the internal calling logic gets
2090 2089 # refactored, or else we'll be expanding the wrong variables.
2091 2090 stack_depth = 2
2092 2091 magic_arg_s = self.var_expand(line, stack_depth)
2093 2092 with self.builtin_trap:
2094 2093 result = fn(magic_arg_s, cell)
2095 2094 return result
2096 2095
2097 2096 def find_line_magic(self, magic_name):
2098 2097 """Find and return a line magic by name.
2099 2098
2100 2099 Returns None if the magic isn't found."""
2101 2100 return self.magics_manager.magics['line'].get(magic_name)
2102 2101
2103 2102 def find_cell_magic(self, magic_name):
2104 2103 """Find and return a cell magic by name.
2105 2104
2106 2105 Returns None if the magic isn't found."""
2107 2106 return self.magics_manager.magics['cell'].get(magic_name)
2108 2107
2109 2108 def find_magic(self, magic_name, magic_kind='line'):
2110 2109 """Find and return a magic of the given type by name.
2111 2110
2112 2111 Returns None if the magic isn't found."""
2113 2112 return self.magics_manager.magics[magic_kind].get(magic_name)
2114 2113
2115 2114 def magic(self, arg_s):
2116 2115 """DEPRECATED. Use run_line_magic() instead.
2117 2116
2118 2117 Call a magic function by name.
2119 2118
2120 2119 Input: a string containing the name of the magic function to call and
2121 2120 any additional arguments to be passed to the magic.
2122 2121
2123 2122 magic('name -opt foo bar') is equivalent to typing at the ipython
2124 2123 prompt:
2125 2124
2126 2125 In[1]: %name -opt foo bar
2127 2126
2128 2127 To call a magic without arguments, simply use magic('name').
2129 2128
2130 2129 This provides a proper Python function to call IPython's magics in any
2131 2130 valid Python code you can type at the interpreter, including loops and
2132 2131 compound statements.
2133 2132 """
2134 2133 # TODO: should we issue a loud deprecation warning here?
2135 2134 magic_name, _, magic_arg_s = arg_s.partition(' ')
2136 2135 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2137 2136 return self.run_line_magic(magic_name, magic_arg_s)
2138 2137
2139 2138 #-------------------------------------------------------------------------
2140 2139 # Things related to macros
2141 2140 #-------------------------------------------------------------------------
2142 2141
2143 2142 def define_macro(self, name, themacro):
2144 2143 """Define a new macro
2145 2144
2146 2145 Parameters
2147 2146 ----------
2148 2147 name : str
2149 2148 The name of the macro.
2150 2149 themacro : str or Macro
2151 2150 The action to do upon invoking the macro. If a string, a new
2152 2151 Macro object is created by passing the string to it.
2153 2152 """
2154 2153
2155 2154 from IPython.core import macro
2156 2155
2157 2156 if isinstance(themacro, string_types):
2158 2157 themacro = macro.Macro(themacro)
2159 2158 if not isinstance(themacro, macro.Macro):
2160 2159 raise ValueError('A macro must be a string or a Macro instance.')
2161 2160 self.user_ns[name] = themacro
2162 2161
2163 2162 #-------------------------------------------------------------------------
2164 2163 # Things related to the running of system commands
2165 2164 #-------------------------------------------------------------------------
2166 2165
2167 2166 def system_piped(self, cmd):
2168 2167 """Call the given cmd in a subprocess, piping stdout/err
2169 2168
2170 2169 Parameters
2171 2170 ----------
2172 2171 cmd : str
2173 2172 Command to execute (can not end in '&', as background processes are
2174 2173 not supported. Should not be a command that expects input
2175 2174 other than simple text.
2176 2175 """
2177 2176 if cmd.rstrip().endswith('&'):
2178 2177 # this is *far* from a rigorous test
2179 2178 # We do not support backgrounding processes because we either use
2180 2179 # pexpect or pipes to read from. Users can always just call
2181 2180 # os.system() or use ip.system=ip.system_raw
2182 2181 # if they really want a background process.
2183 2182 raise OSError("Background processes not supported.")
2184 2183
2185 2184 # we explicitly do NOT return the subprocess status code, because
2186 2185 # a non-None value would trigger :func:`sys.displayhook` calls.
2187 2186 # Instead, we store the exit_code in user_ns.
2188 2187 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2189 2188
2190 2189 def system_raw(self, cmd):
2191 2190 """Call the given cmd in a subprocess using os.system on Windows or
2192 2191 subprocess.call using the system shell on other platforms.
2193 2192
2194 2193 Parameters
2195 2194 ----------
2196 2195 cmd : str
2197 2196 Command to execute.
2198 2197 """
2199 2198 cmd = self.var_expand(cmd, depth=1)
2200 2199 # protect os.system from UNC paths on Windows, which it can't handle:
2201 2200 if sys.platform == 'win32':
2202 2201 from IPython.utils._process_win32 import AvoidUNCPath
2203 2202 with AvoidUNCPath() as path:
2204 2203 if path is not None:
2205 2204 cmd = '"pushd %s &&"%s' % (path, cmd)
2206 2205 cmd = py3compat.unicode_to_str(cmd)
2207 2206 try:
2208 2207 ec = os.system(cmd)
2209 2208 except KeyboardInterrupt:
2210 2209 print('\n' + self.get_exception_only(), file=sys.stderr)
2211 2210 ec = -2
2212 2211 else:
2213 2212 cmd = py3compat.unicode_to_str(cmd)
2214 2213 # For posix the result of the subprocess.call() below is an exit
2215 2214 # code, which by convention is zero for success, positive for
2216 2215 # program failure. Exit codes above 128 are reserved for signals,
2217 2216 # and the formula for converting a signal to an exit code is usually
2218 2217 # signal_number+128. To more easily differentiate between exit
2219 2218 # codes and signals, ipython uses negative numbers. For instance
2220 2219 # since control-c is signal 2 but exit code 130, ipython's
2221 2220 # _exit_code variable will read -2. Note that some shells like
2222 2221 # csh and fish don't follow sh/bash conventions for exit codes.
2223 2222 executable = os.environ.get('SHELL', None)
2224 2223 try:
2225 2224 # Use env shell instead of default /bin/sh
2226 2225 ec = subprocess.call(cmd, shell=True, executable=executable)
2227 2226 except KeyboardInterrupt:
2228 2227 # intercept control-C; a long traceback is not useful here
2229 2228 print('\n' + self.get_exception_only(), file=sys.stderr)
2230 2229 ec = 130
2231 2230 if ec > 128:
2232 2231 ec = -(ec - 128)
2233 2232
2234 2233 # We explicitly do NOT return the subprocess status code, because
2235 2234 # a non-None value would trigger :func:`sys.displayhook` calls.
2236 2235 # Instead, we store the exit_code in user_ns. Note the semantics
2237 2236 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2238 2237 # but raising SystemExit(_exit_code) will give status 254!
2239 2238 self.user_ns['_exit_code'] = ec
2240 2239
2241 2240 # use piped system by default, because it is better behaved
2242 2241 system = system_piped
2243 2242
2244 2243 def getoutput(self, cmd, split=True, depth=0):
2245 2244 """Get output (possibly including stderr) from a subprocess.
2246 2245
2247 2246 Parameters
2248 2247 ----------
2249 2248 cmd : str
2250 2249 Command to execute (can not end in '&', as background processes are
2251 2250 not supported.
2252 2251 split : bool, optional
2253 2252 If True, split the output into an IPython SList. Otherwise, an
2254 2253 IPython LSString is returned. These are objects similar to normal
2255 2254 lists and strings, with a few convenience attributes for easier
2256 2255 manipulation of line-based output. You can use '?' on them for
2257 2256 details.
2258 2257 depth : int, optional
2259 2258 How many frames above the caller are the local variables which should
2260 2259 be expanded in the command string? The default (0) assumes that the
2261 2260 expansion variables are in the stack frame calling this function.
2262 2261 """
2263 2262 if cmd.rstrip().endswith('&'):
2264 2263 # this is *far* from a rigorous test
2265 2264 raise OSError("Background processes not supported.")
2266 2265 out = getoutput(self.var_expand(cmd, depth=depth+1))
2267 2266 if split:
2268 2267 out = SList(out.splitlines())
2269 2268 else:
2270 2269 out = LSString(out)
2271 2270 return out
2272 2271
2273 2272 #-------------------------------------------------------------------------
2274 2273 # Things related to aliases
2275 2274 #-------------------------------------------------------------------------
2276 2275
2277 2276 def init_alias(self):
2278 2277 self.alias_manager = AliasManager(shell=self, parent=self)
2279 2278 self.configurables.append(self.alias_manager)
2280 2279
2281 2280 #-------------------------------------------------------------------------
2282 2281 # Things related to extensions
2283 2282 #-------------------------------------------------------------------------
2284 2283
2285 2284 def init_extension_manager(self):
2286 2285 self.extension_manager = ExtensionManager(shell=self, parent=self)
2287 2286 self.configurables.append(self.extension_manager)
2288 2287
2289 2288 #-------------------------------------------------------------------------
2290 2289 # Things related to payloads
2291 2290 #-------------------------------------------------------------------------
2292 2291
2293 2292 def init_payload(self):
2294 2293 self.payload_manager = PayloadManager(parent=self)
2295 2294 self.configurables.append(self.payload_manager)
2296 2295
2297 2296 #-------------------------------------------------------------------------
2298 2297 # Things related to the prefilter
2299 2298 #-------------------------------------------------------------------------
2300 2299
2301 2300 def init_prefilter(self):
2302 2301 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2303 2302 self.configurables.append(self.prefilter_manager)
2304 2303 # Ultimately this will be refactored in the new interpreter code, but
2305 2304 # for now, we should expose the main prefilter method (there's legacy
2306 2305 # code out there that may rely on this).
2307 2306 self.prefilter = self.prefilter_manager.prefilter_lines
2308 2307
2309 2308 def auto_rewrite_input(self, cmd):
2310 2309 """Print to the screen the rewritten form of the user's command.
2311 2310
2312 2311 This shows visual feedback by rewriting input lines that cause
2313 2312 automatic calling to kick in, like::
2314 2313
2315 2314 /f x
2316 2315
2317 2316 into::
2318 2317
2319 2318 ------> f(x)
2320 2319
2321 2320 after the user's input prompt. This helps the user understand that the
2322 2321 input line was transformed automatically by IPython.
2323 2322 """
2324 2323 if not self.show_rewritten_input:
2325 2324 return
2326 2325
2327 2326 # This is overridden in TerminalInteractiveShell to use fancy prompts
2328 2327 print("------> " + cmd)
2329 2328
2330 2329 #-------------------------------------------------------------------------
2331 2330 # Things related to extracting values/expressions from kernel and user_ns
2332 2331 #-------------------------------------------------------------------------
2333 2332
2334 2333 def _user_obj_error(self):
2335 2334 """return simple exception dict
2336 2335
2337 2336 for use in user_expressions
2338 2337 """
2339 2338
2340 2339 etype, evalue, tb = self._get_exc_info()
2341 2340 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2342 2341
2343 2342 exc_info = {
2344 2343 u'status' : 'error',
2345 2344 u'traceback' : stb,
2346 2345 u'ename' : unicode_type(etype.__name__),
2347 2346 u'evalue' : py3compat.safe_unicode(evalue),
2348 2347 }
2349 2348
2350 2349 return exc_info
2351 2350
2352 2351 def _format_user_obj(self, obj):
2353 2352 """format a user object to display dict
2354 2353
2355 2354 for use in user_expressions
2356 2355 """
2357 2356
2358 2357 data, md = self.display_formatter.format(obj)
2359 2358 value = {
2360 2359 'status' : 'ok',
2361 2360 'data' : data,
2362 2361 'metadata' : md,
2363 2362 }
2364 2363 return value
2365 2364
2366 2365 def user_expressions(self, expressions):
2367 2366 """Evaluate a dict of expressions in the user's namespace.
2368 2367
2369 2368 Parameters
2370 2369 ----------
2371 2370 expressions : dict
2372 2371 A dict with string keys and string values. The expression values
2373 2372 should be valid Python expressions, each of which will be evaluated
2374 2373 in the user namespace.
2375 2374
2376 2375 Returns
2377 2376 -------
2378 2377 A dict, keyed like the input expressions dict, with the rich mime-typed
2379 2378 display_data of each value.
2380 2379 """
2381 2380 out = {}
2382 2381 user_ns = self.user_ns
2383 2382 global_ns = self.user_global_ns
2384 2383
2385 2384 for key, expr in iteritems(expressions):
2386 2385 try:
2387 2386 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2388 2387 except:
2389 2388 value = self._user_obj_error()
2390 2389 out[key] = value
2391 2390 return out
2392 2391
2393 2392 #-------------------------------------------------------------------------
2394 2393 # Things related to the running of code
2395 2394 #-------------------------------------------------------------------------
2396 2395
2397 2396 def ex(self, cmd):
2398 2397 """Execute a normal python statement in user namespace."""
2399 2398 with self.builtin_trap:
2400 2399 exec(cmd, self.user_global_ns, self.user_ns)
2401 2400
2402 2401 def ev(self, expr):
2403 2402 """Evaluate python expression expr in user namespace.
2404 2403
2405 2404 Returns the result of evaluation
2406 2405 """
2407 2406 with self.builtin_trap:
2408 2407 return eval(expr, self.user_global_ns, self.user_ns)
2409 2408
2410 2409 def safe_execfile(self, fname, *where, **kw):
2411 2410 """A safe version of the builtin execfile().
2412 2411
2413 2412 This version will never throw an exception, but instead print
2414 2413 helpful error messages to the screen. This only works on pure
2415 2414 Python files with the .py extension.
2416 2415
2417 2416 Parameters
2418 2417 ----------
2419 2418 fname : string
2420 2419 The name of the file to be executed.
2421 2420 where : tuple
2422 2421 One or two namespaces, passed to execfile() as (globals,locals).
2423 2422 If only one is given, it is passed as both.
2424 2423 exit_ignore : bool (False)
2425 2424 If True, then silence SystemExit for non-zero status (it is always
2426 2425 silenced for zero status, as it is so common).
2427 2426 raise_exceptions : bool (False)
2428 2427 If True raise exceptions everywhere. Meant for testing.
2429 2428 shell_futures : bool (False)
2430 2429 If True, the code will share future statements with the interactive
2431 2430 shell. It will both be affected by previous __future__ imports, and
2432 2431 any __future__ imports in the code will affect the shell. If False,
2433 2432 __future__ imports are not shared in either direction.
2434 2433
2435 2434 """
2436 2435 kw.setdefault('exit_ignore', False)
2437 2436 kw.setdefault('raise_exceptions', False)
2438 2437 kw.setdefault('shell_futures', False)
2439 2438
2440 2439 fname = os.path.abspath(os.path.expanduser(fname))
2441 2440
2442 2441 # Make sure we can open the file
2443 2442 try:
2444 2443 with open(fname):
2445 2444 pass
2446 2445 except:
2447 2446 warn('Could not open file <%s> for safe execution.' % fname)
2448 2447 return
2449 2448
2450 2449 # Find things also in current directory. This is needed to mimic the
2451 2450 # behavior of running a script from the system command line, where
2452 2451 # Python inserts the script's directory into sys.path
2453 2452 dname = os.path.dirname(fname)
2454 2453
2455 2454 with prepended_to_syspath(dname), self.builtin_trap:
2456 2455 try:
2457 2456 glob, loc = (where + (None, ))[:2]
2458 2457 py3compat.execfile(
2459 2458 fname, glob, loc,
2460 2459 self.compile if kw['shell_futures'] else None)
2461 2460 except SystemExit as status:
2462 2461 # If the call was made with 0 or None exit status (sys.exit(0)
2463 2462 # or sys.exit() ), don't bother showing a traceback, as both of
2464 2463 # these are considered normal by the OS:
2465 2464 # > python -c'import sys;sys.exit(0)'; echo $?
2466 2465 # 0
2467 2466 # > python -c'import sys;sys.exit()'; echo $?
2468 2467 # 0
2469 2468 # For other exit status, we show the exception unless
2470 2469 # explicitly silenced, but only in short form.
2471 2470 if status.code:
2472 2471 if kw['raise_exceptions']:
2473 2472 raise
2474 2473 if not kw['exit_ignore']:
2475 2474 self.showtraceback(exception_only=True)
2476 2475 except:
2477 2476 if kw['raise_exceptions']:
2478 2477 raise
2479 2478 # tb offset is 2 because we wrap execfile
2480 2479 self.showtraceback(tb_offset=2)
2481 2480
2482 2481 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2483 2482 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2484 2483
2485 2484 Parameters
2486 2485 ----------
2487 2486 fname : str
2488 2487 The name of the file to execute. The filename must have a
2489 2488 .ipy or .ipynb extension.
2490 2489 shell_futures : bool (False)
2491 2490 If True, the code will share future statements with the interactive
2492 2491 shell. It will both be affected by previous __future__ imports, and
2493 2492 any __future__ imports in the code will affect the shell. If False,
2494 2493 __future__ imports are not shared in either direction.
2495 2494 raise_exceptions : bool (False)
2496 2495 If True raise exceptions everywhere. Meant for testing.
2497 2496 """
2498 2497 fname = os.path.abspath(os.path.expanduser(fname))
2499 2498
2500 2499 # Make sure we can open the file
2501 2500 try:
2502 2501 with open(fname):
2503 2502 pass
2504 2503 except:
2505 2504 warn('Could not open file <%s> for safe execution.' % fname)
2506 2505 return
2507 2506
2508 2507 # Find things also in current directory. This is needed to mimic the
2509 2508 # behavior of running a script from the system command line, where
2510 2509 # Python inserts the script's directory into sys.path
2511 2510 dname = os.path.dirname(fname)
2512 2511
2513 2512 def get_cells():
2514 2513 """generator for sequence of code blocks to run"""
2515 2514 if fname.endswith('.ipynb'):
2516 2515 from nbformat import read
2517 2516 with io_open(fname) as f:
2518 2517 nb = read(f, as_version=4)
2519 2518 if not nb.cells:
2520 2519 return
2521 2520 for cell in nb.cells:
2522 2521 if cell.cell_type == 'code':
2523 2522 yield cell.source
2524 2523 else:
2525 2524 with open(fname) as f:
2526 2525 yield f.read()
2527 2526
2528 2527 with prepended_to_syspath(dname):
2529 2528 try:
2530 2529 for cell in get_cells():
2531 2530 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2532 2531 if raise_exceptions:
2533 2532 result.raise_error()
2534 2533 elif not result.success:
2535 2534 break
2536 2535 except:
2537 2536 if raise_exceptions:
2538 2537 raise
2539 2538 self.showtraceback()
2540 2539 warn('Unknown failure executing file: <%s>' % fname)
2541 2540
2542 2541 def safe_run_module(self, mod_name, where):
2543 2542 """A safe version of runpy.run_module().
2544 2543
2545 2544 This version will never throw an exception, but instead print
2546 2545 helpful error messages to the screen.
2547 2546
2548 2547 `SystemExit` exceptions with status code 0 or None are ignored.
2549 2548
2550 2549 Parameters
2551 2550 ----------
2552 2551 mod_name : string
2553 2552 The name of the module to be executed.
2554 2553 where : dict
2555 2554 The globals namespace.
2556 2555 """
2557 2556 try:
2558 2557 try:
2559 2558 where.update(
2560 2559 runpy.run_module(str(mod_name), run_name="__main__",
2561 2560 alter_sys=True)
2562 2561 )
2563 2562 except SystemExit as status:
2564 2563 if status.code:
2565 2564 raise
2566 2565 except:
2567 2566 self.showtraceback()
2568 2567 warn('Unknown failure executing module: <%s>' % mod_name)
2569 2568
2570 2569 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2571 2570 """Run a complete IPython cell.
2572 2571
2573 2572 Parameters
2574 2573 ----------
2575 2574 raw_cell : str
2576 2575 The code (including IPython code such as %magic functions) to run.
2577 2576 store_history : bool
2578 2577 If True, the raw and translated cell will be stored in IPython's
2579 2578 history. For user code calling back into IPython's machinery, this
2580 2579 should be set to False.
2581 2580 silent : bool
2582 2581 If True, avoid side-effects, such as implicit displayhooks and
2583 2582 and logging. silent=True forces store_history=False.
2584 2583 shell_futures : bool
2585 2584 If True, the code will share future statements with the interactive
2586 2585 shell. It will both be affected by previous __future__ imports, and
2587 2586 any __future__ imports in the code will affect the shell. If False,
2588 2587 __future__ imports are not shared in either direction.
2589 2588
2590 2589 Returns
2591 2590 -------
2592 2591 result : :class:`ExecutionResult`
2593 2592 """
2594 2593 result = ExecutionResult()
2595 2594
2596 2595 if (not raw_cell) or raw_cell.isspace():
2597 2596 self.last_execution_succeeded = True
2598 2597 return result
2599 2598
2600 2599 if silent:
2601 2600 store_history = False
2602 2601
2603 2602 if store_history:
2604 2603 result.execution_count = self.execution_count
2605 2604
2606 2605 def error_before_exec(value):
2607 2606 result.error_before_exec = value
2608 2607 self.last_execution_succeeded = False
2609 2608 return result
2610 2609
2611 2610 self.events.trigger('pre_execute')
2612 2611 if not silent:
2613 2612 self.events.trigger('pre_run_cell')
2614 2613
2615 2614 # If any of our input transformation (input_transformer_manager or
2616 2615 # prefilter_manager) raises an exception, we store it in this variable
2617 2616 # so that we can display the error after logging the input and storing
2618 2617 # it in the history.
2619 2618 preprocessing_exc_tuple = None
2620 2619 try:
2621 2620 # Static input transformations
2622 2621 cell = self.input_transformer_manager.transform_cell(raw_cell)
2623 2622 except SyntaxError:
2624 2623 preprocessing_exc_tuple = sys.exc_info()
2625 2624 cell = raw_cell # cell has to exist so it can be stored/logged
2626 2625 else:
2627 2626 if len(cell.splitlines()) == 1:
2628 2627 # Dynamic transformations - only applied for single line commands
2629 2628 with self.builtin_trap:
2630 2629 try:
2631 2630 # use prefilter_lines to handle trailing newlines
2632 2631 # restore trailing newline for ast.parse
2633 2632 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2634 2633 except Exception:
2635 2634 # don't allow prefilter errors to crash IPython
2636 2635 preprocessing_exc_tuple = sys.exc_info()
2637 2636
2638 2637 # Store raw and processed history
2639 2638 if store_history:
2640 2639 self.history_manager.store_inputs(self.execution_count,
2641 2640 cell, raw_cell)
2642 2641 if not silent:
2643 2642 self.logger.log(cell, raw_cell)
2644 2643
2645 2644 # Display the exception if input processing failed.
2646 2645 if preprocessing_exc_tuple is not None:
2647 2646 self.showtraceback(preprocessing_exc_tuple)
2648 2647 if store_history:
2649 2648 self.execution_count += 1
2650 2649 return error_before_exec(preprocessing_exc_tuple[2])
2651 2650
2652 2651 # Our own compiler remembers the __future__ environment. If we want to
2653 2652 # run code with a separate __future__ environment, use the default
2654 2653 # compiler
2655 2654 compiler = self.compile if shell_futures else CachingCompiler()
2656 2655
2657 2656 with self.builtin_trap:
2658 2657 cell_name = self.compile.cache(cell, self.execution_count)
2659 2658
2660 2659 with self.display_trap:
2661 2660 # Compile to bytecode
2662 2661 try:
2663 2662 code_ast = compiler.ast_parse(cell, filename=cell_name)
2664 2663 except self.custom_exceptions as e:
2665 2664 etype, value, tb = sys.exc_info()
2666 2665 self.CustomTB(etype, value, tb)
2667 2666 return error_before_exec(e)
2668 2667 except IndentationError as e:
2669 2668 self.showindentationerror()
2670 2669 if store_history:
2671 2670 self.execution_count += 1
2672 2671 return error_before_exec(e)
2673 2672 except (OverflowError, SyntaxError, ValueError, TypeError,
2674 2673 MemoryError) as e:
2675 2674 self.showsyntaxerror()
2676 2675 if store_history:
2677 2676 self.execution_count += 1
2678 2677 return error_before_exec(e)
2679 2678
2680 2679 # Apply AST transformations
2681 2680 try:
2682 2681 code_ast = self.transform_ast(code_ast)
2683 2682 except InputRejected as e:
2684 2683 self.showtraceback()
2685 2684 if store_history:
2686 2685 self.execution_count += 1
2687 2686 return error_before_exec(e)
2688 2687
2689 2688 # Give the displayhook a reference to our ExecutionResult so it
2690 2689 # can fill in the output value.
2691 2690 self.displayhook.exec_result = result
2692 2691
2693 2692 # Execute the user code
2694 2693 interactivity = "none" if silent else self.ast_node_interactivity
2695 2694 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2696 2695 interactivity=interactivity, compiler=compiler, result=result)
2697 2696
2698 2697 self.last_execution_succeeded = not has_raised
2699 2698
2700 2699 # Reset this so later displayed values do not modify the
2701 2700 # ExecutionResult
2702 2701 self.displayhook.exec_result = None
2703 2702
2704 2703 self.events.trigger('post_execute')
2705 2704 if not silent:
2706 2705 self.events.trigger('post_run_cell')
2707 2706
2708 2707 if store_history:
2709 2708 # Write output to the database. Does nothing unless
2710 2709 # history output logging is enabled.
2711 2710 self.history_manager.store_output(self.execution_count)
2712 2711 # Each cell is a *single* input, regardless of how many lines it has
2713 2712 self.execution_count += 1
2714 2713
2715 2714 return result
2716 2715
2717 2716 def transform_ast(self, node):
2718 2717 """Apply the AST transformations from self.ast_transformers
2719 2718
2720 2719 Parameters
2721 2720 ----------
2722 2721 node : ast.Node
2723 2722 The root node to be transformed. Typically called with the ast.Module
2724 2723 produced by parsing user input.
2725 2724
2726 2725 Returns
2727 2726 -------
2728 2727 An ast.Node corresponding to the node it was called with. Note that it
2729 2728 may also modify the passed object, so don't rely on references to the
2730 2729 original AST.
2731 2730 """
2732 2731 for transformer in self.ast_transformers:
2733 2732 try:
2734 2733 node = transformer.visit(node)
2735 2734 except InputRejected:
2736 2735 # User-supplied AST transformers can reject an input by raising
2737 2736 # an InputRejected. Short-circuit in this case so that we
2738 2737 # don't unregister the transform.
2739 2738 raise
2740 2739 except Exception:
2741 2740 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2742 2741 self.ast_transformers.remove(transformer)
2743 2742
2744 2743 if self.ast_transformers:
2745 2744 ast.fix_missing_locations(node)
2746 2745 return node
2747 2746
2748 2747
2749 2748 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2750 2749 compiler=compile, result=None):
2751 2750 """Run a sequence of AST nodes. The execution mode depends on the
2752 2751 interactivity parameter.
2753 2752
2754 2753 Parameters
2755 2754 ----------
2756 2755 nodelist : list
2757 2756 A sequence of AST nodes to run.
2758 2757 cell_name : str
2759 2758 Will be passed to the compiler as the filename of the cell. Typically
2760 2759 the value returned by ip.compile.cache(cell).
2761 2760 interactivity : str
2762 2761 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2763 2762 run interactively (displaying output from expressions). 'last_expr'
2764 2763 will run the last node interactively only if it is an expression (i.e.
2765 2764 expressions in loops or other blocks are not displayed. Other values
2766 2765 for this parameter will raise a ValueError.
2767 2766 compiler : callable
2768 2767 A function with the same interface as the built-in compile(), to turn
2769 2768 the AST nodes into code objects. Default is the built-in compile().
2770 2769 result : ExecutionResult, optional
2771 2770 An object to store exceptions that occur during execution.
2772 2771
2773 2772 Returns
2774 2773 -------
2775 2774 True if an exception occurred while running code, False if it finished
2776 2775 running.
2777 2776 """
2778 2777 if not nodelist:
2779 2778 return
2780 2779
2781 2780 if interactivity == 'last_expr':
2782 2781 if isinstance(nodelist[-1], ast.Expr):
2783 2782 interactivity = "last"
2784 2783 else:
2785 2784 interactivity = "none"
2786 2785
2787 2786 if interactivity == 'none':
2788 2787 to_run_exec, to_run_interactive = nodelist, []
2789 2788 elif interactivity == 'last':
2790 2789 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2791 2790 elif interactivity == 'all':
2792 2791 to_run_exec, to_run_interactive = [], nodelist
2793 2792 else:
2794 2793 raise ValueError("Interactivity was %r" % interactivity)
2795 2794
2796 2795 try:
2797 2796 for i, node in enumerate(to_run_exec):
2798 2797 mod = ast.Module([node])
2799 2798 code = compiler(mod, cell_name, "exec")
2800 2799 if self.run_code(code, result):
2801 2800 return True
2802 2801
2803 2802 for i, node in enumerate(to_run_interactive):
2804 2803 mod = ast.Interactive([node])
2805 2804 code = compiler(mod, cell_name, "single")
2806 2805 if self.run_code(code, result):
2807 2806 return True
2808 2807
2809 2808 # Flush softspace
2810 2809 if softspace(sys.stdout, 0):
2811 2810 print()
2812 2811
2813 2812 except:
2814 2813 # It's possible to have exceptions raised here, typically by
2815 2814 # compilation of odd code (such as a naked 'return' outside a
2816 2815 # function) that did parse but isn't valid. Typically the exception
2817 2816 # is a SyntaxError, but it's safest just to catch anything and show
2818 2817 # the user a traceback.
2819 2818
2820 2819 # We do only one try/except outside the loop to minimize the impact
2821 2820 # on runtime, and also because if any node in the node list is
2822 2821 # broken, we should stop execution completely.
2823 2822 if result:
2824 2823 result.error_before_exec = sys.exc_info()[1]
2825 2824 self.showtraceback()
2826 2825 return True
2827 2826
2828 2827 return False
2829 2828
2830 2829 def run_code(self, code_obj, result=None):
2831 2830 """Execute a code object.
2832 2831
2833 2832 When an exception occurs, self.showtraceback() is called to display a
2834 2833 traceback.
2835 2834
2836 2835 Parameters
2837 2836 ----------
2838 2837 code_obj : code object
2839 2838 A compiled code object, to be executed
2840 2839 result : ExecutionResult, optional
2841 2840 An object to store exceptions that occur during execution.
2842 2841
2843 2842 Returns
2844 2843 -------
2845 2844 False : successful execution.
2846 2845 True : an error occurred.
2847 2846 """
2848 2847 # Set our own excepthook in case the user code tries to call it
2849 2848 # directly, so that the IPython crash handler doesn't get triggered
2850 2849 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2851 2850
2852 2851 # we save the original sys.excepthook in the instance, in case config
2853 2852 # code (such as magics) needs access to it.
2854 2853 self.sys_excepthook = old_excepthook
2855 2854 outflag = 1 # happens in more places, so it's easier as default
2856 2855 try:
2857 2856 try:
2858 2857 self.hooks.pre_run_code_hook()
2859 2858 #rprint('Running code', repr(code_obj)) # dbg
2860 2859 exec(code_obj, self.user_global_ns, self.user_ns)
2861 2860 finally:
2862 2861 # Reset our crash handler in place
2863 2862 sys.excepthook = old_excepthook
2864 2863 except SystemExit as e:
2865 2864 if result is not None:
2866 2865 result.error_in_exec = e
2867 2866 self.showtraceback(exception_only=True)
2868 2867 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2869 2868 except self.custom_exceptions:
2870 2869 etype, value, tb = sys.exc_info()
2871 2870 if result is not None:
2872 2871 result.error_in_exec = value
2873 2872 self.CustomTB(etype, value, tb)
2874 2873 except:
2875 2874 if result is not None:
2876 2875 result.error_in_exec = sys.exc_info()[1]
2877 2876 self.showtraceback()
2878 2877 else:
2879 2878 outflag = 0
2880 2879 return outflag
2881 2880
2882 2881 # For backwards compatibility
2883 2882 runcode = run_code
2884 2883
2885 2884 #-------------------------------------------------------------------------
2886 2885 # Things related to GUI support and pylab
2887 2886 #-------------------------------------------------------------------------
2888 2887
2889 2888 active_eventloop = None
2890 2889
2891 2890 def enable_gui(self, gui=None):
2892 2891 raise NotImplementedError('Implement enable_gui in a subclass')
2893 2892
2894 2893 def enable_matplotlib(self, gui=None):
2895 2894 """Enable interactive matplotlib and inline figure support.
2896 2895
2897 2896 This takes the following steps:
2898 2897
2899 2898 1. select the appropriate eventloop and matplotlib backend
2900 2899 2. set up matplotlib for interactive use with that backend
2901 2900 3. configure formatters for inline figure display
2902 2901 4. enable the selected gui eventloop
2903 2902
2904 2903 Parameters
2905 2904 ----------
2906 2905 gui : optional, string
2907 2906 If given, dictates the choice of matplotlib GUI backend to use
2908 2907 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2909 2908 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2910 2909 matplotlib (as dictated by the matplotlib build-time options plus the
2911 2910 user's matplotlibrc configuration file). Note that not all backends
2912 2911 make sense in all contexts, for example a terminal ipython can't
2913 2912 display figures inline.
2914 2913 """
2915 2914 from IPython.core import pylabtools as pt
2916 2915 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2917 2916
2918 2917 if gui != 'inline':
2919 2918 # If we have our first gui selection, store it
2920 2919 if self.pylab_gui_select is None:
2921 2920 self.pylab_gui_select = gui
2922 2921 # Otherwise if they are different
2923 2922 elif gui != self.pylab_gui_select:
2924 2923 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2925 2924 ' Using %s instead.' % (gui, self.pylab_gui_select))
2926 2925 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2927 2926
2928 2927 pt.activate_matplotlib(backend)
2929 2928 pt.configure_inline_support(self, backend)
2930 2929
2931 2930 # Now we must activate the gui pylab wants to use, and fix %run to take
2932 2931 # plot updates into account
2933 2932 self.enable_gui(gui)
2934 2933 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2935 2934 pt.mpl_runner(self.safe_execfile)
2936 2935
2937 2936 return gui, backend
2938 2937
2939 2938 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2940 2939 """Activate pylab support at runtime.
2941 2940
2942 2941 This turns on support for matplotlib, preloads into the interactive
2943 2942 namespace all of numpy and pylab, and configures IPython to correctly
2944 2943 interact with the GUI event loop. The GUI backend to be used can be
2945 2944 optionally selected with the optional ``gui`` argument.
2946 2945
2947 2946 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2948 2947
2949 2948 Parameters
2950 2949 ----------
2951 2950 gui : optional, string
2952 2951 If given, dictates the choice of matplotlib GUI backend to use
2953 2952 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2954 2953 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2955 2954 matplotlib (as dictated by the matplotlib build-time options plus the
2956 2955 user's matplotlibrc configuration file). Note that not all backends
2957 2956 make sense in all contexts, for example a terminal ipython can't
2958 2957 display figures inline.
2959 2958 import_all : optional, bool, default: True
2960 2959 Whether to do `from numpy import *` and `from pylab import *`
2961 2960 in addition to module imports.
2962 2961 welcome_message : deprecated
2963 2962 This argument is ignored, no welcome message will be displayed.
2964 2963 """
2965 2964 from IPython.core.pylabtools import import_pylab
2966 2965
2967 2966 gui, backend = self.enable_matplotlib(gui)
2968 2967
2969 2968 # We want to prevent the loading of pylab to pollute the user's
2970 2969 # namespace as shown by the %who* magics, so we execute the activation
2971 2970 # code in an empty namespace, and we update *both* user_ns and
2972 2971 # user_ns_hidden with this information.
2973 2972 ns = {}
2974 2973 import_pylab(ns, import_all)
2975 2974 # warn about clobbered names
2976 2975 ignored = {"__builtins__"}
2977 2976 both = set(ns).intersection(self.user_ns).difference(ignored)
2978 2977 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2979 2978 self.user_ns.update(ns)
2980 2979 self.user_ns_hidden.update(ns)
2981 2980 return gui, backend, clobbered
2982 2981
2983 2982 #-------------------------------------------------------------------------
2984 2983 # Utilities
2985 2984 #-------------------------------------------------------------------------
2986 2985
2987 2986 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2988 2987 """Expand python variables in a string.
2989 2988
2990 2989 The depth argument indicates how many frames above the caller should
2991 2990 be walked to look for the local namespace where to expand variables.
2992 2991
2993 2992 The global namespace for expansion is always the user's interactive
2994 2993 namespace.
2995 2994 """
2996 2995 ns = self.user_ns.copy()
2997 2996 try:
2998 2997 frame = sys._getframe(depth+1)
2999 2998 except ValueError:
3000 2999 # This is thrown if there aren't that many frames on the stack,
3001 3000 # e.g. if a script called run_line_magic() directly.
3002 3001 pass
3003 3002 else:
3004 3003 ns.update(frame.f_locals)
3005 3004
3006 3005 try:
3007 3006 # We have to use .vformat() here, because 'self' is a valid and common
3008 3007 # name, and expanding **ns for .format() would make it collide with
3009 3008 # the 'self' argument of the method.
3010 3009 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3011 3010 except Exception:
3012 3011 # if formatter couldn't format, just let it go untransformed
3013 3012 pass
3014 3013 return cmd
3015 3014
3016 3015 def mktempfile(self, data=None, prefix='ipython_edit_'):
3017 3016 """Make a new tempfile and return its filename.
3018 3017
3019 3018 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3020 3019 but it registers the created filename internally so ipython cleans it up
3021 3020 at exit time.
3022 3021
3023 3022 Optional inputs:
3024 3023
3025 3024 - data(None): if data is given, it gets written out to the temp file
3026 3025 immediately, and the file is closed again."""
3027 3026
3028 3027 dirname = tempfile.mkdtemp(prefix=prefix)
3029 3028 self.tempdirs.append(dirname)
3030 3029
3031 3030 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3032 3031 os.close(handle) # On Windows, there can only be one open handle on a file
3033 3032 self.tempfiles.append(filename)
3034 3033
3035 3034 if data:
3036 3035 tmp_file = open(filename,'w')
3037 3036 tmp_file.write(data)
3038 3037 tmp_file.close()
3039 3038 return filename
3040 3039
3041 3040 @undoc
3042 3041 def write(self,data):
3043 3042 """DEPRECATED: Write a string to the default output"""
3044 3043 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3045 3044 DeprecationWarning, stacklevel=2)
3046 3045 sys.stdout.write(data)
3047 3046
3048 3047 @undoc
3049 3048 def write_err(self,data):
3050 3049 """DEPRECATED: Write a string to the default error output"""
3051 3050 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3052 3051 DeprecationWarning, stacklevel=2)
3053 3052 sys.stderr.write(data)
3054 3053
3055 3054 def ask_yes_no(self, prompt, default=None, interrupt=None):
3056 3055 if self.quiet:
3057 3056 return True
3058 3057 return ask_yes_no(prompt,default,interrupt)
3059 3058
3060 3059 def show_usage(self):
3061 3060 """Show a usage message"""
3062 3061 page.page(IPython.core.usage.interactive_usage)
3063 3062
3064 3063 def extract_input_lines(self, range_str, raw=False):
3065 3064 """Return as a string a set of input history slices.
3066 3065
3067 3066 Parameters
3068 3067 ----------
3069 3068 range_str : string
3070 3069 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3071 3070 since this function is for use by magic functions which get their
3072 3071 arguments as strings. The number before the / is the session
3073 3072 number: ~n goes n back from the current session.
3074 3073
3075 3074 raw : bool, optional
3076 3075 By default, the processed input is used. If this is true, the raw
3077 3076 input history is used instead.
3078 3077
3079 3078 Notes
3080 3079 -----
3081 3080
3082 3081 Slices can be described with two notations:
3083 3082
3084 3083 * ``N:M`` -> standard python form, means including items N...(M-1).
3085 3084 * ``N-M`` -> include items N..M (closed endpoint).
3086 3085 """
3087 3086 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3088 3087 return "\n".join(x for _, _, x in lines)
3089 3088
3090 3089 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3091 3090 """Get a code string from history, file, url, or a string or macro.
3092 3091
3093 3092 This is mainly used by magic functions.
3094 3093
3095 3094 Parameters
3096 3095 ----------
3097 3096
3098 3097 target : str
3099 3098
3100 3099 A string specifying code to retrieve. This will be tried respectively
3101 3100 as: ranges of input history (see %history for syntax), url,
3102 3101 corresponding .py file, filename, or an expression evaluating to a
3103 3102 string or Macro in the user namespace.
3104 3103
3105 3104 raw : bool
3106 3105 If true (default), retrieve raw history. Has no effect on the other
3107 3106 retrieval mechanisms.
3108 3107
3109 3108 py_only : bool (default False)
3110 3109 Only try to fetch python code, do not try alternative methods to decode file
3111 3110 if unicode fails.
3112 3111
3113 3112 Returns
3114 3113 -------
3115 3114 A string of code.
3116 3115
3117 3116 ValueError is raised if nothing is found, and TypeError if it evaluates
3118 3117 to an object of another type. In each case, .args[0] is a printable
3119 3118 message.
3120 3119 """
3121 3120 code = self.extract_input_lines(target, raw=raw) # Grab history
3122 3121 if code:
3123 3122 return code
3124 3123 try:
3125 3124 if target.startswith(('http://', 'https://')):
3126 3125 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3127 3126 except UnicodeDecodeError:
3128 3127 if not py_only :
3129 3128 # Deferred import
3130 3129 try:
3131 3130 from urllib.request import urlopen # Py3
3132 3131 except ImportError:
3133 3132 from urllib import urlopen
3134 3133 response = urlopen(target)
3135 3134 return response.read().decode('latin1')
3136 3135 raise ValueError(("'%s' seem to be unreadable.") % target)
3137 3136
3138 3137 potential_target = [target]
3139 3138 try :
3140 3139 potential_target.insert(0,get_py_filename(target))
3141 3140 except IOError:
3142 3141 pass
3143 3142
3144 3143 for tgt in potential_target :
3145 3144 if os.path.isfile(tgt): # Read file
3146 3145 try :
3147 3146 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3148 3147 except UnicodeDecodeError :
3149 3148 if not py_only :
3150 3149 with io_open(tgt,'r', encoding='latin1') as f :
3151 3150 return f.read()
3152 3151 raise ValueError(("'%s' seem to be unreadable.") % target)
3153 3152 elif os.path.isdir(os.path.expanduser(tgt)):
3154 3153 raise ValueError("'%s' is a directory, not a regular file." % target)
3155 3154
3156 3155 if search_ns:
3157 3156 # Inspect namespace to load object source
3158 3157 object_info = self.object_inspect(target, detail_level=1)
3159 3158 if object_info['found'] and object_info['source']:
3160 3159 return object_info['source']
3161 3160
3162 3161 try: # User namespace
3163 3162 codeobj = eval(target, self.user_ns)
3164 3163 except Exception:
3165 3164 raise ValueError(("'%s' was not found in history, as a file, url, "
3166 3165 "nor in the user namespace.") % target)
3167 3166
3168 3167 if isinstance(codeobj, string_types):
3169 3168 return codeobj
3170 3169 elif isinstance(codeobj, Macro):
3171 3170 return codeobj.value
3172 3171
3173 3172 raise TypeError("%s is neither a string nor a macro." % target,
3174 3173 codeobj)
3175 3174
3176 3175 #-------------------------------------------------------------------------
3177 3176 # Things related to IPython exiting
3178 3177 #-------------------------------------------------------------------------
3179 3178 def atexit_operations(self):
3180 3179 """This will be executed at the time of exit.
3181 3180
3182 3181 Cleanup operations and saving of persistent data that is done
3183 3182 unconditionally by IPython should be performed here.
3184 3183
3185 3184 For things that may depend on startup flags or platform specifics (such
3186 3185 as having readline or not), register a separate atexit function in the
3187 3186 code that has the appropriate information, rather than trying to
3188 3187 clutter
3189 3188 """
3190 3189 # Close the history session (this stores the end time and line count)
3191 3190 # this must be *before* the tempfile cleanup, in case of temporary
3192 3191 # history db
3193 3192 self.history_manager.end_session()
3194 3193
3195 3194 # Cleanup all tempfiles and folders left around
3196 3195 for tfile in self.tempfiles:
3197 3196 try:
3198 3197 os.unlink(tfile)
3199 3198 except OSError:
3200 3199 pass
3201 3200
3202 3201 for tdir in self.tempdirs:
3203 3202 try:
3204 3203 os.rmdir(tdir)
3205 3204 except OSError:
3206 3205 pass
3207 3206
3208 3207 # Clear all user namespaces to release all references cleanly.
3209 3208 self.reset(new_session=False)
3210 3209
3211 3210 # Run user hooks
3212 3211 self.hooks.shutdown_hook()
3213 3212
3214 3213 def cleanup(self):
3215 3214 self.restore_sys_module_state()
3216 3215
3217 3216
3218 3217 # Overridden in terminal subclass to change prompts
3219 3218 def switch_doctest_mode(self, mode):
3220 3219 pass
3221 3220
3222 3221
3223 3222 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3224 3223 """An abstract base class for InteractiveShell."""
3225 3224
3226 3225 InteractiveShellABC.register(InteractiveShell)
@@ -1,221 +1,220 b''
1 1 """Logger class for IPython's logging facilities.
2 2 """
3 from __future__ import print_function
4 3
5 4 #*****************************************************************************
6 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 6 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 7 #
9 8 # Distributed under the terms of the BSD License. The full license is in
10 9 # the file COPYING, distributed as part of this software.
11 10 #*****************************************************************************
12 11
13 12 #****************************************************************************
14 13 # Modules and globals
15 14
16 15 # Python standard modules
17 16 import glob
18 17 import io
19 18 import os
20 19 import time
21 20
22 21 from IPython.utils.py3compat import str_to_unicode
23 22
24 23 #****************************************************************************
25 24 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
26 25 # ipython and does input cache management. Finish cleanup later...
27 26
28 27 class Logger(object):
29 28 """A Logfile class with different policies for file creation"""
30 29
31 30 def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
32 31 logmode='over'):
33 32
34 33 # this is the full ipython instance, we need some attributes from it
35 34 # which won't exist until later. What a mess, clean up later...
36 35 self.home_dir = home_dir
37 36
38 37 self.logfname = logfname
39 38 self.loghead = loghead
40 39 self.logmode = logmode
41 40 self.logfile = None
42 41
43 42 # Whether to log raw or processed input
44 43 self.log_raw_input = False
45 44
46 45 # whether to also log output
47 46 self.log_output = False
48 47
49 48 # whether to put timestamps before each log entry
50 49 self.timestamp = False
51 50
52 51 # activity control flags
53 52 self.log_active = False
54 53
55 54 # logmode is a validated property
56 55 def _set_mode(self,mode):
57 56 if mode not in ['append','backup','global','over','rotate']:
58 57 raise ValueError('invalid log mode %s given' % mode)
59 58 self._logmode = mode
60 59
61 60 def _get_mode(self):
62 61 return self._logmode
63 62
64 63 logmode = property(_get_mode,_set_mode)
65 64
66 65 def logstart(self, logfname=None, loghead=None, logmode=None,
67 66 log_output=False, timestamp=False, log_raw_input=False):
68 67 """Generate a new log-file with a default header.
69 68
70 69 Raises RuntimeError if the log has already been started"""
71 70
72 71 if self.logfile is not None:
73 72 raise RuntimeError('Log file is already active: %s' %
74 73 self.logfname)
75 74
76 75 # The parameters can override constructor defaults
77 76 if logfname is not None: self.logfname = logfname
78 77 if loghead is not None: self.loghead = loghead
79 78 if logmode is not None: self.logmode = logmode
80 79
81 80 # Parameters not part of the constructor
82 81 self.timestamp = timestamp
83 82 self.log_output = log_output
84 83 self.log_raw_input = log_raw_input
85 84
86 85 # init depending on the log mode requested
87 86 isfile = os.path.isfile
88 87 logmode = self.logmode
89 88
90 89 if logmode == 'append':
91 90 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
92 91
93 92 elif logmode == 'backup':
94 93 if isfile(self.logfname):
95 94 backup_logname = self.logfname+'~'
96 95 # Manually remove any old backup, since os.rename may fail
97 96 # under Windows.
98 97 if isfile(backup_logname):
99 98 os.remove(backup_logname)
100 99 os.rename(self.logfname,backup_logname)
101 100 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
102 101
103 102 elif logmode == 'global':
104 103 self.logfname = os.path.join(self.home_dir,self.logfname)
105 104 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
106 105
107 106 elif logmode == 'over':
108 107 if isfile(self.logfname):
109 108 os.remove(self.logfname)
110 109 self.logfile = io.open(self.logfname,'w', encoding='utf-8')
111 110
112 111 elif logmode == 'rotate':
113 112 if isfile(self.logfname):
114 113 if isfile(self.logfname+'.001~'):
115 114 old = glob.glob(self.logfname+'.*~')
116 115 old.sort()
117 116 old.reverse()
118 117 for f in old:
119 118 root, ext = os.path.splitext(f)
120 119 num = int(ext[1:-1])+1
121 120 os.rename(f, root+'.'+repr(num).zfill(3)+'~')
122 121 os.rename(self.logfname, self.logfname+'.001~')
123 122 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
124 123
125 124 if logmode != 'append':
126 125 self.logfile.write(self.loghead)
127 126
128 127 self.logfile.flush()
129 128 self.log_active = True
130 129
131 130 def switch_log(self,val):
132 131 """Switch logging on/off. val should be ONLY a boolean."""
133 132
134 133 if val not in [False,True,0,1]:
135 134 raise ValueError('Call switch_log ONLY with a boolean argument, '
136 135 'not with: %s' % val)
137 136
138 137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
139 138
140 139 if self.logfile is None:
141 140 print("""
142 141 Logging hasn't been started yet (use logstart for that).
143 142
144 143 %logon/%logoff are for temporarily starting and stopping logging for a logfile
145 144 which already exists. But you must first start the logging process with
146 145 %logstart (optionally giving a logfile name).""")
147 146
148 147 else:
149 148 if self.log_active == val:
150 149 print('Logging is already',label[val])
151 150 else:
152 151 print('Switching logging',label[val])
153 152 self.log_active = not self.log_active
154 153 self.log_active_out = self.log_active
155 154
156 155 def logstate(self):
157 156 """Print a status message about the logger."""
158 157 if self.logfile is None:
159 158 print('Logging has not been activated.')
160 159 else:
161 160 state = self.log_active and 'active' or 'temporarily suspended'
162 161 print('Filename :', self.logfname)
163 162 print('Mode :', self.logmode)
164 163 print('Output logging :', self.log_output)
165 164 print('Raw input log :', self.log_raw_input)
166 165 print('Timestamping :', self.timestamp)
167 166 print('State :', state)
168 167
169 168 def log(self, line_mod, line_ori):
170 169 """Write the sources to a log.
171 170
172 171 Inputs:
173 172
174 173 - line_mod: possibly modified input, such as the transformations made
175 174 by input prefilters or input handlers of various kinds. This should
176 175 always be valid Python.
177 176
178 177 - line_ori: unmodified input line from the user. This is not
179 178 necessarily valid Python.
180 179 """
181 180
182 181 # Write the log line, but decide which one according to the
183 182 # log_raw_input flag, set when the log is started.
184 183 if self.log_raw_input:
185 184 self.log_write(line_ori)
186 185 else:
187 186 self.log_write(line_mod)
188 187
189 188 def log_write(self, data, kind='input'):
190 189 """Write data to the log file, if active"""
191 190
192 191 #print 'data: %r' % data # dbg
193 192 if self.log_active and data:
194 193 write = self.logfile.write
195 194 if kind=='input':
196 195 if self.timestamp:
197 196 write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
198 197 time.localtime())))
199 198 write(data)
200 199 elif kind=='output' and self.log_output:
201 200 odata = u'\n'.join([u'#[Out]# %s' % s
202 201 for s in data.splitlines()])
203 202 write(u'%s\n' % odata)
204 203 self.logfile.flush()
205 204
206 205 def logstop(self):
207 206 """Fully stop logging and close log file.
208 207
209 208 In order to start logging again, a new logstart() call needs to be
210 209 made, possibly (though not necessarily) with a new filename, mode and
211 210 other options."""
212 211
213 212 if self.logfile is not None:
214 213 self.logfile.close()
215 214 self.logfile = None
216 215 else:
217 216 print("Logging hadn't been started.")
218 217 self.log_active = False
219 218
220 219 # For backwards compatibility, in case anyone was using this.
221 220 close_log = logstop
@@ -1,680 +1,679 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 from __future__ import print_function
5 4
6 5 #-----------------------------------------------------------------------------
7 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
9 8 # Copyright (C) 2008 The IPython Development Team
10 9
11 10 # Distributed under the terms of the BSD License. The full license is in
12 11 # the file COPYING, distributed as part of this software.
13 12 #-----------------------------------------------------------------------------
14 13
15 14 import os
16 15 import re
17 16 import sys
18 17 import types
19 18 from getopt import getopt, GetoptError
20 19
21 20 from traitlets.config.configurable import Configurable
22 21 from IPython.core import oinspect
23 22 from IPython.core.error import UsageError
24 23 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
25 24 from decorator import decorator
26 25 from IPython.utils.ipstruct import Struct
27 26 from IPython.utils.process import arg_split
28 27 from IPython.utils.py3compat import string_types, iteritems
29 28 from IPython.utils.text import dedent
30 29 from traitlets import Bool, Dict, Instance, observe
31 30 from logging import error
32 31
33 32 #-----------------------------------------------------------------------------
34 33 # Globals
35 34 #-----------------------------------------------------------------------------
36 35
37 36 # A dict we'll use for each class that has magics, used as temporary storage to
38 37 # pass information between the @line/cell_magic method decorators and the
39 38 # @magics_class class decorator, because the method decorators have no
40 39 # access to the class when they run. See for more details:
41 40 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
42 41
43 42 magics = dict(line={}, cell={})
44 43
45 44 magic_kinds = ('line', 'cell')
46 45 magic_spec = ('line', 'cell', 'line_cell')
47 46 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
48 47
49 48 #-----------------------------------------------------------------------------
50 49 # Utility classes and functions
51 50 #-----------------------------------------------------------------------------
52 51
53 52 class Bunch: pass
54 53
55 54
56 55 def on_off(tag):
57 56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 57 return ['OFF','ON'][tag]
59 58
60 59
61 60 def compress_dhist(dh):
62 61 """Compress a directory history into a new one with at most 20 entries.
63 62
64 63 Return a new list made from the first and last 10 elements of dhist after
65 64 removal of duplicates.
66 65 """
67 66 head, tail = dh[:-10], dh[-10:]
68 67
69 68 newhead = []
70 69 done = set()
71 70 for h in head:
72 71 if h in done:
73 72 continue
74 73 newhead.append(h)
75 74 done.add(h)
76 75
77 76 return newhead + tail
78 77
79 78
80 79 def needs_local_scope(func):
81 80 """Decorator to mark magic functions which need to local scope to run."""
82 81 func.needs_local_scope = True
83 82 return func
84 83
85 84 #-----------------------------------------------------------------------------
86 85 # Class and method decorators for registering magics
87 86 #-----------------------------------------------------------------------------
88 87
89 88 def magics_class(cls):
90 89 """Class decorator for all subclasses of the main Magics class.
91 90
92 91 Any class that subclasses Magics *must* also apply this decorator, to
93 92 ensure that all the methods that have been decorated as line/cell magics
94 93 get correctly registered in the class instance. This is necessary because
95 94 when method decorators run, the class does not exist yet, so they
96 95 temporarily store their information into a module global. Application of
97 96 this class decorator copies that global data to the class instance and
98 97 clears the global.
99 98
100 99 Obviously, this mechanism is not thread-safe, which means that the
101 100 *creation* of subclasses of Magic should only be done in a single-thread
102 101 context. Instantiation of the classes has no restrictions. Given that
103 102 these classes are typically created at IPython startup time and before user
104 103 application code becomes active, in practice this should not pose any
105 104 problems.
106 105 """
107 106 cls.registered = True
108 107 cls.magics = dict(line = magics['line'],
109 108 cell = magics['cell'])
110 109 magics['line'] = {}
111 110 magics['cell'] = {}
112 111 return cls
113 112
114 113
115 114 def record_magic(dct, magic_kind, magic_name, func):
116 115 """Utility function to store a function as a magic of a specific kind.
117 116
118 117 Parameters
119 118 ----------
120 119 dct : dict
121 120 A dictionary with 'line' and 'cell' subdicts.
122 121
123 122 magic_kind : str
124 123 Kind of magic to be stored.
125 124
126 125 magic_name : str
127 126 Key to store the magic as.
128 127
129 128 func : function
130 129 Callable object to store.
131 130 """
132 131 if magic_kind == 'line_cell':
133 132 dct['line'][magic_name] = dct['cell'][magic_name] = func
134 133 else:
135 134 dct[magic_kind][magic_name] = func
136 135
137 136
138 137 def validate_type(magic_kind):
139 138 """Ensure that the given magic_kind is valid.
140 139
141 140 Check that the given magic_kind is one of the accepted spec types (stored
142 141 in the global `magic_spec`), raise ValueError otherwise.
143 142 """
144 143 if magic_kind not in magic_spec:
145 144 raise ValueError('magic_kind must be one of %s, %s given' %
146 145 magic_kinds, magic_kind)
147 146
148 147
149 148 # The docstrings for the decorator below will be fairly similar for the two
150 149 # types (method and function), so we generate them here once and reuse the
151 150 # templates below.
152 151 _docstring_template = \
153 152 """Decorate the given {0} as {1} magic.
154 153
155 154 The decorator can be used with or without arguments, as follows.
156 155
157 156 i) without arguments: it will create a {1} magic named as the {0} being
158 157 decorated::
159 158
160 159 @deco
161 160 def foo(...)
162 161
163 162 will create a {1} magic named `foo`.
164 163
165 164 ii) with one string argument: which will be used as the actual name of the
166 165 resulting magic::
167 166
168 167 @deco('bar')
169 168 def foo(...)
170 169
171 170 will create a {1} magic named `bar`.
172 171 """
173 172
174 173 # These two are decorator factories. While they are conceptually very similar,
175 174 # there are enough differences in the details that it's simpler to have them
176 175 # written as completely standalone functions rather than trying to share code
177 176 # and make a single one with convoluted logic.
178 177
179 178 def _method_magic_marker(magic_kind):
180 179 """Decorator factory for methods in Magics subclasses.
181 180 """
182 181
183 182 validate_type(magic_kind)
184 183
185 184 # This is a closure to capture the magic_kind. We could also use a class,
186 185 # but it's overkill for just that one bit of state.
187 186 def magic_deco(arg):
188 187 call = lambda f, *a, **k: f(*a, **k)
189 188
190 189 if callable(arg):
191 190 # "Naked" decorator call (just @foo, no args)
192 191 func = arg
193 192 name = func.__name__
194 193 retval = decorator(call, func)
195 194 record_magic(magics, magic_kind, name, name)
196 195 elif isinstance(arg, string_types):
197 196 # Decorator called with arguments (@foo('bar'))
198 197 name = arg
199 198 def mark(func, *a, **kw):
200 199 record_magic(magics, magic_kind, name, func.__name__)
201 200 return decorator(call, func)
202 201 retval = mark
203 202 else:
204 203 raise TypeError("Decorator can only be called with "
205 204 "string or function")
206 205 return retval
207 206
208 207 # Ensure the resulting decorator has a usable docstring
209 208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
210 209 return magic_deco
211 210
212 211
213 212 def _function_magic_marker(magic_kind):
214 213 """Decorator factory for standalone functions.
215 214 """
216 215 validate_type(magic_kind)
217 216
218 217 # This is a closure to capture the magic_kind. We could also use a class,
219 218 # but it's overkill for just that one bit of state.
220 219 def magic_deco(arg):
221 220 call = lambda f, *a, **k: f(*a, **k)
222 221
223 222 # Find get_ipython() in the caller's namespace
224 223 caller = sys._getframe(1)
225 224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
226 225 get_ipython = getattr(caller, ns).get('get_ipython')
227 226 if get_ipython is not None:
228 227 break
229 228 else:
230 229 raise NameError('Decorator can only run in context where '
231 230 '`get_ipython` exists')
232 231
233 232 ip = get_ipython()
234 233
235 234 if callable(arg):
236 235 # "Naked" decorator call (just @foo, no args)
237 236 func = arg
238 237 name = func.__name__
239 238 ip.register_magic_function(func, magic_kind, name)
240 239 retval = decorator(call, func)
241 240 elif isinstance(arg, string_types):
242 241 # Decorator called with arguments (@foo('bar'))
243 242 name = arg
244 243 def mark(func, *a, **kw):
245 244 ip.register_magic_function(func, magic_kind, name)
246 245 return decorator(call, func)
247 246 retval = mark
248 247 else:
249 248 raise TypeError("Decorator can only be called with "
250 249 "string or function")
251 250 return retval
252 251
253 252 # Ensure the resulting decorator has a usable docstring
254 253 ds = _docstring_template.format('function', magic_kind)
255 254
256 255 ds += dedent("""
257 256 Note: this decorator can only be used in a context where IPython is already
258 257 active, so that the `get_ipython()` call succeeds. You can therefore use
259 258 it in your startup files loaded after IPython initializes, but *not* in the
260 259 IPython configuration file itself, which is executed before IPython is
261 260 fully up and running. Any file located in the `startup` subdirectory of
262 261 your configuration profile will be OK in this sense.
263 262 """)
264 263
265 264 magic_deco.__doc__ = ds
266 265 return magic_deco
267 266
268 267
269 268 # Create the actual decorators for public use
270 269
271 270 # These three are used to decorate methods in class definitions
272 271 line_magic = _method_magic_marker('line')
273 272 cell_magic = _method_magic_marker('cell')
274 273 line_cell_magic = _method_magic_marker('line_cell')
275 274
276 275 # These three decorate standalone functions and perform the decoration
277 276 # immediately. They can only run where get_ipython() works
278 277 register_line_magic = _function_magic_marker('line')
279 278 register_cell_magic = _function_magic_marker('cell')
280 279 register_line_cell_magic = _function_magic_marker('line_cell')
281 280
282 281 #-----------------------------------------------------------------------------
283 282 # Core Magic classes
284 283 #-----------------------------------------------------------------------------
285 284
286 285 class MagicsManager(Configurable):
287 286 """Object that handles all magic-related functionality for IPython.
288 287 """
289 288 # Non-configurable class attributes
290 289
291 290 # A two-level dict, first keyed by magic type, then by magic function, and
292 291 # holding the actual callable object as value. This is the dict used for
293 292 # magic function dispatch
294 293 magics = Dict()
295 294
296 295 # A registry of the original objects that we've been given holding magics.
297 296 registry = Dict()
298 297
299 298 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
300 299
301 300 auto_magic = Bool(True, help=
302 301 "Automatically call line magics without requiring explicit % prefix"
303 302 ).tag(config=True)
304 303 @observe('auto_magic')
305 304 def _auto_magic_changed(self, change):
306 305 self.shell.automagic = change['new']
307 306
308 307 _auto_status = [
309 308 'Automagic is OFF, % prefix IS needed for line magics.',
310 309 'Automagic is ON, % prefix IS NOT needed for line magics.']
311 310
312 311 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
313 312
314 313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
315 314
316 315 super(MagicsManager, self).__init__(shell=shell, config=config,
317 316 user_magics=user_magics, **traits)
318 317 self.magics = dict(line={}, cell={})
319 318 # Let's add the user_magics to the registry for uniformity, so *all*
320 319 # registered magic containers can be found there.
321 320 self.registry[user_magics.__class__.__name__] = user_magics
322 321
323 322 def auto_status(self):
324 323 """Return descriptive string with automagic status."""
325 324 return self._auto_status[self.auto_magic]
326 325
327 326 def lsmagic(self):
328 327 """Return a dict of currently available magic functions.
329 328
330 329 The return dict has the keys 'line' and 'cell', corresponding to the
331 330 two types of magics we support. Each value is a list of names.
332 331 """
333 332 return self.magics
334 333
335 334 def lsmagic_docs(self, brief=False, missing=''):
336 335 """Return dict of documentation of magic functions.
337 336
338 337 The return dict has the keys 'line' and 'cell', corresponding to the
339 338 two types of magics we support. Each value is a dict keyed by magic
340 339 name whose value is the function docstring. If a docstring is
341 340 unavailable, the value of `missing` is used instead.
342 341
343 342 If brief is True, only the first line of each docstring will be returned.
344 343 """
345 344 docs = {}
346 345 for m_type in self.magics:
347 346 m_docs = {}
348 347 for m_name, m_func in iteritems(self.magics[m_type]):
349 348 if m_func.__doc__:
350 349 if brief:
351 350 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
352 351 else:
353 352 m_docs[m_name] = m_func.__doc__.rstrip()
354 353 else:
355 354 m_docs[m_name] = missing
356 355 docs[m_type] = m_docs
357 356 return docs
358 357
359 358 def register(self, *magic_objects):
360 359 """Register one or more instances of Magics.
361 360
362 361 Take one or more classes or instances of classes that subclass the main
363 362 `core.Magic` class, and register them with IPython to use the magic
364 363 functions they provide. The registration process will then ensure that
365 364 any methods that have decorated to provide line and/or cell magics will
366 365 be recognized with the `%x`/`%%x` syntax as a line/cell magic
367 366 respectively.
368 367
369 368 If classes are given, they will be instantiated with the default
370 369 constructor. If your classes need a custom constructor, you should
371 370 instanitate them first and pass the instance.
372 371
373 372 The provided arguments can be an arbitrary mix of classes and instances.
374 373
375 374 Parameters
376 375 ----------
377 376 magic_objects : one or more classes or instances
378 377 """
379 378 # Start by validating them to ensure they have all had their magic
380 379 # methods registered at the instance level
381 380 for m in magic_objects:
382 381 if not m.registered:
383 382 raise ValueError("Class of magics %r was constructed without "
384 383 "the @register_magics class decorator")
385 384 if isinstance(m, type):
386 385 # If we're given an uninstantiated class
387 386 m = m(shell=self.shell)
388 387
389 388 # Now that we have an instance, we can register it and update the
390 389 # table of callables
391 390 self.registry[m.__class__.__name__] = m
392 391 for mtype in magic_kinds:
393 392 self.magics[mtype].update(m.magics[mtype])
394 393
395 394 def register_function(self, func, magic_kind='line', magic_name=None):
396 395 """Expose a standalone function as magic function for IPython.
397 396
398 397 This will create an IPython magic (line, cell or both) from a
399 398 standalone function. The functions should have the following
400 399 signatures:
401 400
402 401 * For line magics: `def f(line)`
403 402 * For cell magics: `def f(line, cell)`
404 403 * For a function that does both: `def f(line, cell=None)`
405 404
406 405 In the latter case, the function will be called with `cell==None` when
407 406 invoked as `%f`, and with cell as a string when invoked as `%%f`.
408 407
409 408 Parameters
410 409 ----------
411 410 func : callable
412 411 Function to be registered as a magic.
413 412
414 413 magic_kind : str
415 414 Kind of magic, one of 'line', 'cell' or 'line_cell'
416 415
417 416 magic_name : optional str
418 417 If given, the name the magic will have in the IPython namespace. By
419 418 default, the name of the function itself is used.
420 419 """
421 420
422 421 # Create the new method in the user_magics and register it in the
423 422 # global table
424 423 validate_type(magic_kind)
425 424 magic_name = func.__name__ if magic_name is None else magic_name
426 425 setattr(self.user_magics, magic_name, func)
427 426 record_magic(self.magics, magic_kind, magic_name, func)
428 427
429 428 def register_alias(self, alias_name, magic_name, magic_kind='line'):
430 429 """Register an alias to a magic function.
431 430
432 431 The alias is an instance of :class:`MagicAlias`, which holds the
433 432 name and kind of the magic it should call. Binding is done at
434 433 call time, so if the underlying magic function is changed the alias
435 434 will call the new function.
436 435
437 436 Parameters
438 437 ----------
439 438 alias_name : str
440 439 The name of the magic to be registered.
441 440
442 441 magic_name : str
443 442 The name of an existing magic.
444 443
445 444 magic_kind : str
446 445 Kind of magic, one of 'line' or 'cell'
447 446 """
448 447
449 448 # `validate_type` is too permissive, as it allows 'line_cell'
450 449 # which we do not handle.
451 450 if magic_kind not in magic_kinds:
452 451 raise ValueError('magic_kind must be one of %s, %s given' %
453 452 magic_kinds, magic_kind)
454 453
455 454 alias = MagicAlias(self.shell, magic_name, magic_kind)
456 455 setattr(self.user_magics, alias_name, alias)
457 456 record_magic(self.magics, magic_kind, alias_name, alias)
458 457
459 458 # Key base class that provides the central functionality for magics.
460 459
461 460
462 461 class Magics(Configurable):
463 462 """Base class for implementing magic functions.
464 463
465 464 Shell functions which can be reached as %function_name. All magic
466 465 functions should accept a string, which they can parse for their own
467 466 needs. This can make some functions easier to type, eg `%cd ../`
468 467 vs. `%cd("../")`
469 468
470 469 Classes providing magic functions need to subclass this class, and they
471 470 MUST:
472 471
473 472 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
474 473 individual methods as magic functions, AND
475 474
476 475 - Use the class decorator `@magics_class` to ensure that the magic
477 476 methods are properly registered at the instance level upon instance
478 477 initialization.
479 478
480 479 See :mod:`magic_functions` for examples of actual implementation classes.
481 480 """
482 481 # Dict holding all command-line options for each magic.
483 482 options_table = None
484 483 # Dict for the mapping of magic names to methods, set by class decorator
485 484 magics = None
486 485 # Flag to check that the class decorator was properly applied
487 486 registered = False
488 487 # Instance of IPython shell
489 488 shell = None
490 489
491 490 def __init__(self, shell=None, **kwargs):
492 491 if not(self.__class__.registered):
493 492 raise ValueError('Magics subclass without registration - '
494 493 'did you forget to apply @magics_class?')
495 494 if shell is not None:
496 495 if hasattr(shell, 'configurables'):
497 496 shell.configurables.append(self)
498 497 if hasattr(shell, 'config'):
499 498 kwargs.setdefault('parent', shell)
500 499
501 500 self.shell = shell
502 501 self.options_table = {}
503 502 # The method decorators are run when the instance doesn't exist yet, so
504 503 # they can only record the names of the methods they are supposed to
505 504 # grab. Only now, that the instance exists, can we create the proper
506 505 # mapping to bound methods. So we read the info off the original names
507 506 # table and replace each method name by the actual bound method.
508 507 # But we mustn't clobber the *class* mapping, in case of multiple instances.
509 508 class_magics = self.magics
510 509 self.magics = {}
511 510 for mtype in magic_kinds:
512 511 tab = self.magics[mtype] = {}
513 512 cls_tab = class_magics[mtype]
514 513 for magic_name, meth_name in iteritems(cls_tab):
515 514 if isinstance(meth_name, string_types):
516 515 # it's a method name, grab it
517 516 tab[magic_name] = getattr(self, meth_name)
518 517 else:
519 518 # it's the real thing
520 519 tab[magic_name] = meth_name
521 520 # Configurable **needs** to be initiated at the end or the config
522 521 # magics get screwed up.
523 522 super(Magics, self).__init__(**kwargs)
524 523
525 524 def arg_err(self,func):
526 525 """Print docstring if incorrect arguments were passed"""
527 526 print('Error in arguments:')
528 527 print(oinspect.getdoc(func))
529 528
530 529 def format_latex(self, strng):
531 530 """Format a string for latex inclusion."""
532 531
533 532 # Characters that need to be escaped for latex:
534 533 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
535 534 # Magic command names as headers:
536 535 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
537 536 re.MULTILINE)
538 537 # Magic commands
539 538 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
540 539 re.MULTILINE)
541 540 # Paragraph continue
542 541 par_re = re.compile(r'\\$',re.MULTILINE)
543 542
544 543 # The "\n" symbol
545 544 newline_re = re.compile(r'\\n')
546 545
547 546 # Now build the string for output:
548 547 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
549 548 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
550 549 strng)
551 550 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
552 551 strng = par_re.sub(r'\\\\',strng)
553 552 strng = escape_re.sub(r'\\\1',strng)
554 553 strng = newline_re.sub(r'\\textbackslash{}n',strng)
555 554 return strng
556 555
557 556 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
558 557 """Parse options passed to an argument string.
559 558
560 559 The interface is similar to that of :func:`getopt.getopt`, but it
561 560 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
562 561 and the stripped argument string still as a string.
563 562
564 563 arg_str is quoted as a true sys.argv vector by using shlex.split.
565 564 This allows us to easily expand variables, glob files, quote
566 565 arguments, etc.
567 566
568 567 Parameters
569 568 ----------
570 569
571 570 arg_str : str
572 571 The arguments to parse.
573 572
574 573 opt_str : str
575 574 The options specification.
576 575
577 576 mode : str, default 'string'
578 577 If given as 'list', the argument string is returned as a list (split
579 578 on whitespace) instead of a string.
580 579
581 580 list_all : bool, default False
582 581 Put all option values in lists. Normally only options
583 582 appearing more than once are put in a list.
584 583
585 584 posix : bool, default True
586 585 Whether to split the input line in POSIX mode or not, as per the
587 586 conventions outlined in the :mod:`shlex` module from the standard
588 587 library.
589 588 """
590 589
591 590 # inject default options at the beginning of the input line
592 591 caller = sys._getframe(1).f_code.co_name
593 592 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
594 593
595 594 mode = kw.get('mode','string')
596 595 if mode not in ['string','list']:
597 596 raise ValueError('incorrect mode given: %s' % mode)
598 597 # Get options
599 598 list_all = kw.get('list_all',0)
600 599 posix = kw.get('posix', os.name == 'posix')
601 600 strict = kw.get('strict', True)
602 601
603 602 # Check if we have more than one argument to warrant extra processing:
604 603 odict = {} # Dictionary with options
605 604 args = arg_str.split()
606 605 if len(args) >= 1:
607 606 # If the list of inputs only has 0 or 1 thing in it, there's no
608 607 # need to look for options
609 608 argv = arg_split(arg_str, posix, strict)
610 609 # Do regular option processing
611 610 try:
612 611 opts,args = getopt(argv, opt_str, long_opts)
613 612 except GetoptError as e:
614 613 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
615 614 " ".join(long_opts)))
616 615 for o,a in opts:
617 616 if o.startswith('--'):
618 617 o = o[2:]
619 618 else:
620 619 o = o[1:]
621 620 try:
622 621 odict[o].append(a)
623 622 except AttributeError:
624 623 odict[o] = [odict[o],a]
625 624 except KeyError:
626 625 if list_all:
627 626 odict[o] = [a]
628 627 else:
629 628 odict[o] = a
630 629
631 630 # Prepare opts,args for return
632 631 opts = Struct(odict)
633 632 if mode == 'string':
634 633 args = ' '.join(args)
635 634
636 635 return opts,args
637 636
638 637 def default_option(self, fn, optstr):
639 638 """Make an entry in the options_table for fn, with value optstr"""
640 639
641 640 if fn not in self.lsmagic():
642 641 error("%s is not a magic function" % fn)
643 642 self.options_table[fn] = optstr
644 643
645 644
646 645 class MagicAlias(object):
647 646 """An alias to another magic function.
648 647
649 648 An alias is determined by its magic name and magic kind. Lookup
650 649 is done at call time, so if the underlying magic changes the alias
651 650 will call the new function.
652 651
653 652 Use the :meth:`MagicsManager.register_alias` method or the
654 653 `%alias_magic` magic function to create and register a new alias.
655 654 """
656 655 def __init__(self, shell, magic_name, magic_kind):
657 656 self.shell = shell
658 657 self.magic_name = magic_name
659 658 self.magic_kind = magic_kind
660 659
661 660 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
662 661 self.__doc__ = "Alias for `%s`." % self.pretty_target
663 662
664 663 self._in_call = False
665 664
666 665 def __call__(self, *args, **kwargs):
667 666 """Call the magic alias."""
668 667 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
669 668 if fn is None:
670 669 raise UsageError("Magic `%s` not found." % self.pretty_target)
671 670
672 671 # Protect against infinite recursion.
673 672 if self._in_call:
674 673 raise UsageError("Infinite recursion detected; "
675 674 "magic aliases cannot call themselves.")
676 675 self._in_call = True
677 676 try:
678 677 return fn(*args, **kwargs)
679 678 finally:
680 679 self._in_call = False
@@ -1,130 +1,128 b''
1 1 """Implementation of magic functions that control various automatic behaviors.
2 2 """
3 from __future__ import print_function
4 from __future__ import absolute_import
5 3 #-----------------------------------------------------------------------------
6 4 # Copyright (c) 2012 The IPython Development Team.
7 5 #
8 6 # Distributed under the terms of the Modified BSD License.
9 7 #
10 8 # The full license is in the file COPYING.txt, distributed with this software.
11 9 #-----------------------------------------------------------------------------
12 10
13 11 #-----------------------------------------------------------------------------
14 12 # Imports
15 13 #-----------------------------------------------------------------------------
16 14
17 15 # Our own packages
18 16 from IPython.core.magic import Bunch, Magics, magics_class, line_magic
19 17 from IPython.testing.skipdoctest import skip_doctest
20 18 from logging import error
21 19
22 20 #-----------------------------------------------------------------------------
23 21 # Magic implementation classes
24 22 #-----------------------------------------------------------------------------
25 23
26 24 @magics_class
27 25 class AutoMagics(Magics):
28 26 """Magics that control various autoX behaviors."""
29 27
30 28 def __init__(self, shell):
31 29 super(AutoMagics, self).__init__(shell)
32 30 # namespace for holding state we may need
33 31 self._magic_state = Bunch()
34 32
35 33 @line_magic
36 34 def automagic(self, parameter_s=''):
37 35 """Make magic functions callable without having to type the initial %.
38 36
39 37 Without argumentsl toggles on/off (when off, you must call it as
40 38 %automagic, of course). With arguments it sets the value, and you can
41 39 use any of (case insensitive):
42 40
43 41 - on, 1, True: to activate
44 42
45 43 - off, 0, False: to deactivate.
46 44
47 45 Note that magic functions have lowest priority, so if there's a
48 46 variable whose name collides with that of a magic fn, automagic won't
49 47 work for that function (you get the variable instead). However, if you
50 48 delete the variable (del var), the previously shadowed magic function
51 49 becomes visible to automagic again."""
52 50
53 51 arg = parameter_s.lower()
54 52 mman = self.shell.magics_manager
55 53 if arg in ('on', '1', 'true'):
56 54 val = True
57 55 elif arg in ('off', '0', 'false'):
58 56 val = False
59 57 else:
60 58 val = not mman.auto_magic
61 59 mman.auto_magic = val
62 60 print('\n' + self.shell.magics_manager.auto_status())
63 61
64 62 @skip_doctest
65 63 @line_magic
66 64 def autocall(self, parameter_s=''):
67 65 """Make functions callable without having to type parentheses.
68 66
69 67 Usage:
70 68
71 69 %autocall [mode]
72 70
73 71 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
74 72 value is toggled on and off (remembering the previous state).
75 73
76 74 In more detail, these values mean:
77 75
78 76 0 -> fully disabled
79 77
80 78 1 -> active, but do not apply if there are no arguments on the line.
81 79
82 80 In this mode, you get::
83 81
84 82 In [1]: callable
85 83 Out[1]: <built-in function callable>
86 84
87 85 In [2]: callable 'hello'
88 86 ------> callable('hello')
89 87 Out[2]: False
90 88
91 89 2 -> Active always. Even if no arguments are present, the callable
92 90 object is called::
93 91
94 92 In [2]: float
95 93 ------> float()
96 94 Out[2]: 0.0
97 95
98 96 Note that even with autocall off, you can still use '/' at the start of
99 97 a line to treat the first argument on the command line as a function
100 98 and add parentheses to it::
101 99
102 100 In [8]: /str 43
103 101 ------> str(43)
104 102 Out[8]: '43'
105 103
106 104 # all-random (note for auto-testing)
107 105 """
108 106
109 107 if parameter_s:
110 108 arg = int(parameter_s)
111 109 else:
112 110 arg = 'toggle'
113 111
114 112 if not arg in (0, 1, 2, 'toggle'):
115 113 error('Valid modes: (0->Off, 1->Smart, 2->Full')
116 114 return
117 115
118 116 if arg in (0, 1, 2):
119 117 self.shell.autocall = arg
120 118 else: # toggle
121 119 if self.shell.autocall:
122 120 self._magic_state.autocall_save = self.shell.autocall
123 121 self.shell.autocall = 0
124 122 else:
125 123 try:
126 124 self.shell.autocall = self._magic_state.autocall_save
127 125 except AttributeError:
128 126 self.shell.autocall = self._magic_state.autocall_save = 1
129 127
130 128 print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
@@ -1,583 +1,581 b''
1 1 """Implementation of basic magic functions."""
2 2
3 from __future__ import print_function
4 from __future__ import absolute_import
5 3
6 4 import argparse
7 5 import io
8 6 import sys
9 7 from pprint import pformat
10 8
11 9 from IPython.core import magic_arguments, page
12 10 from IPython.core.error import UsageError
13 11 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
14 12 from IPython.utils.text import format_screen, dedent, indent
15 13 from IPython.testing.skipdoctest import skip_doctest
16 14 from IPython.utils.ipstruct import Struct
17 15 from IPython.utils.py3compat import unicode_type
18 16 from warnings import warn
19 17 from logging import error
20 18
21 19
22 20 class MagicsDisplay(object):
23 21 def __init__(self, magics_manager):
24 22 self.magics_manager = magics_manager
25 23
26 24 def _lsmagic(self):
27 25 """The main implementation of the %lsmagic"""
28 26 mesc = magic_escapes['line']
29 27 cesc = magic_escapes['cell']
30 28 mman = self.magics_manager
31 29 magics = mman.lsmagic()
32 30 out = ['Available line magics:',
33 31 mesc + (' '+mesc).join(sorted(magics['line'])),
34 32 '',
35 33 'Available cell magics:',
36 34 cesc + (' '+cesc).join(sorted(magics['cell'])),
37 35 '',
38 36 mman.auto_status()]
39 37 return '\n'.join(out)
40 38
41 39 def _repr_pretty_(self, p, cycle):
42 40 p.text(self._lsmagic())
43 41
44 42 def __str__(self):
45 43 return self._lsmagic()
46 44
47 45 def _jsonable(self):
48 46 """turn magics dict into jsonable dict of the same structure
49 47
50 48 replaces object instances with their class names as strings
51 49 """
52 50 magic_dict = {}
53 51 mman = self.magics_manager
54 52 magics = mman.lsmagic()
55 53 for key, subdict in magics.items():
56 54 d = {}
57 55 magic_dict[key] = d
58 56 for name, obj in subdict.items():
59 57 try:
60 58 classname = obj.__self__.__class__.__name__
61 59 except AttributeError:
62 60 classname = 'Other'
63 61
64 62 d[name] = classname
65 63 return magic_dict
66 64
67 65 def _repr_json_(self):
68 66 return self._jsonable()
69 67
70 68
71 69 @magics_class
72 70 class BasicMagics(Magics):
73 71 """Magics that provide central IPython functionality.
74 72
75 73 These are various magics that don't fit into specific categories but that
76 74 are all part of the base 'IPython experience'."""
77 75
78 76 @magic_arguments.magic_arguments()
79 77 @magic_arguments.argument(
80 78 '-l', '--line', action='store_true',
81 79 help="""Create a line magic alias."""
82 80 )
83 81 @magic_arguments.argument(
84 82 '-c', '--cell', action='store_true',
85 83 help="""Create a cell magic alias."""
86 84 )
87 85 @magic_arguments.argument(
88 86 'name',
89 87 help="""Name of the magic to be created."""
90 88 )
91 89 @magic_arguments.argument(
92 90 'target',
93 91 help="""Name of the existing line or cell magic."""
94 92 )
95 93 @line_magic
96 94 def alias_magic(self, line=''):
97 95 """Create an alias for an existing line or cell magic.
98 96
99 97 Examples
100 98 --------
101 99 ::
102 100
103 101 In [1]: %alias_magic t timeit
104 102 Created `%t` as an alias for `%timeit`.
105 103 Created `%%t` as an alias for `%%timeit`.
106 104
107 105 In [2]: %t -n1 pass
108 106 1 loops, best of 3: 954 ns per loop
109 107
110 108 In [3]: %%t -n1
111 109 ...: pass
112 110 ...:
113 111 1 loops, best of 3: 954 ns per loop
114 112
115 113 In [4]: %alias_magic --cell whereami pwd
116 114 UsageError: Cell magic function `%%pwd` not found.
117 115 In [5]: %alias_magic --line whereami pwd
118 116 Created `%whereami` as an alias for `%pwd`.
119 117
120 118 In [6]: %whereami
121 119 Out[6]: u'/home/testuser'
122 120 """
123 121 args = magic_arguments.parse_argstring(self.alias_magic, line)
124 122 shell = self.shell
125 123 mman = self.shell.magics_manager
126 124 escs = ''.join(magic_escapes.values())
127 125
128 126 target = args.target.lstrip(escs)
129 127 name = args.name.lstrip(escs)
130 128
131 129 # Find the requested magics.
132 130 m_line = shell.find_magic(target, 'line')
133 131 m_cell = shell.find_magic(target, 'cell')
134 132 if args.line and m_line is None:
135 133 raise UsageError('Line magic function `%s%s` not found.' %
136 134 (magic_escapes['line'], target))
137 135 if args.cell and m_cell is None:
138 136 raise UsageError('Cell magic function `%s%s` not found.' %
139 137 (magic_escapes['cell'], target))
140 138
141 139 # If --line and --cell are not specified, default to the ones
142 140 # that are available.
143 141 if not args.line and not args.cell:
144 142 if not m_line and not m_cell:
145 143 raise UsageError(
146 144 'No line or cell magic with name `%s` found.' % target
147 145 )
148 146 args.line = bool(m_line)
149 147 args.cell = bool(m_cell)
150 148
151 149 if args.line:
152 150 mman.register_alias(name, target, 'line')
153 151 print('Created `%s%s` as an alias for `%s%s`.' % (
154 152 magic_escapes['line'], name,
155 153 magic_escapes['line'], target))
156 154
157 155 if args.cell:
158 156 mman.register_alias(name, target, 'cell')
159 157 print('Created `%s%s` as an alias for `%s%s`.' % (
160 158 magic_escapes['cell'], name,
161 159 magic_escapes['cell'], target))
162 160
163 161 @line_magic
164 162 def lsmagic(self, parameter_s=''):
165 163 """List currently available magic functions."""
166 164 return MagicsDisplay(self.shell.magics_manager)
167 165
168 166 def _magic_docs(self, brief=False, rest=False):
169 167 """Return docstrings from magic functions."""
170 168 mman = self.shell.magics_manager
171 169 docs = mman.lsmagic_docs(brief, missing='No documentation')
172 170
173 171 if rest:
174 172 format_string = '**%s%s**::\n\n%s\n\n'
175 173 else:
176 174 format_string = '%s%s:\n%s\n'
177 175
178 176 return ''.join(
179 177 [format_string % (magic_escapes['line'], fname,
180 178 indent(dedent(fndoc)))
181 179 for fname, fndoc in sorted(docs['line'].items())]
182 180 +
183 181 [format_string % (magic_escapes['cell'], fname,
184 182 indent(dedent(fndoc)))
185 183 for fname, fndoc in sorted(docs['cell'].items())]
186 184 )
187 185
188 186 @line_magic
189 187 def magic(self, parameter_s=''):
190 188 """Print information about the magic function system.
191 189
192 190 Supported formats: -latex, -brief, -rest
193 191 """
194 192
195 193 mode = ''
196 194 try:
197 195 mode = parameter_s.split()[0][1:]
198 196 except IndexError:
199 197 pass
200 198
201 199 brief = (mode == 'brief')
202 200 rest = (mode == 'rest')
203 201 magic_docs = self._magic_docs(brief, rest)
204 202
205 203 if mode == 'latex':
206 204 print(self.format_latex(magic_docs))
207 205 return
208 206 else:
209 207 magic_docs = format_screen(magic_docs)
210 208
211 209 out = ["""
212 210 IPython's 'magic' functions
213 211 ===========================
214 212
215 213 The magic function system provides a series of functions which allow you to
216 214 control the behavior of IPython itself, plus a lot of system-type
217 215 features. There are two kinds of magics, line-oriented and cell-oriented.
218 216
219 217 Line magics are prefixed with the % character and work much like OS
220 218 command-line calls: they get as an argument the rest of the line, where
221 219 arguments are passed without parentheses or quotes. For example, this will
222 220 time the given statement::
223 221
224 222 %timeit range(1000)
225 223
226 224 Cell magics are prefixed with a double %%, and they are functions that get as
227 225 an argument not only the rest of the line, but also the lines below it in a
228 226 separate argument. These magics are called with two arguments: the rest of the
229 227 call line and the body of the cell, consisting of the lines below the first.
230 228 For example::
231 229
232 230 %%timeit x = numpy.random.randn((100, 100))
233 231 numpy.linalg.svd(x)
234 232
235 233 will time the execution of the numpy svd routine, running the assignment of x
236 234 as part of the setup phase, which is not timed.
237 235
238 236 In a line-oriented client (the terminal or Qt console IPython), starting a new
239 237 input with %% will automatically enter cell mode, and IPython will continue
240 238 reading input until a blank line is given. In the notebook, simply type the
241 239 whole cell as one entity, but keep in mind that the %% escape can only be at
242 240 the very start of the cell.
243 241
244 242 NOTE: If you have 'automagic' enabled (via the command line option or with the
245 243 %automagic function), you don't need to type in the % explicitly for line
246 244 magics; cell magics always require an explicit '%%' escape. By default,
247 245 IPython ships with automagic on, so you should only rarely need the % escape.
248 246
249 247 Example: typing '%cd mydir' (without the quotes) changes your working directory
250 248 to 'mydir', if it exists.
251 249
252 250 For a list of the available magic functions, use %lsmagic. For a description
253 251 of any of them, type %magic_name?, e.g. '%cd?'.
254 252
255 253 Currently the magic system has the following functions:""",
256 254 magic_docs,
257 255 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
258 256 str(self.lsmagic()),
259 257 ]
260 258 page.page('\n'.join(out))
261 259
262 260
263 261 @line_magic
264 262 def page(self, parameter_s=''):
265 263 """Pretty print the object and display it through a pager.
266 264
267 265 %page [options] OBJECT
268 266
269 267 If no object is given, use _ (last output).
270 268
271 269 Options:
272 270
273 271 -r: page str(object), don't pretty-print it."""
274 272
275 273 # After a function contributed by Olivier Aubert, slightly modified.
276 274
277 275 # Process options/args
278 276 opts, args = self.parse_options(parameter_s, 'r')
279 277 raw = 'r' in opts
280 278
281 279 oname = args and args or '_'
282 280 info = self.shell._ofind(oname)
283 281 if info['found']:
284 282 txt = (raw and str or pformat)( info['obj'] )
285 283 page.page(txt)
286 284 else:
287 285 print('Object `%s` not found' % oname)
288 286
289 287 @line_magic
290 288 def profile(self, parameter_s=''):
291 289 """Print your currently active IPython profile.
292 290
293 291 See Also
294 292 --------
295 293 prun : run code using the Python profiler
296 294 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
297 295 """
298 296 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
299 297 from IPython.core.application import BaseIPythonApplication
300 298 if BaseIPythonApplication.initialized():
301 299 print(BaseIPythonApplication.instance().profile)
302 300 else:
303 301 error("profile is an application-level value, but you don't appear to be in an IPython application")
304 302
305 303 @line_magic
306 304 def pprint(self, parameter_s=''):
307 305 """Toggle pretty printing on/off."""
308 306 ptformatter = self.shell.display_formatter.formatters['text/plain']
309 307 ptformatter.pprint = bool(1 - ptformatter.pprint)
310 308 print('Pretty printing has been turned',
311 309 ['OFF','ON'][ptformatter.pprint])
312 310
313 311 @line_magic
314 312 def colors(self, parameter_s=''):
315 313 """Switch color scheme for prompts, info system and exception handlers.
316 314
317 315 Currently implemented schemes: NoColor, Linux, LightBG.
318 316
319 317 Color scheme names are not case-sensitive.
320 318
321 319 Examples
322 320 --------
323 321 To get a plain black and white terminal::
324 322
325 323 %colors nocolor
326 324 """
327 325 def color_switch_err(name):
328 326 warn('Error changing %s color schemes.\n%s' %
329 327 (name, sys.exc_info()[1]), stacklevel=2)
330 328
331 329
332 330 new_scheme = parameter_s.strip()
333 331 if not new_scheme:
334 332 raise UsageError(
335 333 "%colors: you must specify a color scheme. See '%colors?'")
336 334 # local shortcut
337 335 shell = self.shell
338 336
339 337 # Set shell colour scheme
340 338 try:
341 339 shell.colors = new_scheme
342 340 shell.refresh_style()
343 341 except:
344 342 color_switch_err('shell')
345 343
346 344 # Set exception colors
347 345 try:
348 346 shell.InteractiveTB.set_colors(scheme = new_scheme)
349 347 shell.SyntaxTB.set_colors(scheme = new_scheme)
350 348 except:
351 349 color_switch_err('exception')
352 350
353 351 # Set info (for 'object?') colors
354 352 if shell.color_info:
355 353 try:
356 354 shell.inspector.set_active_scheme(new_scheme)
357 355 except:
358 356 color_switch_err('object inspector')
359 357 else:
360 358 shell.inspector.set_active_scheme('NoColor')
361 359
362 360 @line_magic
363 361 def xmode(self, parameter_s=''):
364 362 """Switch modes for the exception handlers.
365 363
366 364 Valid modes: Plain, Context and Verbose.
367 365
368 366 If called without arguments, acts as a toggle."""
369 367
370 368 def xmode_switch_err(name):
371 369 warn('Error changing %s exception modes.\n%s' %
372 370 (name,sys.exc_info()[1]))
373 371
374 372 shell = self.shell
375 373 new_mode = parameter_s.strip().capitalize()
376 374 try:
377 375 shell.InteractiveTB.set_mode(mode=new_mode)
378 376 print('Exception reporting mode:',shell.InteractiveTB.mode)
379 377 except:
380 378 xmode_switch_err('user')
381 379
382 380 @line_magic
383 381 def quickref(self,arg):
384 382 """ Show a quick reference sheet """
385 383 from IPython.core.usage import quick_reference
386 384 qr = quick_reference + self._magic_docs(brief=True)
387 385 page.page(qr)
388 386
389 387 @line_magic
390 388 def doctest_mode(self, parameter_s=''):
391 389 """Toggle doctest mode on and off.
392 390
393 391 This mode is intended to make IPython behave as much as possible like a
394 392 plain Python shell, from the perspective of how its prompts, exceptions
395 393 and output look. This makes it easy to copy and paste parts of a
396 394 session into doctests. It does so by:
397 395
398 396 - Changing the prompts to the classic ``>>>`` ones.
399 397 - Changing the exception reporting mode to 'Plain'.
400 398 - Disabling pretty-printing of output.
401 399
402 400 Note that IPython also supports the pasting of code snippets that have
403 401 leading '>>>' and '...' prompts in them. This means that you can paste
404 402 doctests from files or docstrings (even if they have leading
405 403 whitespace), and the code will execute correctly. You can then use
406 404 '%history -t' to see the translated history; this will give you the
407 405 input after removal of all the leading prompts and whitespace, which
408 406 can be pasted back into an editor.
409 407
410 408 With these features, you can switch into this mode easily whenever you
411 409 need to do testing and changes to doctests, without having to leave
412 410 your existing IPython session.
413 411 """
414 412
415 413 # Shorthands
416 414 shell = self.shell
417 415 meta = shell.meta
418 416 disp_formatter = self.shell.display_formatter
419 417 ptformatter = disp_formatter.formatters['text/plain']
420 418 # dstore is a data store kept in the instance metadata bag to track any
421 419 # changes we make, so we can undo them later.
422 420 dstore = meta.setdefault('doctest_mode',Struct())
423 421 save_dstore = dstore.setdefault
424 422
425 423 # save a few values we'll need to recover later
426 424 mode = save_dstore('mode',False)
427 425 save_dstore('rc_pprint',ptformatter.pprint)
428 426 save_dstore('xmode',shell.InteractiveTB.mode)
429 427 save_dstore('rc_separate_out',shell.separate_out)
430 428 save_dstore('rc_separate_out2',shell.separate_out2)
431 429 save_dstore('rc_separate_in',shell.separate_in)
432 430 save_dstore('rc_active_types',disp_formatter.active_types)
433 431
434 432 if not mode:
435 433 # turn on
436 434
437 435 # Prompt separators like plain python
438 436 shell.separate_in = ''
439 437 shell.separate_out = ''
440 438 shell.separate_out2 = ''
441 439
442 440
443 441 ptformatter.pprint = False
444 442 disp_formatter.active_types = ['text/plain']
445 443
446 444 shell.magic('xmode Plain')
447 445 else:
448 446 # turn off
449 447 shell.separate_in = dstore.rc_separate_in
450 448
451 449 shell.separate_out = dstore.rc_separate_out
452 450 shell.separate_out2 = dstore.rc_separate_out2
453 451
454 452 ptformatter.pprint = dstore.rc_pprint
455 453 disp_formatter.active_types = dstore.rc_active_types
456 454
457 455 shell.magic('xmode ' + dstore.xmode)
458 456
459 457 # mode here is the state before we switch; switch_doctest_mode takes
460 458 # the mode we're switching to.
461 459 shell.switch_doctest_mode(not mode)
462 460
463 461 # Store new mode and inform
464 462 dstore.mode = bool(not mode)
465 463 mode_label = ['OFF','ON'][dstore.mode]
466 464 print('Doctest mode is:', mode_label)
467 465
468 466 @line_magic
469 467 def gui(self, parameter_s=''):
470 468 """Enable or disable IPython GUI event loop integration.
471 469
472 470 %gui [GUINAME]
473 471
474 472 This magic replaces IPython's threaded shells that were activated
475 473 using the (pylab/wthread/etc.) command line flags. GUI toolkits
476 474 can now be enabled at runtime and keyboard
477 475 interrupts should work without any problems. The following toolkits
478 476 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
479 477
480 478 %gui wx # enable wxPython event loop integration
481 479 %gui qt4|qt # enable PyQt4 event loop integration
482 480 %gui qt5 # enable PyQt5 event loop integration
483 481 %gui gtk # enable PyGTK event loop integration
484 482 %gui gtk3 # enable Gtk3 event loop integration
485 483 %gui tk # enable Tk event loop integration
486 484 %gui osx # enable Cocoa event loop integration
487 485 # (requires %matplotlib 1.1)
488 486 %gui # disable all event loop integration
489 487
490 488 WARNING: after any of these has been called you can simply create
491 489 an application object, but DO NOT start the event loop yourself, as
492 490 we have already handled that.
493 491 """
494 492 opts, arg = self.parse_options(parameter_s, '')
495 493 if arg=='': arg = None
496 494 try:
497 495 return self.shell.enable_gui(arg)
498 496 except Exception as e:
499 497 # print simple error message, rather than traceback if we can't
500 498 # hook up the GUI
501 499 error(str(e))
502 500
503 501 @skip_doctest
504 502 @line_magic
505 503 def precision(self, s=''):
506 504 """Set floating point precision for pretty printing.
507 505
508 506 Can set either integer precision or a format string.
509 507
510 508 If numpy has been imported and precision is an int,
511 509 numpy display precision will also be set, via ``numpy.set_printoptions``.
512 510
513 511 If no argument is given, defaults will be restored.
514 512
515 513 Examples
516 514 --------
517 515 ::
518 516
519 517 In [1]: from math import pi
520 518
521 519 In [2]: %precision 3
522 520 Out[2]: u'%.3f'
523 521
524 522 In [3]: pi
525 523 Out[3]: 3.142
526 524
527 525 In [4]: %precision %i
528 526 Out[4]: u'%i'
529 527
530 528 In [5]: pi
531 529 Out[5]: 3
532 530
533 531 In [6]: %precision %e
534 532 Out[6]: u'%e'
535 533
536 534 In [7]: pi**10
537 535 Out[7]: 9.364805e+04
538 536
539 537 In [8]: %precision
540 538 Out[8]: u'%r'
541 539
542 540 In [9]: pi**10
543 541 Out[9]: 93648.047476082982
544 542 """
545 543 ptformatter = self.shell.display_formatter.formatters['text/plain']
546 544 ptformatter.float_precision = s
547 545 return ptformatter.float_format
548 546
549 547 @magic_arguments.magic_arguments()
550 548 @magic_arguments.argument(
551 549 '-e', '--export', action='store_true', default=False,
552 550 help=argparse.SUPPRESS
553 551 )
554 552 @magic_arguments.argument(
555 553 'filename', type=unicode_type,
556 554 help='Notebook name or filename'
557 555 )
558 556 @line_magic
559 557 def notebook(self, s):
560 558 """Export and convert IPython notebooks.
561 559
562 560 This function can export the current IPython history to a notebook file.
563 561 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
564 562
565 563 The -e or --export flag is deprecated in IPython 5.2, and will be
566 564 removed in the future.
567 565 """
568 566 args = magic_arguments.parse_argstring(self.notebook, s)
569 567
570 568 from nbformat import write, v4
571 569
572 570 cells = []
573 571 hist = list(self.shell.history_manager.get_range())
574 572 if(len(hist)<=1):
575 573 raise ValueError('History is empty, cannot export')
576 574 for session, execution_count, source in hist[:-1]:
577 575 cells.append(v4.new_code_cell(
578 576 execution_count=execution_count,
579 577 source=source
580 578 ))
581 579 nb = v4.new_notebook(cells=cells)
582 580 with io.open(args.filename, 'w', encoding='utf-8') as f:
583 581 write(nb, f, version=4)
@@ -1,746 +1,744 b''
1 1 """Implementation of code management magic functions.
2 2 """
3 from __future__ import print_function
4 from __future__ import absolute_import
5 3 #-----------------------------------------------------------------------------
6 4 # Copyright (c) 2012 The IPython Development Team.
7 5 #
8 6 # Distributed under the terms of the Modified BSD License.
9 7 #
10 8 # The full license is in the file COPYING.txt, distributed with this software.
11 9 #-----------------------------------------------------------------------------
12 10
13 11 #-----------------------------------------------------------------------------
14 12 # Imports
15 13 #-----------------------------------------------------------------------------
16 14
17 15 # Stdlib
18 16 import inspect
19 17 import io
20 18 import os
21 19 import re
22 20 import sys
23 21 import ast
24 22 from itertools import chain
25 23
26 24 # Our own packages
27 25 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
28 26 from IPython.core.macro import Macro
29 27 from IPython.core.magic import Magics, magics_class, line_magic
30 28 from IPython.core.oinspect import find_file, find_source_lines
31 29 from IPython.testing.skipdoctest import skip_doctest
32 30 from IPython.utils import py3compat
33 31 from IPython.utils.py3compat import string_types
34 32 from IPython.utils.contexts import preserve_keys
35 33 from IPython.utils.path import get_py_filename
36 34 from warnings import warn
37 35 from logging import error
38 36 from IPython.utils.text import get_text_list
39 37
40 38 #-----------------------------------------------------------------------------
41 39 # Magic implementation classes
42 40 #-----------------------------------------------------------------------------
43 41
44 42 # Used for exception handling in magic_edit
45 43 class MacroToEdit(ValueError): pass
46 44
47 45 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
48 46
49 47 # To match, e.g. 8-10 1:5 :10 3-
50 48 range_re = re.compile(r"""
51 49 (?P<start>\d+)?
52 50 ((?P<sep>[\-:])
53 51 (?P<end>\d+)?)?
54 52 $""", re.VERBOSE)
55 53
56 54
57 55 def extract_code_ranges(ranges_str):
58 56 """Turn a string of range for %%load into 2-tuples of (start, stop)
59 57 ready to use as a slice of the content splitted by lines.
60 58
61 59 Examples
62 60 --------
63 61 list(extract_input_ranges("5-10 2"))
64 62 [(4, 10), (1, 2)]
65 63 """
66 64 for range_str in ranges_str.split():
67 65 rmatch = range_re.match(range_str)
68 66 if not rmatch:
69 67 continue
70 68 sep = rmatch.group("sep")
71 69 start = rmatch.group("start")
72 70 end = rmatch.group("end")
73 71
74 72 if sep == '-':
75 73 start = int(start) - 1 if start else None
76 74 end = int(end) if end else None
77 75 elif sep == ':':
78 76 start = int(start) - 1 if start else None
79 77 end = int(end) - 1 if end else None
80 78 else:
81 79 end = int(start)
82 80 start = int(start) - 1
83 81 yield (start, end)
84 82
85 83
86 84 @skip_doctest
87 85 def extract_symbols(code, symbols):
88 86 """
89 87 Return a tuple (blocks, not_found)
90 88 where ``blocks`` is a list of code fragments
91 89 for each symbol parsed from code, and ``not_found`` are
92 90 symbols not found in the code.
93 91
94 92 For example::
95 93
96 94 >>> code = '''a = 10
97 95
98 96 def b(): return 42
99 97
100 98 class A: pass'''
101 99
102 100 >>> extract_symbols(code, 'A,b,z')
103 101 (["class A: pass", "def b(): return 42"], ['z'])
104 102 """
105 103 symbols = symbols.split(',')
106 104
107 105 # this will raise SyntaxError if code isn't valid Python
108 106 py_code = ast.parse(code)
109 107
110 108 marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
111 109 code = code.split('\n')
112 110
113 111 symbols_lines = {}
114 112
115 113 # we already know the start_lineno of each symbol (marks).
116 114 # To find each end_lineno, we traverse in reverse order until each
117 115 # non-blank line
118 116 end = len(code)
119 117 for name, start in reversed(marks):
120 118 while not code[end - 1].strip():
121 119 end -= 1
122 120 if name:
123 121 symbols_lines[name] = (start - 1, end)
124 122 end = start - 1
125 123
126 124 # Now symbols_lines is a map
127 125 # {'symbol_name': (start_lineno, end_lineno), ...}
128 126
129 127 # fill a list with chunks of codes for each requested symbol
130 128 blocks = []
131 129 not_found = []
132 130 for symbol in symbols:
133 131 if symbol in symbols_lines:
134 132 start, end = symbols_lines[symbol]
135 133 blocks.append('\n'.join(code[start:end]) + '\n')
136 134 else:
137 135 not_found.append(symbol)
138 136
139 137 return blocks, not_found
140 138
141 139 def strip_initial_indent(lines):
142 140 """For %load, strip indent from lines until finding an unindented line.
143 141
144 142 https://github.com/ipython/ipython/issues/9775
145 143 """
146 144 indent_re = re.compile(r'\s+')
147 145
148 146 it = iter(lines)
149 147 first_line = next(it)
150 148 indent_match = indent_re.match(first_line)
151 149
152 150 if indent_match:
153 151 # First line was indented
154 152 indent = indent_match.group()
155 153 yield first_line[len(indent):]
156 154
157 155 for line in it:
158 156 if line.startswith(indent):
159 157 yield line[len(indent):]
160 158 else:
161 159 # Less indented than the first line - stop dedenting
162 160 yield line
163 161 break
164 162 else:
165 163 yield first_line
166 164
167 165 # Pass the remaining lines through without dedenting
168 166 for line in it:
169 167 yield line
170 168
171 169
172 170 class InteractivelyDefined(Exception):
173 171 """Exception for interactively defined variable in magic_edit"""
174 172 def __init__(self, index):
175 173 self.index = index
176 174
177 175
178 176 @magics_class
179 177 class CodeMagics(Magics):
180 178 """Magics related to code management (loading, saving, editing, ...)."""
181 179
182 180 def __init__(self, *args, **kwargs):
183 181 self._knowntemps = set()
184 182 super(CodeMagics, self).__init__(*args, **kwargs)
185 183
186 184 @line_magic
187 185 def save(self, parameter_s=''):
188 186 """Save a set of lines or a macro to a given filename.
189 187
190 188 Usage:\\
191 189 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
192 190
193 191 Options:
194 192
195 193 -r: use 'raw' input. By default, the 'processed' history is used,
196 194 so that magics are loaded in their transformed version to valid
197 195 Python. If this option is given, the raw input as typed as the
198 196 command line is used instead.
199 197
200 198 -f: force overwrite. If file exists, %save will prompt for overwrite
201 199 unless -f is given.
202 200
203 201 -a: append to the file instead of overwriting it.
204 202
205 203 This function uses the same syntax as %history for input ranges,
206 204 then saves the lines to the filename you specify.
207 205
208 206 It adds a '.py' extension to the file if you don't do so yourself, and
209 207 it asks for confirmation before overwriting existing files.
210 208
211 209 If `-r` option is used, the default extension is `.ipy`.
212 210 """
213 211
214 212 opts,args = self.parse_options(parameter_s,'fra',mode='list')
215 213 if not args:
216 214 raise UsageError('Missing filename.')
217 215 raw = 'r' in opts
218 216 force = 'f' in opts
219 217 append = 'a' in opts
220 218 mode = 'a' if append else 'w'
221 219 ext = u'.ipy' if raw else u'.py'
222 220 fname, codefrom = args[0], " ".join(args[1:])
223 221 if not fname.endswith((u'.py',u'.ipy')):
224 222 fname += ext
225 223 file_exists = os.path.isfile(fname)
226 224 if file_exists and not force and not append:
227 225 try:
228 226 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
229 227 except StdinNotImplementedError:
230 228 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
231 229 return
232 230 if not overwrite :
233 231 print('Operation cancelled.')
234 232 return
235 233 try:
236 234 cmds = self.shell.find_user_code(codefrom,raw)
237 235 except (TypeError, ValueError) as e:
238 236 print(e.args[0])
239 237 return
240 238 out = py3compat.cast_unicode(cmds)
241 239 with io.open(fname, mode, encoding="utf-8") as f:
242 240 if not file_exists or not append:
243 241 f.write(u"# coding: utf-8\n")
244 242 f.write(out)
245 243 # make sure we end on a newline
246 244 if not out.endswith(u'\n'):
247 245 f.write(u'\n')
248 246 print('The following commands were written to file `%s`:' % fname)
249 247 print(cmds)
250 248
251 249 @line_magic
252 250 def pastebin(self, parameter_s=''):
253 251 """Upload code to Github's Gist paste bin, returning the URL.
254 252
255 253 Usage:\\
256 254 %pastebin [-d "Custom description"] 1-7
257 255
258 256 The argument can be an input history range, a filename, or the name of a
259 257 string or macro.
260 258
261 259 Options:
262 260
263 261 -d: Pass a custom description for the gist. The default will say
264 262 "Pasted from IPython".
265 263 """
266 264 opts, args = self.parse_options(parameter_s, 'd:')
267 265
268 266 try:
269 267 code = self.shell.find_user_code(args)
270 268 except (ValueError, TypeError) as e:
271 269 print(e.args[0])
272 270 return
273 271
274 272 # Deferred import
275 273 try:
276 274 from urllib.request import urlopen # Py 3
277 275 except ImportError:
278 276 from urllib2 import urlopen
279 277 import json
280 278 post_data = json.dumps({
281 279 "description": opts.get('d', "Pasted from IPython"),
282 280 "public": True,
283 281 "files": {
284 282 "file1.py": {
285 283 "content": code
286 284 }
287 285 }
288 286 }).encode('utf-8')
289 287
290 288 response = urlopen("https://api.github.com/gists", post_data)
291 289 response_data = json.loads(response.read().decode('utf-8'))
292 290 return response_data['html_url']
293 291
294 292 @line_magic
295 293 def loadpy(self, arg_s):
296 294 """Alias of `%load`
297 295
298 296 `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
299 297 extension. So it has been renamed simply into %load. You can look at
300 298 `%load`'s docstring for more info.
301 299 """
302 300 self.load(arg_s)
303 301
304 302 @line_magic
305 303 def load(self, arg_s):
306 304 """Load code into the current frontend.
307 305
308 306 Usage:\\
309 307 %load [options] source
310 308
311 309 where source can be a filename, URL, input history range, macro, or
312 310 element in the user namespace
313 311
314 312 Options:
315 313
316 314 -r <lines>: Specify lines or ranges of lines to load from the source.
317 315 Ranges could be specified as x-y (x..y) or in python-style x:y
318 316 (x..(y-1)). Both limits x and y can be left blank (meaning the
319 317 beginning and end of the file, respectively).
320 318
321 319 -s <symbols>: Specify function or classes to load from python source.
322 320
323 321 -y : Don't ask confirmation for loading source above 200 000 characters.
324 322
325 323 -n : Include the user's namespace when searching for source code.
326 324
327 325 This magic command can either take a local filename, a URL, an history
328 326 range (see %history) or a macro as argument, it will prompt for
329 327 confirmation before loading source with more than 200 000 characters, unless
330 328 -y flag is passed or if the frontend does not support raw_input::
331 329
332 330 %load myscript.py
333 331 %load 7-27
334 332 %load myMacro
335 333 %load http://www.example.com/myscript.py
336 334 %load -r 5-10 myscript.py
337 335 %load -r 10-20,30,40: foo.py
338 336 %load -s MyClass,wonder_function myscript.py
339 337 %load -n MyClass
340 338 %load -n my_module.wonder_function
341 339 """
342 340 opts,args = self.parse_options(arg_s,'yns:r:')
343 341
344 342 if not args:
345 343 raise UsageError('Missing filename, URL, input history range, '
346 344 'macro, or element in the user namespace.')
347 345
348 346 search_ns = 'n' in opts
349 347
350 348 contents = self.shell.find_user_code(args, search_ns=search_ns)
351 349
352 350 if 's' in opts:
353 351 try:
354 352 blocks, not_found = extract_symbols(contents, opts['s'])
355 353 except SyntaxError:
356 354 # non python code
357 355 error("Unable to parse the input as valid Python code")
358 356 return
359 357
360 358 if len(not_found) == 1:
361 359 warn('The symbol `%s` was not found' % not_found[0])
362 360 elif len(not_found) > 1:
363 361 warn('The symbols %s were not found' % get_text_list(not_found,
364 362 wrap_item_with='`')
365 363 )
366 364
367 365 contents = '\n'.join(blocks)
368 366
369 367 if 'r' in opts:
370 368 ranges = opts['r'].replace(',', ' ')
371 369 lines = contents.split('\n')
372 370 slices = extract_code_ranges(ranges)
373 371 contents = [lines[slice(*slc)] for slc in slices]
374 372 contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
375 373
376 374 l = len(contents)
377 375
378 376 # 200 000 is ~ 2500 full 80 caracter lines
379 377 # so in average, more than 5000 lines
380 378 if l > 200000 and 'y' not in opts:
381 379 try:
382 380 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
383 381 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
384 382 except StdinNotImplementedError:
385 383 #asume yes if raw input not implemented
386 384 ans = True
387 385
388 386 if ans is False :
389 387 print('Operation cancelled.')
390 388 return
391 389
392 390 contents = "# %load {}\n".format(arg_s) + contents
393 391
394 392 self.shell.set_next_input(contents, replace=True)
395 393
396 394 @staticmethod
397 395 def _find_edit_target(shell, args, opts, last_call):
398 396 """Utility method used by magic_edit to find what to edit."""
399 397
400 398 def make_filename(arg):
401 399 "Make a filename from the given args"
402 400 try:
403 401 filename = get_py_filename(arg)
404 402 except IOError:
405 403 # If it ends with .py but doesn't already exist, assume we want
406 404 # a new file.
407 405 if arg.endswith('.py'):
408 406 filename = arg
409 407 else:
410 408 filename = None
411 409 return filename
412 410
413 411 # Set a few locals from the options for convenience:
414 412 opts_prev = 'p' in opts
415 413 opts_raw = 'r' in opts
416 414
417 415 # custom exceptions
418 416 class DataIsObject(Exception): pass
419 417
420 418 # Default line number value
421 419 lineno = opts.get('n',None)
422 420
423 421 if opts_prev:
424 422 args = '_%s' % last_call[0]
425 423 if args not in shell.user_ns:
426 424 args = last_call[1]
427 425
428 426 # by default this is done with temp files, except when the given
429 427 # arg is a filename
430 428 use_temp = True
431 429
432 430 data = ''
433 431
434 432 # First, see if the arguments should be a filename.
435 433 filename = make_filename(args)
436 434 if filename:
437 435 use_temp = False
438 436 elif args:
439 437 # Mode where user specifies ranges of lines, like in %macro.
440 438 data = shell.extract_input_lines(args, opts_raw)
441 439 if not data:
442 440 try:
443 441 # Load the parameter given as a variable. If not a string,
444 442 # process it as an object instead (below)
445 443
446 444 #print '*** args',args,'type',type(args) # dbg
447 445 data = eval(args, shell.user_ns)
448 446 if not isinstance(data, string_types):
449 447 raise DataIsObject
450 448
451 449 except (NameError,SyntaxError):
452 450 # given argument is not a variable, try as a filename
453 451 filename = make_filename(args)
454 452 if filename is None:
455 453 warn("Argument given (%s) can't be found as a variable "
456 454 "or as a filename." % args)
457 455 return (None, None, None)
458 456 use_temp = False
459 457
460 458 except DataIsObject:
461 459 # macros have a special edit function
462 460 if isinstance(data, Macro):
463 461 raise MacroToEdit(data)
464 462
465 463 # For objects, try to edit the file where they are defined
466 464 filename = find_file(data)
467 465 if filename:
468 466 if 'fakemodule' in filename.lower() and \
469 467 inspect.isclass(data):
470 468 # class created by %edit? Try to find source
471 469 # by looking for method definitions instead, the
472 470 # __module__ in those classes is FakeModule.
473 471 attrs = [getattr(data, aname) for aname in dir(data)]
474 472 for attr in attrs:
475 473 if not inspect.ismethod(attr):
476 474 continue
477 475 filename = find_file(attr)
478 476 if filename and \
479 477 'fakemodule' not in filename.lower():
480 478 # change the attribute to be the edit
481 479 # target instead
482 480 data = attr
483 481 break
484 482
485 483 m = ipython_input_pat.match(os.path.basename(filename))
486 484 if m:
487 485 raise InteractivelyDefined(int(m.groups()[0]))
488 486
489 487 datafile = 1
490 488 if filename is None:
491 489 filename = make_filename(args)
492 490 datafile = 1
493 491 if filename is not None:
494 492 # only warn about this if we get a real name
495 493 warn('Could not find file where `%s` is defined.\n'
496 494 'Opening a file named `%s`' % (args, filename))
497 495 # Now, make sure we can actually read the source (if it was
498 496 # in a temp file it's gone by now).
499 497 if datafile:
500 498 if lineno is None:
501 499 lineno = find_source_lines(data)
502 500 if lineno is None:
503 501 filename = make_filename(args)
504 502 if filename is None:
505 503 warn('The file where `%s` was defined '
506 504 'cannot be read or found.' % data)
507 505 return (None, None, None)
508 506 use_temp = False
509 507
510 508 if use_temp:
511 509 filename = shell.mktempfile(data)
512 510 print('IPython will make a temporary file named:',filename)
513 511
514 512 # use last_call to remember the state of the previous call, but don't
515 513 # let it be clobbered by successive '-p' calls.
516 514 try:
517 515 last_call[0] = shell.displayhook.prompt_count
518 516 if not opts_prev:
519 517 last_call[1] = args
520 518 except:
521 519 pass
522 520
523 521
524 522 return filename, lineno, use_temp
525 523
526 524 def _edit_macro(self,mname,macro):
527 525 """open an editor with the macro data in a file"""
528 526 filename = self.shell.mktempfile(macro.value)
529 527 self.shell.hooks.editor(filename)
530 528
531 529 # and make a new macro object, to replace the old one
532 530 with open(filename) as mfile:
533 531 mvalue = mfile.read()
534 532 self.shell.user_ns[mname] = Macro(mvalue)
535 533
536 534 @skip_doctest
537 535 @line_magic
538 536 def edit(self, parameter_s='',last_call=['','']):
539 537 """Bring up an editor and execute the resulting code.
540 538
541 539 Usage:
542 540 %edit [options] [args]
543 541
544 542 %edit runs IPython's editor hook. The default version of this hook is
545 543 set to call the editor specified by your $EDITOR environment variable.
546 544 If this isn't found, it will default to vi under Linux/Unix and to
547 545 notepad under Windows. See the end of this docstring for how to change
548 546 the editor hook.
549 547
550 548 You can also set the value of this editor via the
551 549 ``TerminalInteractiveShell.editor`` option in your configuration file.
552 550 This is useful if you wish to use a different editor from your typical
553 551 default with IPython (and for Windows users who typically don't set
554 552 environment variables).
555 553
556 554 This command allows you to conveniently edit multi-line code right in
557 555 your IPython session.
558 556
559 557 If called without arguments, %edit opens up an empty editor with a
560 558 temporary file and will execute the contents of this file when you
561 559 close it (don't forget to save it!).
562 560
563 561
564 562 Options:
565 563
566 564 -n <number>: open the editor at a specified line number. By default,
567 565 the IPython editor hook uses the unix syntax 'editor +N filename', but
568 566 you can configure this by providing your own modified hook if your
569 567 favorite editor supports line-number specifications with a different
570 568 syntax.
571 569
572 570 -p: this will call the editor with the same data as the previous time
573 571 it was used, regardless of how long ago (in your current session) it
574 572 was.
575 573
576 574 -r: use 'raw' input. This option only applies to input taken from the
577 575 user's history. By default, the 'processed' history is used, so that
578 576 magics are loaded in their transformed version to valid Python. If
579 577 this option is given, the raw input as typed as the command line is
580 578 used instead. When you exit the editor, it will be executed by
581 579 IPython's own processor.
582 580
583 581 -x: do not execute the edited code immediately upon exit. This is
584 582 mainly useful if you are editing programs which need to be called with
585 583 command line arguments, which you can then do using %run.
586 584
587 585
588 586 Arguments:
589 587
590 588 If arguments are given, the following possibilities exist:
591 589
592 590 - If the argument is a filename, IPython will load that into the
593 591 editor. It will execute its contents with execfile() when you exit,
594 592 loading any code in the file into your interactive namespace.
595 593
596 594 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
597 595 The syntax is the same as in the %history magic.
598 596
599 597 - If the argument is a string variable, its contents are loaded
600 598 into the editor. You can thus edit any string which contains
601 599 python code (including the result of previous edits).
602 600
603 601 - If the argument is the name of an object (other than a string),
604 602 IPython will try to locate the file where it was defined and open the
605 603 editor at the point where it is defined. You can use `%edit function`
606 604 to load an editor exactly at the point where 'function' is defined,
607 605 edit it and have the file be executed automatically.
608 606
609 607 - If the object is a macro (see %macro for details), this opens up your
610 608 specified editor with a temporary file containing the macro's data.
611 609 Upon exit, the macro is reloaded with the contents of the file.
612 610
613 611 Note: opening at an exact line is only supported under Unix, and some
614 612 editors (like kedit and gedit up to Gnome 2.8) do not understand the
615 613 '+NUMBER' parameter necessary for this feature. Good editors like
616 614 (X)Emacs, vi, jed, pico and joe all do.
617 615
618 616 After executing your code, %edit will return as output the code you
619 617 typed in the editor (except when it was an existing file). This way
620 618 you can reload the code in further invocations of %edit as a variable,
621 619 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
622 620 the output.
623 621
624 622 Note that %edit is also available through the alias %ed.
625 623
626 624 This is an example of creating a simple function inside the editor and
627 625 then modifying it. First, start up the editor::
628 626
629 627 In [1]: edit
630 628 Editing... done. Executing edited code...
631 629 Out[1]: 'def foo():\\n print "foo() was defined in an editing
632 630 session"\\n'
633 631
634 632 We can then call the function foo()::
635 633
636 634 In [2]: foo()
637 635 foo() was defined in an editing session
638 636
639 637 Now we edit foo. IPython automatically loads the editor with the
640 638 (temporary) file where foo() was previously defined::
641 639
642 640 In [3]: edit foo
643 641 Editing... done. Executing edited code...
644 642
645 643 And if we call foo() again we get the modified version::
646 644
647 645 In [4]: foo()
648 646 foo() has now been changed!
649 647
650 648 Here is an example of how to edit a code snippet successive
651 649 times. First we call the editor::
652 650
653 651 In [5]: edit
654 652 Editing... done. Executing edited code...
655 653 hello
656 654 Out[5]: "print 'hello'\\n"
657 655
658 656 Now we call it again with the previous output (stored in _)::
659 657
660 658 In [6]: edit _
661 659 Editing... done. Executing edited code...
662 660 hello world
663 661 Out[6]: "print 'hello world'\\n"
664 662
665 663 Now we call it with the output #8 (stored in _8, also as Out[8])::
666 664
667 665 In [7]: edit _8
668 666 Editing... done. Executing edited code...
669 667 hello again
670 668 Out[7]: "print 'hello again'\\n"
671 669
672 670
673 671 Changing the default editor hook:
674 672
675 673 If you wish to write your own editor hook, you can put it in a
676 674 configuration file which you load at startup time. The default hook
677 675 is defined in the IPython.core.hooks module, and you can use that as a
678 676 starting example for further modifications. That file also has
679 677 general instructions on how to set a new hook for use once you've
680 678 defined it."""
681 679 opts,args = self.parse_options(parameter_s,'prxn:')
682 680
683 681 try:
684 682 filename, lineno, is_temp = self._find_edit_target(self.shell,
685 683 args, opts, last_call)
686 684 except MacroToEdit as e:
687 685 self._edit_macro(args, e.args[0])
688 686 return
689 687 except InteractivelyDefined as e:
690 688 print("Editing In[%i]" % e.index)
691 689 args = str(e.index)
692 690 filename, lineno, is_temp = self._find_edit_target(self.shell,
693 691 args, opts, last_call)
694 692 if filename is None:
695 693 # nothing was found, warnings have already been issued,
696 694 # just give up.
697 695 return
698 696
699 697 if is_temp:
700 698 self._knowntemps.add(filename)
701 699 elif (filename in self._knowntemps):
702 700 is_temp = True
703 701
704 702
705 703 # do actual editing here
706 704 print('Editing...', end=' ')
707 705 sys.stdout.flush()
708 706 try:
709 707 # Quote filenames that may have spaces in them
710 708 if ' ' in filename:
711 709 filename = "'%s'" % filename
712 710 self.shell.hooks.editor(filename,lineno)
713 711 except TryNext:
714 712 warn('Could not open editor')
715 713 return
716 714
717 715 # XXX TODO: should this be generalized for all string vars?
718 716 # For now, this is special-cased to blocks created by cpaste
719 717 if args.strip() == 'pasted_block':
720 718 with open(filename, 'r') as f:
721 719 self.shell.user_ns['pasted_block'] = f.read()
722 720
723 721 if 'x' in opts: # -x prevents actual execution
724 722 print()
725 723 else:
726 724 print('done. Executing edited code...')
727 725 with preserve_keys(self.shell.user_ns, '__file__'):
728 726 if not is_temp:
729 727 self.shell.user_ns['__file__'] = filename
730 728 if 'r' in opts: # Untranslated IPython code
731 729 with open(filename, 'r') as f:
732 730 source = f.read()
733 731 self.shell.run_cell(source, store_history=False)
734 732 else:
735 733 self.shell.safe_execfile(filename, self.shell.user_ns,
736 734 self.shell.user_ns)
737 735
738 736 if is_temp:
739 737 try:
740 738 return open(filename).read()
741 739 except IOError as msg:
742 740 if msg.filename == filename:
743 741 warn('File not found. Did you forget to save?')
744 742 return
745 743 else:
746 744 self.shell.showtraceback()
@@ -1,159 +1,157 b''
1 1 """Implementation of configuration-related magic functions.
2 2 """
3 from __future__ import print_function
4 from __future__ import absolute_import
5 3 #-----------------------------------------------------------------------------
6 4 # Copyright (c) 2012 The IPython Development Team.
7 5 #
8 6 # Distributed under the terms of the Modified BSD License.
9 7 #
10 8 # The full license is in the file COPYING.txt, distributed with this software.
11 9 #-----------------------------------------------------------------------------
12 10
13 11 #-----------------------------------------------------------------------------
14 12 # Imports
15 13 #-----------------------------------------------------------------------------
16 14
17 15 # Stdlib
18 16 import re
19 17
20 18 # Our own packages
21 19 from IPython.core.error import UsageError
22 20 from IPython.core.magic import Magics, magics_class, line_magic
23 21 from logging import error
24 22
25 23 #-----------------------------------------------------------------------------
26 24 # Magic implementation classes
27 25 #-----------------------------------------------------------------------------
28 26
29 27 reg = re.compile('^\w+\.\w+$')
30 28 @magics_class
31 29 class ConfigMagics(Magics):
32 30
33 31 def __init__(self, shell):
34 32 super(ConfigMagics, self).__init__(shell)
35 33 self.configurables = []
36 34
37 35 @line_magic
38 36 def config(self, s):
39 37 """configure IPython
40 38
41 39 %config Class[.trait=value]
42 40
43 41 This magic exposes most of the IPython config system. Any
44 42 Configurable class should be able to be configured with the simple
45 43 line::
46 44
47 45 %config Class.trait=value
48 46
49 47 Where `value` will be resolved in the user's namespace, if it is an
50 48 expression or variable name.
51 49
52 50 Examples
53 51 --------
54 52
55 53 To see what classes are available for config, pass no arguments::
56 54
57 55 In [1]: %config
58 56 Available objects for config:
59 57 TerminalInteractiveShell
60 58 HistoryManager
61 59 PrefilterManager
62 60 AliasManager
63 61 IPCompleter
64 62 DisplayFormatter
65 63
66 64 To view what is configurable on a given class, just pass the class
67 65 name::
68 66
69 67 In [2]: %config IPCompleter
70 68 IPCompleter options
71 69 -----------------
72 70 IPCompleter.omit__names=<Enum>
73 71 Current: 2
74 72 Choices: (0, 1, 2)
75 73 Instruct the completer to omit private method names
76 74 Specifically, when completing on ``object.<tab>``.
77 75 When 2 [default]: all names that start with '_' will be excluded.
78 76 When 1: all 'magic' names (``__foo__``) will be excluded.
79 77 When 0: nothing will be excluded.
80 78 IPCompleter.merge_completions=<CBool>
81 79 Current: True
82 80 Whether to merge completion results into a single list
83 81 If False, only the completion results from the first non-empty
84 82 completer will be returned.
85 83 IPCompleter.limit_to__all__=<CBool>
86 84 Current: False
87 85 Instruct the completer to use __all__ for the completion
88 86 Specifically, when completing on ``object.<tab>``.
89 87 When True: only those names in obj.__all__ will be included.
90 88 When False [default]: the __all__ attribute is ignored
91 89 IPCompleter.greedy=<CBool>
92 90 Current: False
93 91 Activate greedy completion
94 92 This will enable completion on elements of lists, results of
95 93 function calls, etc., but can be unsafe because the code is
96 94 actually evaluated on TAB.
97 95
98 96 but the real use is in setting values::
99 97
100 98 In [3]: %config IPCompleter.greedy = True
101 99
102 100 and these values are read from the user_ns if they are variables::
103 101
104 102 In [4]: feeling_greedy=False
105 103
106 104 In [5]: %config IPCompleter.greedy = feeling_greedy
107 105
108 106 """
109 107 from traitlets.config.loader import Config
110 108 # some IPython objects are Configurable, but do not yet have
111 109 # any configurable traits. Exclude them from the effects of
112 110 # this magic, as their presence is just noise:
113 111 configurables = [ c for c in self.shell.configurables
114 112 if c.__class__.class_traits(config=True) ]
115 113 classnames = [ c.__class__.__name__ for c in configurables ]
116 114
117 115 line = s.strip()
118 116 if not line:
119 117 # print available configurable names
120 118 print("Available objects for config:")
121 119 for name in classnames:
122 120 print(" ", name)
123 121 return
124 122 elif line in classnames:
125 123 # `%config TerminalInteractiveShell` will print trait info for
126 124 # TerminalInteractiveShell
127 125 c = configurables[classnames.index(line)]
128 126 cls = c.__class__
129 127 help = cls.class_get_help(c)
130 128 # strip leading '--' from cl-args:
131 129 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
132 130 print(help)
133 131 return
134 132 elif reg.match(line):
135 133 cls, attr = line.split('.')
136 134 return getattr(configurables[classnames.index(cls)],attr)
137 135 elif '=' not in line:
138 136 msg = "Invalid config statement: %r, "\
139 137 "should be `Class.trait = value`."
140 138
141 139 ll = line.lower()
142 140 for classname in classnames:
143 141 if ll == classname.lower():
144 142 msg = msg + '\nDid you mean %s (note the case)?' % classname
145 143 break
146 144
147 145 raise UsageError( msg % line)
148 146
149 147 # otherwise, assume we are setting configurables.
150 148 # leave quotes on args when splitting, because we want
151 149 # unquoted args to eval in user_ns
152 150 cfg = Config()
153 151 exec("cfg."+line, locals(), self.shell.user_ns)
154 152
155 153 for configurable in configurables:
156 154 try:
157 155 configurable.update_config(cfg)
158 156 except Exception as e:
159 157 error(e)
@@ -1,1370 +1,1368 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Implementation of execution-related magic functions."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 from __future__ import print_function
8 from __future__ import absolute_import
9 7
10 8 import ast
11 9 import bdb
12 10 import gc
13 11 import itertools
14 12 import os
15 13 import sys
16 14 import time
17 15 import timeit
18 16 import math
19 17 from pdb import Restart
20 18
21 19 # cProfile was added in Python2.5
22 20 try:
23 21 import cProfile as profile
24 22 import pstats
25 23 except ImportError:
26 24 # profile isn't bundled by default in Debian for license reasons
27 25 try:
28 26 import profile, pstats
29 27 except ImportError:
30 28 profile = pstats = None
31 29
32 30 from IPython.core import oinspect
33 31 from IPython.core import magic_arguments
34 32 from IPython.core import page
35 33 from IPython.core.error import UsageError
36 34 from IPython.core.macro import Macro
37 35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
38 36 line_cell_magic, on_off, needs_local_scope)
39 37 from IPython.testing.skipdoctest import skip_doctest
40 38 from IPython.utils import py3compat
41 39 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
42 40 from IPython.utils.contexts import preserve_keys
43 41 from IPython.utils.capture import capture_output
44 42 from IPython.utils.ipstruct import Struct
45 43 from IPython.utils.module_paths import find_mod
46 44 from IPython.utils.path import get_py_filename, shellglob
47 45 from IPython.utils.timing import clock, clock2
48 46 from warnings import warn
49 47 from logging import error
50 48
51 49 if PY3:
52 50 from io import StringIO
53 51 else:
54 52 from StringIO import StringIO
55 53
56 54 #-----------------------------------------------------------------------------
57 55 # Magic implementation classes
58 56 #-----------------------------------------------------------------------------
59 57
60 58
61 59 class TimeitResult(object):
62 60 """
63 61 Object returned by the timeit magic with info about the run.
64 62
65 63 Contains the following attributes :
66 64
67 65 loops: (int) number of loops done per measurement
68 66 repeat: (int) number of times the measurement has been repeated
69 67 best: (float) best execution time / number
70 68 all_runs: (list of float) execution time of each run (in s)
71 69 compile_time: (float) time of statement compilation (s)
72 70
73 71 """
74 72 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
75 73 self.loops = loops
76 74 self.repeat = repeat
77 75 self.best = best
78 76 self.worst = worst
79 77 self.all_runs = all_runs
80 78 self.compile_time = compile_time
81 79 self._precision = precision
82 80 self.timings = [ dt / self.loops for dt in all_runs]
83 81
84 82 @property
85 83 def average(self):
86 84 return math.fsum(self.timings) / len(self.timings)
87 85
88 86 @property
89 87 def stdev(self):
90 88 mean = self.average
91 89 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
92 90
93 91 def __str__(self):
94 92 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
95 93 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
96 94 _format_time(self.average, self._precision),
97 95 _format_time(self.stdev, self._precision)))
98 96
99 97 def _repr_pretty_(self, p , cycle):
100 98 unic = self.__str__()
101 99 p.text(u'<TimeitResult : '+unic+u'>')
102 100
103 101
104 102
105 103 class TimeitTemplateFiller(ast.NodeTransformer):
106 104 """Fill in the AST template for timing execution.
107 105
108 106 This is quite closely tied to the template definition, which is in
109 107 :meth:`ExecutionMagics.timeit`.
110 108 """
111 109 def __init__(self, ast_setup, ast_stmt):
112 110 self.ast_setup = ast_setup
113 111 self.ast_stmt = ast_stmt
114 112
115 113 def visit_FunctionDef(self, node):
116 114 "Fill in the setup statement"
117 115 self.generic_visit(node)
118 116 if node.name == "inner":
119 117 node.body[:1] = self.ast_setup.body
120 118
121 119 return node
122 120
123 121 def visit_For(self, node):
124 122 "Fill in the statement to be timed"
125 123 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
126 124 node.body = self.ast_stmt.body
127 125 return node
128 126
129 127
130 128 class Timer(timeit.Timer):
131 129 """Timer class that explicitly uses self.inner
132 130
133 131 which is an undocumented implementation detail of CPython,
134 132 not shared by PyPy.
135 133 """
136 134 # Timer.timeit copied from CPython 3.4.2
137 135 def timeit(self, number=timeit.default_number):
138 136 """Time 'number' executions of the main statement.
139 137
140 138 To be precise, this executes the setup statement once, and
141 139 then returns the time it takes to execute the main statement
142 140 a number of times, as a float measured in seconds. The
143 141 argument is the number of times through the loop, defaulting
144 142 to one million. The main statement, the setup statement and
145 143 the timer function to be used are passed to the constructor.
146 144 """
147 145 it = itertools.repeat(None, number)
148 146 gcold = gc.isenabled()
149 147 gc.disable()
150 148 try:
151 149 timing = self.inner(it, self.timer)
152 150 finally:
153 151 if gcold:
154 152 gc.enable()
155 153 return timing
156 154
157 155
158 156 @magics_class
159 157 class ExecutionMagics(Magics):
160 158 """Magics related to code execution, debugging, profiling, etc.
161 159
162 160 """
163 161
164 162 def __init__(self, shell):
165 163 super(ExecutionMagics, self).__init__(shell)
166 164 if profile is None:
167 165 self.prun = self.profile_missing_notice
168 166 # Default execution function used to actually run user code.
169 167 self.default_runner = None
170 168
171 169 def profile_missing_notice(self, *args, **kwargs):
172 170 error("""\
173 171 The profile module could not be found. It has been removed from the standard
174 172 python packages because of its non-free license. To use profiling, install the
175 173 python-profiler package from non-free.""")
176 174
177 175 @skip_doctest
178 176 @line_cell_magic
179 177 def prun(self, parameter_s='', cell=None):
180 178
181 179 """Run a statement through the python code profiler.
182 180
183 181 Usage, in line mode:
184 182 %prun [options] statement
185 183
186 184 Usage, in cell mode:
187 185 %%prun [options] [statement]
188 186 code...
189 187 code...
190 188
191 189 In cell mode, the additional code lines are appended to the (possibly
192 190 empty) statement in the first line. Cell mode allows you to easily
193 191 profile multiline blocks without having to put them in a separate
194 192 function.
195 193
196 194 The given statement (which doesn't require quote marks) is run via the
197 195 python profiler in a manner similar to the profile.run() function.
198 196 Namespaces are internally managed to work correctly; profile.run
199 197 cannot be used in IPython because it makes certain assumptions about
200 198 namespaces which do not hold under IPython.
201 199
202 200 Options:
203 201
204 202 -l <limit>
205 203 you can place restrictions on what or how much of the
206 204 profile gets printed. The limit value can be:
207 205
208 206 * A string: only information for function names containing this string
209 207 is printed.
210 208
211 209 * An integer: only these many lines are printed.
212 210
213 211 * A float (between 0 and 1): this fraction of the report is printed
214 212 (for example, use a limit of 0.4 to see the topmost 40% only).
215 213
216 214 You can combine several limits with repeated use of the option. For
217 215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
218 216 information about class constructors.
219 217
220 218 -r
221 219 return the pstats.Stats object generated by the profiling. This
222 220 object has all the information about the profile in it, and you can
223 221 later use it for further analysis or in other functions.
224 222
225 223 -s <key>
226 224 sort profile by given key. You can provide more than one key
227 225 by using the option several times: '-s key1 -s key2 -s key3...'. The
228 226 default sorting key is 'time'.
229 227
230 228 The following is copied verbatim from the profile documentation
231 229 referenced below:
232 230
233 231 When more than one key is provided, additional keys are used as
234 232 secondary criteria when the there is equality in all keys selected
235 233 before them.
236 234
237 235 Abbreviations can be used for any key names, as long as the
238 236 abbreviation is unambiguous. The following are the keys currently
239 237 defined:
240 238
241 239 ============ =====================
242 240 Valid Arg Meaning
243 241 ============ =====================
244 242 "calls" call count
245 243 "cumulative" cumulative time
246 244 "file" file name
247 245 "module" file name
248 246 "pcalls" primitive call count
249 247 "line" line number
250 248 "name" function name
251 249 "nfl" name/file/line
252 250 "stdname" standard name
253 251 "time" internal time
254 252 ============ =====================
255 253
256 254 Note that all sorts on statistics are in descending order (placing
257 255 most time consuming items first), where as name, file, and line number
258 256 searches are in ascending order (i.e., alphabetical). The subtle
259 257 distinction between "nfl" and "stdname" is that the standard name is a
260 258 sort of the name as printed, which means that the embedded line
261 259 numbers get compared in an odd way. For example, lines 3, 20, and 40
262 260 would (if the file names were the same) appear in the string order
263 261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
264 262 line numbers. In fact, sort_stats("nfl") is the same as
265 263 sort_stats("name", "file", "line").
266 264
267 265 -T <filename>
268 266 save profile results as shown on screen to a text
269 267 file. The profile is still shown on screen.
270 268
271 269 -D <filename>
272 270 save (via dump_stats) profile statistics to given
273 271 filename. This data is in a format understood by the pstats module, and
274 272 is generated by a call to the dump_stats() method of profile
275 273 objects. The profile is still shown on screen.
276 274
277 275 -q
278 276 suppress output to the pager. Best used with -T and/or -D above.
279 277
280 278 If you want to run complete programs under the profiler's control, use
281 279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
282 280 contains profiler specific options as described here.
283 281
284 282 You can read the complete documentation for the profile module with::
285 283
286 284 In [1]: import profile; profile.help()
287 285 """
288 286 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
289 287 list_all=True, posix=False)
290 288 if cell is not None:
291 289 arg_str += '\n' + cell
292 290 arg_str = self.shell.input_splitter.transform_cell(arg_str)
293 291 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
294 292
295 293 def _run_with_profiler(self, code, opts, namespace):
296 294 """
297 295 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
298 296
299 297 Parameters
300 298 ----------
301 299 code : str
302 300 Code to be executed.
303 301 opts : Struct
304 302 Options parsed by `self.parse_options`.
305 303 namespace : dict
306 304 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
307 305
308 306 """
309 307
310 308 # Fill default values for unspecified options:
311 309 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
312 310
313 311 prof = profile.Profile()
314 312 try:
315 313 prof = prof.runctx(code, namespace, namespace)
316 314 sys_exit = ''
317 315 except SystemExit:
318 316 sys_exit = """*** SystemExit exception caught in code being profiled."""
319 317
320 318 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
321 319
322 320 lims = opts.l
323 321 if lims:
324 322 lims = [] # rebuild lims with ints/floats/strings
325 323 for lim in opts.l:
326 324 try:
327 325 lims.append(int(lim))
328 326 except ValueError:
329 327 try:
330 328 lims.append(float(lim))
331 329 except ValueError:
332 330 lims.append(lim)
333 331
334 332 # Trap output.
335 333 stdout_trap = StringIO()
336 334 stats_stream = stats.stream
337 335 try:
338 336 stats.stream = stdout_trap
339 337 stats.print_stats(*lims)
340 338 finally:
341 339 stats.stream = stats_stream
342 340
343 341 output = stdout_trap.getvalue()
344 342 output = output.rstrip()
345 343
346 344 if 'q' not in opts:
347 345 page.page(output)
348 346 print(sys_exit, end=' ')
349 347
350 348 dump_file = opts.D[0]
351 349 text_file = opts.T[0]
352 350 if dump_file:
353 351 prof.dump_stats(dump_file)
354 352 print('\n*** Profile stats marshalled to file',\
355 353 repr(dump_file)+'.',sys_exit)
356 354 if text_file:
357 355 pfile = open(text_file,'w')
358 356 pfile.write(output)
359 357 pfile.close()
360 358 print('\n*** Profile printout saved to text file',\
361 359 repr(text_file)+'.',sys_exit)
362 360
363 361 if 'r' in opts:
364 362 return stats
365 363 else:
366 364 return None
367 365
368 366 @line_magic
369 367 def pdb(self, parameter_s=''):
370 368 """Control the automatic calling of the pdb interactive debugger.
371 369
372 370 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
373 371 argument it works as a toggle.
374 372
375 373 When an exception is triggered, IPython can optionally call the
376 374 interactive pdb debugger after the traceback printout. %pdb toggles
377 375 this feature on and off.
378 376
379 377 The initial state of this feature is set in your configuration
380 378 file (the option is ``InteractiveShell.pdb``).
381 379
382 380 If you want to just activate the debugger AFTER an exception has fired,
383 381 without having to type '%pdb on' and rerunning your code, you can use
384 382 the %debug magic."""
385 383
386 384 par = parameter_s.strip().lower()
387 385
388 386 if par:
389 387 try:
390 388 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
391 389 except KeyError:
392 390 print ('Incorrect argument. Use on/1, off/0, '
393 391 'or nothing for a toggle.')
394 392 return
395 393 else:
396 394 # toggle
397 395 new_pdb = not self.shell.call_pdb
398 396
399 397 # set on the shell
400 398 self.shell.call_pdb = new_pdb
401 399 print('Automatic pdb calling has been turned',on_off(new_pdb))
402 400
403 401 @skip_doctest
404 402 @magic_arguments.magic_arguments()
405 403 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
406 404 help="""
407 405 Set break point at LINE in FILE.
408 406 """
409 407 )
410 408 @magic_arguments.argument('statement', nargs='*',
411 409 help="""
412 410 Code to run in debugger.
413 411 You can omit this in cell magic mode.
414 412 """
415 413 )
416 414 @line_cell_magic
417 415 def debug(self, line='', cell=None):
418 416 """Activate the interactive debugger.
419 417
420 418 This magic command support two ways of activating debugger.
421 419 One is to activate debugger before executing code. This way, you
422 420 can set a break point, to step through the code from the point.
423 421 You can use this mode by giving statements to execute and optionally
424 422 a breakpoint.
425 423
426 424 The other one is to activate debugger in post-mortem mode. You can
427 425 activate this mode simply running %debug without any argument.
428 426 If an exception has just occurred, this lets you inspect its stack
429 427 frames interactively. Note that this will always work only on the last
430 428 traceback that occurred, so you must call this quickly after an
431 429 exception that you wish to inspect has fired, because if another one
432 430 occurs, it clobbers the previous one.
433 431
434 432 If you want IPython to automatically do this on every exception, see
435 433 the %pdb magic for more details.
436 434 """
437 435 args = magic_arguments.parse_argstring(self.debug, line)
438 436
439 437 if not (args.breakpoint or args.statement or cell):
440 438 self._debug_post_mortem()
441 439 else:
442 440 code = "\n".join(args.statement)
443 441 if cell:
444 442 code += "\n" + cell
445 443 self._debug_exec(code, args.breakpoint)
446 444
447 445 def _debug_post_mortem(self):
448 446 self.shell.debugger(force=True)
449 447
450 448 def _debug_exec(self, code, breakpoint):
451 449 if breakpoint:
452 450 (filename, bp_line) = breakpoint.rsplit(':', 1)
453 451 bp_line = int(bp_line)
454 452 else:
455 453 (filename, bp_line) = (None, None)
456 454 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
457 455
458 456 @line_magic
459 457 def tb(self, s):
460 458 """Print the last traceback with the currently active exception mode.
461 459
462 460 See %xmode for changing exception reporting modes."""
463 461 self.shell.showtraceback()
464 462
465 463 @skip_doctest
466 464 @line_magic
467 465 def run(self, parameter_s='', runner=None,
468 466 file_finder=get_py_filename):
469 467 """Run the named file inside IPython as a program.
470 468
471 469 Usage::
472 470
473 471 %run [-n -i -e -G]
474 472 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
475 473 ( -m mod | file ) [args]
476 474
477 475 Parameters after the filename are passed as command-line arguments to
478 476 the program (put in sys.argv). Then, control returns to IPython's
479 477 prompt.
480 478
481 479 This is similar to running at a system prompt ``python file args``,
482 480 but with the advantage of giving you IPython's tracebacks, and of
483 481 loading all variables into your interactive namespace for further use
484 482 (unless -p is used, see below).
485 483
486 484 The file is executed in a namespace initially consisting only of
487 485 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
488 486 sees its environment as if it were being run as a stand-alone program
489 487 (except for sharing global objects such as previously imported
490 488 modules). But after execution, the IPython interactive namespace gets
491 489 updated with all variables defined in the program (except for __name__
492 490 and sys.argv). This allows for very convenient loading of code for
493 491 interactive work, while giving each program a 'clean sheet' to run in.
494 492
495 493 Arguments are expanded using shell-like glob match. Patterns
496 494 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
497 495 tilde '~' will be expanded into user's home directory. Unlike
498 496 real shells, quotation does not suppress expansions. Use
499 497 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
500 498 To completely disable these expansions, you can use -G flag.
501 499
502 500 Options:
503 501
504 502 -n
505 503 __name__ is NOT set to '__main__', but to the running file's name
506 504 without extension (as python does under import). This allows running
507 505 scripts and reloading the definitions in them without calling code
508 506 protected by an ``if __name__ == "__main__"`` clause.
509 507
510 508 -i
511 509 run the file in IPython's namespace instead of an empty one. This
512 510 is useful if you are experimenting with code written in a text editor
513 511 which depends on variables defined interactively.
514 512
515 513 -e
516 514 ignore sys.exit() calls or SystemExit exceptions in the script
517 515 being run. This is particularly useful if IPython is being used to
518 516 run unittests, which always exit with a sys.exit() call. In such
519 517 cases you are interested in the output of the test results, not in
520 518 seeing a traceback of the unittest module.
521 519
522 520 -t
523 521 print timing information at the end of the run. IPython will give
524 522 you an estimated CPU time consumption for your script, which under
525 523 Unix uses the resource module to avoid the wraparound problems of
526 524 time.clock(). Under Unix, an estimate of time spent on system tasks
527 525 is also given (for Windows platforms this is reported as 0.0).
528 526
529 527 If -t is given, an additional ``-N<N>`` option can be given, where <N>
530 528 must be an integer indicating how many times you want the script to
531 529 run. The final timing report will include total and per run results.
532 530
533 531 For example (testing the script uniq_stable.py)::
534 532
535 533 In [1]: run -t uniq_stable
536 534
537 535 IPython CPU timings (estimated):
538 536 User : 0.19597 s.
539 537 System: 0.0 s.
540 538
541 539 In [2]: run -t -N5 uniq_stable
542 540
543 541 IPython CPU timings (estimated):
544 542 Total runs performed: 5
545 543 Times : Total Per run
546 544 User : 0.910862 s, 0.1821724 s.
547 545 System: 0.0 s, 0.0 s.
548 546
549 547 -d
550 548 run your program under the control of pdb, the Python debugger.
551 549 This allows you to execute your program step by step, watch variables,
552 550 etc. Internally, what IPython does is similar to calling::
553 551
554 552 pdb.run('execfile("YOURFILENAME")')
555 553
556 554 with a breakpoint set on line 1 of your file. You can change the line
557 555 number for this automatic breakpoint to be <N> by using the -bN option
558 556 (where N must be an integer). For example::
559 557
560 558 %run -d -b40 myscript
561 559
562 560 will set the first breakpoint at line 40 in myscript.py. Note that
563 561 the first breakpoint must be set on a line which actually does
564 562 something (not a comment or docstring) for it to stop execution.
565 563
566 564 Or you can specify a breakpoint in a different file::
567 565
568 566 %run -d -b myotherfile.py:20 myscript
569 567
570 568 When the pdb debugger starts, you will see a (Pdb) prompt. You must
571 569 first enter 'c' (without quotes) to start execution up to the first
572 570 breakpoint.
573 571
574 572 Entering 'help' gives information about the use of the debugger. You
575 573 can easily see pdb's full documentation with "import pdb;pdb.help()"
576 574 at a prompt.
577 575
578 576 -p
579 577 run program under the control of the Python profiler module (which
580 578 prints a detailed report of execution times, function calls, etc).
581 579
582 580 You can pass other options after -p which affect the behavior of the
583 581 profiler itself. See the docs for %prun for details.
584 582
585 583 In this mode, the program's variables do NOT propagate back to the
586 584 IPython interactive namespace (because they remain in the namespace
587 585 where the profiler executes them).
588 586
589 587 Internally this triggers a call to %prun, see its documentation for
590 588 details on the options available specifically for profiling.
591 589
592 590 There is one special usage for which the text above doesn't apply:
593 591 if the filename ends with .ipy[nb], the file is run as ipython script,
594 592 just as if the commands were written on IPython prompt.
595 593
596 594 -m
597 595 specify module name to load instead of script path. Similar to
598 596 the -m option for the python interpreter. Use this option last if you
599 597 want to combine with other %run options. Unlike the python interpreter
600 598 only source modules are allowed no .pyc or .pyo files.
601 599 For example::
602 600
603 601 %run -m example
604 602
605 603 will run the example module.
606 604
607 605 -G
608 606 disable shell-like glob expansion of arguments.
609 607
610 608 """
611 609
612 610 # get arguments and set sys.argv for program to be run.
613 611 opts, arg_lst = self.parse_options(parameter_s,
614 612 'nidtN:b:pD:l:rs:T:em:G',
615 613 mode='list', list_all=1)
616 614 if "m" in opts:
617 615 modulename = opts["m"][0]
618 616 modpath = find_mod(modulename)
619 617 if modpath is None:
620 618 warn('%r is not a valid modulename on sys.path'%modulename)
621 619 return
622 620 arg_lst = [modpath] + arg_lst
623 621 try:
624 622 filename = file_finder(arg_lst[0])
625 623 except IndexError:
626 624 warn('you must provide at least a filename.')
627 625 print('\n%run:\n', oinspect.getdoc(self.run))
628 626 return
629 627 except IOError as e:
630 628 try:
631 629 msg = str(e)
632 630 except UnicodeError:
633 631 msg = e.message
634 632 error(msg)
635 633 return
636 634
637 635 if filename.lower().endswith(('.ipy', '.ipynb')):
638 636 with preserve_keys(self.shell.user_ns, '__file__'):
639 637 self.shell.user_ns['__file__'] = filename
640 638 self.shell.safe_execfile_ipy(filename)
641 639 return
642 640
643 641 # Control the response to exit() calls made by the script being run
644 642 exit_ignore = 'e' in opts
645 643
646 644 # Make sure that the running script gets a proper sys.argv as if it
647 645 # were run from a system shell.
648 646 save_argv = sys.argv # save it for later restoring
649 647
650 648 if 'G' in opts:
651 649 args = arg_lst[1:]
652 650 else:
653 651 # tilde and glob expansion
654 652 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
655 653
656 654 sys.argv = [filename] + args # put in the proper filename
657 655 # protect sys.argv from potential unicode strings on Python 2:
658 656 if not py3compat.PY3:
659 657 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
660 658
661 659 if 'i' in opts:
662 660 # Run in user's interactive namespace
663 661 prog_ns = self.shell.user_ns
664 662 __name__save = self.shell.user_ns['__name__']
665 663 prog_ns['__name__'] = '__main__'
666 664 main_mod = self.shell.user_module
667 665
668 666 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
669 667 # set the __file__ global in the script's namespace
670 668 # TK: Is this necessary in interactive mode?
671 669 prog_ns['__file__'] = filename
672 670 else:
673 671 # Run in a fresh, empty namespace
674 672 if 'n' in opts:
675 673 name = os.path.splitext(os.path.basename(filename))[0]
676 674 else:
677 675 name = '__main__'
678 676
679 677 # The shell MUST hold a reference to prog_ns so after %run
680 678 # exits, the python deletion mechanism doesn't zero it out
681 679 # (leaving dangling references). See interactiveshell for details
682 680 main_mod = self.shell.new_main_mod(filename, name)
683 681 prog_ns = main_mod.__dict__
684 682
685 683 # pickle fix. See interactiveshell for an explanation. But we need to
686 684 # make sure that, if we overwrite __main__, we replace it at the end
687 685 main_mod_name = prog_ns['__name__']
688 686
689 687 if main_mod_name == '__main__':
690 688 restore_main = sys.modules['__main__']
691 689 else:
692 690 restore_main = False
693 691
694 692 # This needs to be undone at the end to prevent holding references to
695 693 # every single object ever created.
696 694 sys.modules[main_mod_name] = main_mod
697 695
698 696 if 'p' in opts or 'd' in opts:
699 697 if 'm' in opts:
700 698 code = 'run_module(modulename, prog_ns)'
701 699 code_ns = {
702 700 'run_module': self.shell.safe_run_module,
703 701 'prog_ns': prog_ns,
704 702 'modulename': modulename,
705 703 }
706 704 else:
707 705 if 'd' in opts:
708 706 # allow exceptions to raise in debug mode
709 707 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
710 708 else:
711 709 code = 'execfile(filename, prog_ns)'
712 710 code_ns = {
713 711 'execfile': self.shell.safe_execfile,
714 712 'prog_ns': prog_ns,
715 713 'filename': get_py_filename(filename),
716 714 }
717 715
718 716 try:
719 717 stats = None
720 718 if 'p' in opts:
721 719 stats = self._run_with_profiler(code, opts, code_ns)
722 720 else:
723 721 if 'd' in opts:
724 722 bp_file, bp_line = parse_breakpoint(
725 723 opts.get('b', ['1'])[0], filename)
726 724 self._run_with_debugger(
727 725 code, code_ns, filename, bp_line, bp_file)
728 726 else:
729 727 if 'm' in opts:
730 728 def run():
731 729 self.shell.safe_run_module(modulename, prog_ns)
732 730 else:
733 731 if runner is None:
734 732 runner = self.default_runner
735 733 if runner is None:
736 734 runner = self.shell.safe_execfile
737 735
738 736 def run():
739 737 runner(filename, prog_ns, prog_ns,
740 738 exit_ignore=exit_ignore)
741 739
742 740 if 't' in opts:
743 741 # timed execution
744 742 try:
745 743 nruns = int(opts['N'][0])
746 744 if nruns < 1:
747 745 error('Number of runs must be >=1')
748 746 return
749 747 except (KeyError):
750 748 nruns = 1
751 749 self._run_with_timing(run, nruns)
752 750 else:
753 751 # regular execution
754 752 run()
755 753
756 754 if 'i' in opts:
757 755 self.shell.user_ns['__name__'] = __name__save
758 756 else:
759 757 # update IPython interactive namespace
760 758
761 759 # Some forms of read errors on the file may mean the
762 760 # __name__ key was never set; using pop we don't have to
763 761 # worry about a possible KeyError.
764 762 prog_ns.pop('__name__', None)
765 763
766 764 with preserve_keys(self.shell.user_ns, '__file__'):
767 765 self.shell.user_ns.update(prog_ns)
768 766 finally:
769 767 # It's a bit of a mystery why, but __builtins__ can change from
770 768 # being a module to becoming a dict missing some key data after
771 769 # %run. As best I can see, this is NOT something IPython is doing
772 770 # at all, and similar problems have been reported before:
773 771 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
774 772 # Since this seems to be done by the interpreter itself, the best
775 773 # we can do is to at least restore __builtins__ for the user on
776 774 # exit.
777 775 self.shell.user_ns['__builtins__'] = builtin_mod
778 776
779 777 # Ensure key global structures are restored
780 778 sys.argv = save_argv
781 779 if restore_main:
782 780 sys.modules['__main__'] = restore_main
783 781 else:
784 782 # Remove from sys.modules the reference to main_mod we'd
785 783 # added. Otherwise it will trap references to objects
786 784 # contained therein.
787 785 del sys.modules[main_mod_name]
788 786
789 787 return stats
790 788
791 789 def _run_with_debugger(self, code, code_ns, filename=None,
792 790 bp_line=None, bp_file=None):
793 791 """
794 792 Run `code` in debugger with a break point.
795 793
796 794 Parameters
797 795 ----------
798 796 code : str
799 797 Code to execute.
800 798 code_ns : dict
801 799 A namespace in which `code` is executed.
802 800 filename : str
803 801 `code` is ran as if it is in `filename`.
804 802 bp_line : int, optional
805 803 Line number of the break point.
806 804 bp_file : str, optional
807 805 Path to the file in which break point is specified.
808 806 `filename` is used if not given.
809 807
810 808 Raises
811 809 ------
812 810 UsageError
813 811 If the break point given by `bp_line` is not valid.
814 812
815 813 """
816 814 deb = self.shell.InteractiveTB.pdb
817 815 if not deb:
818 816 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
819 817 deb = self.shell.InteractiveTB.pdb
820 818
821 819 # reset Breakpoint state, which is moronically kept
822 820 # in a class
823 821 bdb.Breakpoint.next = 1
824 822 bdb.Breakpoint.bplist = {}
825 823 bdb.Breakpoint.bpbynumber = [None]
826 824 if bp_line is not None:
827 825 # Set an initial breakpoint to stop execution
828 826 maxtries = 10
829 827 bp_file = bp_file or filename
830 828 checkline = deb.checkline(bp_file, bp_line)
831 829 if not checkline:
832 830 for bp in range(bp_line + 1, bp_line + maxtries + 1):
833 831 if deb.checkline(bp_file, bp):
834 832 break
835 833 else:
836 834 msg = ("\nI failed to find a valid line to set "
837 835 "a breakpoint\n"
838 836 "after trying up to line: %s.\n"
839 837 "Please set a valid breakpoint manually "
840 838 "with the -b option." % bp)
841 839 raise UsageError(msg)
842 840 # if we find a good linenumber, set the breakpoint
843 841 deb.do_break('%s:%s' % (bp_file, bp_line))
844 842
845 843 if filename:
846 844 # Mimic Pdb._runscript(...)
847 845 deb._wait_for_mainpyfile = True
848 846 deb.mainpyfile = deb.canonic(filename)
849 847
850 848 # Start file run
851 849 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
852 850 try:
853 851 if filename:
854 852 # save filename so it can be used by methods on the deb object
855 853 deb._exec_filename = filename
856 854 while True:
857 855 try:
858 856 deb.run(code, code_ns)
859 857 except Restart:
860 858 print("Restarting")
861 859 if filename:
862 860 deb._wait_for_mainpyfile = True
863 861 deb.mainpyfile = deb.canonic(filename)
864 862 continue
865 863 else:
866 864 break
867 865
868 866
869 867 except:
870 868 etype, value, tb = sys.exc_info()
871 869 # Skip three frames in the traceback: the %run one,
872 870 # one inside bdb.py, and the command-line typed by the
873 871 # user (run by exec in pdb itself).
874 872 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
875 873
876 874 @staticmethod
877 875 def _run_with_timing(run, nruns):
878 876 """
879 877 Run function `run` and print timing information.
880 878
881 879 Parameters
882 880 ----------
883 881 run : callable
884 882 Any callable object which takes no argument.
885 883 nruns : int
886 884 Number of times to execute `run`.
887 885
888 886 """
889 887 twall0 = time.time()
890 888 if nruns == 1:
891 889 t0 = clock2()
892 890 run()
893 891 t1 = clock2()
894 892 t_usr = t1[0] - t0[0]
895 893 t_sys = t1[1] - t0[1]
896 894 print("\nIPython CPU timings (estimated):")
897 895 print(" User : %10.2f s." % t_usr)
898 896 print(" System : %10.2f s." % t_sys)
899 897 else:
900 898 runs = range(nruns)
901 899 t0 = clock2()
902 900 for nr in runs:
903 901 run()
904 902 t1 = clock2()
905 903 t_usr = t1[0] - t0[0]
906 904 t_sys = t1[1] - t0[1]
907 905 print("\nIPython CPU timings (estimated):")
908 906 print("Total runs performed:", nruns)
909 907 print(" Times : %10s %10s" % ('Total', 'Per run'))
910 908 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
911 909 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
912 910 twall1 = time.time()
913 911 print("Wall time: %10.2f s." % (twall1 - twall0))
914 912
915 913 @skip_doctest
916 914 @line_cell_magic
917 915 def timeit(self, line='', cell=None):
918 916 """Time execution of a Python statement or expression
919 917
920 918 Usage, in line mode:
921 919 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
922 920 or in cell mode:
923 921 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
924 922 code
925 923 code...
926 924
927 925 Time execution of a Python statement or expression using the timeit
928 926 module. This function can be used both as a line and cell magic:
929 927
930 928 - In line mode you can time a single-line statement (though multiple
931 929 ones can be chained with using semicolons).
932 930
933 931 - In cell mode, the statement in the first line is used as setup code
934 932 (executed but not timed) and the body of the cell is timed. The cell
935 933 body has access to any variables created in the setup code.
936 934
937 935 Options:
938 936 -n<N>: execute the given statement <N> times in a loop. If this value
939 937 is not given, a fitting value is chosen.
940 938
941 939 -r<R>: repeat the loop iteration <R> times and take the best result.
942 940 Default: 3
943 941
944 942 -t: use time.time to measure the time, which is the default on Unix.
945 943 This function measures wall time.
946 944
947 945 -c: use time.clock to measure the time, which is the default on
948 946 Windows and measures wall time. On Unix, resource.getrusage is used
949 947 instead and returns the CPU user time.
950 948
951 949 -p<P>: use a precision of <P> digits to display the timing result.
952 950 Default: 3
953 951
954 952 -q: Quiet, do not print result.
955 953
956 954 -o: return a TimeitResult that can be stored in a variable to inspect
957 955 the result in more details.
958 956
959 957
960 958 Examples
961 959 --------
962 960 ::
963 961
964 962 In [1]: %timeit pass
965 963 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
966 964
967 965 In [2]: u = None
968 966
969 967 In [3]: %timeit u is None
970 968 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
971 969
972 970 In [4]: %timeit -r 4 u == None
973 971 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
974 972
975 973 In [5]: import time
976 974
977 975 In [6]: %timeit -n1 time.sleep(2)
978 976 1 loop, average of 7: 2 s +- 4.71 µs per loop (using standard deviation)
979 977
980 978
981 979 The times reported by %timeit will be slightly higher than those
982 980 reported by the timeit.py script when variables are accessed. This is
983 981 due to the fact that %timeit executes the statement in the namespace
984 982 of the shell, compared with timeit.py, which uses a single setup
985 983 statement to import function or create variables. Generally, the bias
986 984 does not matter as long as results from timeit.py are not mixed with
987 985 those from %timeit."""
988 986
989 987 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
990 988 posix=False, strict=False)
991 989 if stmt == "" and cell is None:
992 990 return
993 991
994 992 timefunc = timeit.default_timer
995 993 number = int(getattr(opts, "n", 0))
996 994 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
997 995 repeat = int(getattr(opts, "r", default_repeat))
998 996 precision = int(getattr(opts, "p", 3))
999 997 quiet = 'q' in opts
1000 998 return_result = 'o' in opts
1001 999 if hasattr(opts, "t"):
1002 1000 timefunc = time.time
1003 1001 if hasattr(opts, "c"):
1004 1002 timefunc = clock
1005 1003
1006 1004 timer = Timer(timer=timefunc)
1007 1005 # this code has tight coupling to the inner workings of timeit.Timer,
1008 1006 # but is there a better way to achieve that the code stmt has access
1009 1007 # to the shell namespace?
1010 1008 transform = self.shell.input_splitter.transform_cell
1011 1009
1012 1010 if cell is None:
1013 1011 # called as line magic
1014 1012 ast_setup = self.shell.compile.ast_parse("pass")
1015 1013 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1016 1014 else:
1017 1015 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1018 1016 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1019 1017
1020 1018 ast_setup = self.shell.transform_ast(ast_setup)
1021 1019 ast_stmt = self.shell.transform_ast(ast_stmt)
1022 1020
1023 1021 # This codestring is taken from timeit.template - we fill it in as an
1024 1022 # AST, so that we can apply our AST transformations to the user code
1025 1023 # without affecting the timing code.
1026 1024 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1027 1025 ' setup\n'
1028 1026 ' _t0 = _timer()\n'
1029 1027 ' for _i in _it:\n'
1030 1028 ' stmt\n'
1031 1029 ' _t1 = _timer()\n'
1032 1030 ' return _t1 - _t0\n')
1033 1031
1034 1032 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1035 1033 timeit_ast = ast.fix_missing_locations(timeit_ast)
1036 1034
1037 1035 # Track compilation time so it can be reported if too long
1038 1036 # Minimum time above which compilation time will be reported
1039 1037 tc_min = 0.1
1040 1038
1041 1039 t0 = clock()
1042 1040 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1043 1041 tc = clock()-t0
1044 1042
1045 1043 ns = {}
1046 1044 exec(code, self.shell.user_ns, ns)
1047 1045 timer.inner = ns["inner"]
1048 1046
1049 1047 # This is used to check if there is a huge difference between the
1050 1048 # best and worst timings.
1051 1049 # Issue: https://github.com/ipython/ipython/issues/6471
1052 1050 if number == 0:
1053 1051 # determine number so that 0.2 <= total time < 2.0
1054 1052 for index in range(0, 10):
1055 1053 number = 10 ** index
1056 1054 time_number = timer.timeit(number)
1057 1055 if time_number >= 0.2:
1058 1056 break
1059 1057
1060 1058 all_runs = timer.repeat(repeat, number)
1061 1059 best = min(all_runs) / number
1062 1060 worst = max(all_runs) / number
1063 1061 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1064 1062
1065 1063 if not quiet :
1066 1064 # Check best timing is greater than zero to avoid a
1067 1065 # ZeroDivisionError.
1068 1066 # In cases where the slowest timing is lesser than a micosecond
1069 1067 # we assume that it does not really matter if the fastest
1070 1068 # timing is 4 times faster than the slowest timing or not.
1071 1069 if worst > 4 * best and best > 0 and worst > 1e-6:
1072 1070 print("The slowest run took %0.2f times longer than the "
1073 1071 "fastest. This could mean that an intermediate result "
1074 1072 "is being cached." % (worst / best))
1075 1073
1076 1074 print( timeit_result )
1077 1075
1078 1076 if tc > tc_min:
1079 1077 print("Compiler time: %.2f s" % tc)
1080 1078 if return_result:
1081 1079 return timeit_result
1082 1080
1083 1081 @skip_doctest
1084 1082 @needs_local_scope
1085 1083 @line_cell_magic
1086 1084 def time(self,line='', cell=None, local_ns=None):
1087 1085 """Time execution of a Python statement or expression.
1088 1086
1089 1087 The CPU and wall clock times are printed, and the value of the
1090 1088 expression (if any) is returned. Note that under Win32, system time
1091 1089 is always reported as 0, since it can not be measured.
1092 1090
1093 1091 This function can be used both as a line and cell magic:
1094 1092
1095 1093 - In line mode you can time a single-line statement (though multiple
1096 1094 ones can be chained with using semicolons).
1097 1095
1098 1096 - In cell mode, you can time the cell body (a directly
1099 1097 following statement raises an error).
1100 1098
1101 1099 This function provides very basic timing functionality. Use the timeit
1102 1100 magic for more control over the measurement.
1103 1101
1104 1102 Examples
1105 1103 --------
1106 1104 ::
1107 1105
1108 1106 In [1]: %time 2**128
1109 1107 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1110 1108 Wall time: 0.00
1111 1109 Out[1]: 340282366920938463463374607431768211456L
1112 1110
1113 1111 In [2]: n = 1000000
1114 1112
1115 1113 In [3]: %time sum(range(n))
1116 1114 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1117 1115 Wall time: 1.37
1118 1116 Out[3]: 499999500000L
1119 1117
1120 1118 In [4]: %time print 'hello world'
1121 1119 hello world
1122 1120 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1123 1121 Wall time: 0.00
1124 1122
1125 1123 Note that the time needed by Python to compile the given expression
1126 1124 will be reported if it is more than 0.1s. In this example, the
1127 1125 actual exponentiation is done by Python at compilation time, so while
1128 1126 the expression can take a noticeable amount of time to compute, that
1129 1127 time is purely due to the compilation:
1130 1128
1131 1129 In [5]: %time 3**9999;
1132 1130 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1133 1131 Wall time: 0.00 s
1134 1132
1135 1133 In [6]: %time 3**999999;
1136 1134 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1137 1135 Wall time: 0.00 s
1138 1136 Compiler : 0.78 s
1139 1137 """
1140 1138
1141 1139 # fail immediately if the given expression can't be compiled
1142 1140
1143 1141 if line and cell:
1144 1142 raise UsageError("Can't use statement directly after '%%time'!")
1145 1143
1146 1144 if cell:
1147 1145 expr = self.shell.input_transformer_manager.transform_cell(cell)
1148 1146 else:
1149 1147 expr = self.shell.input_transformer_manager.transform_cell(line)
1150 1148
1151 1149 # Minimum time above which parse time will be reported
1152 1150 tp_min = 0.1
1153 1151
1154 1152 t0 = clock()
1155 1153 expr_ast = self.shell.compile.ast_parse(expr)
1156 1154 tp = clock()-t0
1157 1155
1158 1156 # Apply AST transformations
1159 1157 expr_ast = self.shell.transform_ast(expr_ast)
1160 1158
1161 1159 # Minimum time above which compilation time will be reported
1162 1160 tc_min = 0.1
1163 1161
1164 1162 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1165 1163 mode = 'eval'
1166 1164 source = '<timed eval>'
1167 1165 expr_ast = ast.Expression(expr_ast.body[0].value)
1168 1166 else:
1169 1167 mode = 'exec'
1170 1168 source = '<timed exec>'
1171 1169 t0 = clock()
1172 1170 code = self.shell.compile(expr_ast, source, mode)
1173 1171 tc = clock()-t0
1174 1172
1175 1173 # skew measurement as little as possible
1176 1174 glob = self.shell.user_ns
1177 1175 wtime = time.time
1178 1176 # time execution
1179 1177 wall_st = wtime()
1180 1178 if mode=='eval':
1181 1179 st = clock2()
1182 1180 out = eval(code, glob, local_ns)
1183 1181 end = clock2()
1184 1182 else:
1185 1183 st = clock2()
1186 1184 exec(code, glob, local_ns)
1187 1185 end = clock2()
1188 1186 out = None
1189 1187 wall_end = wtime()
1190 1188 # Compute actual times and report
1191 1189 wall_time = wall_end-wall_st
1192 1190 cpu_user = end[0]-st[0]
1193 1191 cpu_sys = end[1]-st[1]
1194 1192 cpu_tot = cpu_user+cpu_sys
1195 1193 # On windows cpu_sys is always zero, so no new information to the next print
1196 1194 if sys.platform != 'win32':
1197 1195 print("CPU times: user %s, sys: %s, total: %s" % \
1198 1196 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1199 1197 print("Wall time: %s" % _format_time(wall_time))
1200 1198 if tc > tc_min:
1201 1199 print("Compiler : %s" % _format_time(tc))
1202 1200 if tp > tp_min:
1203 1201 print("Parser : %s" % _format_time(tp))
1204 1202 return out
1205 1203
1206 1204 @skip_doctest
1207 1205 @line_magic
1208 1206 def macro(self, parameter_s=''):
1209 1207 """Define a macro for future re-execution. It accepts ranges of history,
1210 1208 filenames or string objects.
1211 1209
1212 1210 Usage:\\
1213 1211 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1214 1212
1215 1213 Options:
1216 1214
1217 1215 -r: use 'raw' input. By default, the 'processed' history is used,
1218 1216 so that magics are loaded in their transformed version to valid
1219 1217 Python. If this option is given, the raw input as typed at the
1220 1218 command line is used instead.
1221 1219
1222 1220 -q: quiet macro definition. By default, a tag line is printed
1223 1221 to indicate the macro has been created, and then the contents of
1224 1222 the macro are printed. If this option is given, then no printout
1225 1223 is produced once the macro is created.
1226 1224
1227 1225 This will define a global variable called `name` which is a string
1228 1226 made of joining the slices and lines you specify (n1,n2,... numbers
1229 1227 above) from your input history into a single string. This variable
1230 1228 acts like an automatic function which re-executes those lines as if
1231 1229 you had typed them. You just type 'name' at the prompt and the code
1232 1230 executes.
1233 1231
1234 1232 The syntax for indicating input ranges is described in %history.
1235 1233
1236 1234 Note: as a 'hidden' feature, you can also use traditional python slice
1237 1235 notation, where N:M means numbers N through M-1.
1238 1236
1239 1237 For example, if your history contains (print using %hist -n )::
1240 1238
1241 1239 44: x=1
1242 1240 45: y=3
1243 1241 46: z=x+y
1244 1242 47: print x
1245 1243 48: a=5
1246 1244 49: print 'x',x,'y',y
1247 1245
1248 1246 you can create a macro with lines 44 through 47 (included) and line 49
1249 1247 called my_macro with::
1250 1248
1251 1249 In [55]: %macro my_macro 44-47 49
1252 1250
1253 1251 Now, typing `my_macro` (without quotes) will re-execute all this code
1254 1252 in one pass.
1255 1253
1256 1254 You don't need to give the line-numbers in order, and any given line
1257 1255 number can appear multiple times. You can assemble macros with any
1258 1256 lines from your input history in any order.
1259 1257
1260 1258 The macro is a simple object which holds its value in an attribute,
1261 1259 but IPython's display system checks for macros and executes them as
1262 1260 code instead of printing them when you type their name.
1263 1261
1264 1262 You can view a macro's contents by explicitly printing it with::
1265 1263
1266 1264 print macro_name
1267 1265
1268 1266 """
1269 1267 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1270 1268 if not args: # List existing macros
1271 1269 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1272 1270 isinstance(v, Macro))
1273 1271 if len(args) == 1:
1274 1272 raise UsageError(
1275 1273 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1276 1274 name, codefrom = args[0], " ".join(args[1:])
1277 1275
1278 1276 #print 'rng',ranges # dbg
1279 1277 try:
1280 1278 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1281 1279 except (ValueError, TypeError) as e:
1282 1280 print(e.args[0])
1283 1281 return
1284 1282 macro = Macro(lines)
1285 1283 self.shell.define_macro(name, macro)
1286 1284 if not ( 'q' in opts) :
1287 1285 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1288 1286 print('=== Macro contents: ===')
1289 1287 print(macro, end=' ')
1290 1288
1291 1289 @magic_arguments.magic_arguments()
1292 1290 @magic_arguments.argument('output', type=str, default='', nargs='?',
1293 1291 help="""The name of the variable in which to store output.
1294 1292 This is a utils.io.CapturedIO object with stdout/err attributes
1295 1293 for the text of the captured output.
1296 1294
1297 1295 CapturedOutput also has a show() method for displaying the output,
1298 1296 and __call__ as well, so you can use that to quickly display the
1299 1297 output.
1300 1298
1301 1299 If unspecified, captured output is discarded.
1302 1300 """
1303 1301 )
1304 1302 @magic_arguments.argument('--no-stderr', action="store_true",
1305 1303 help="""Don't capture stderr."""
1306 1304 )
1307 1305 @magic_arguments.argument('--no-stdout', action="store_true",
1308 1306 help="""Don't capture stdout."""
1309 1307 )
1310 1308 @magic_arguments.argument('--no-display', action="store_true",
1311 1309 help="""Don't capture IPython's rich display."""
1312 1310 )
1313 1311 @cell_magic
1314 1312 def capture(self, line, cell):
1315 1313 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1316 1314 args = magic_arguments.parse_argstring(self.capture, line)
1317 1315 out = not args.no_stdout
1318 1316 err = not args.no_stderr
1319 1317 disp = not args.no_display
1320 1318 with capture_output(out, err, disp) as io:
1321 1319 self.shell.run_cell(cell)
1322 1320 if args.output:
1323 1321 self.shell.user_ns[args.output] = io
1324 1322
1325 1323 def parse_breakpoint(text, current_file):
1326 1324 '''Returns (file, line) for file:line and (current_file, line) for line'''
1327 1325 colon = text.find(':')
1328 1326 if colon == -1:
1329 1327 return current_file, int(text)
1330 1328 else:
1331 1329 return text[:colon], int(text[colon+1:])
1332 1330
1333 1331 def _format_time(timespan, precision=3):
1334 1332 """Formats the timespan in a human readable form"""
1335 1333
1336 1334 if timespan >= 60.0:
1337 1335 # we have more than a minute, format that in a human readable form
1338 1336 # Idea from http://snipplr.com/view/5713/
1339 1337 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1340 1338 time = []
1341 1339 leftover = timespan
1342 1340 for suffix, length in parts:
1343 1341 value = int(leftover / length)
1344 1342 if value > 0:
1345 1343 leftover = leftover % length
1346 1344 time.append(u'%s%s' % (str(value), suffix))
1347 1345 if leftover < 1:
1348 1346 break
1349 1347 return " ".join(time)
1350 1348
1351 1349
1352 1350 # Unfortunately the unicode 'micro' symbol can cause problems in
1353 1351 # certain terminals.
1354 1352 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1355 1353 # Try to prevent crashes by being more secure than it needs to
1356 1354 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1357 1355 units = [u"s", u"ms",u'us',"ns"] # the save value
1358 1356 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1359 1357 try:
1360 1358 u'\xb5'.encode(sys.stdout.encoding)
1361 1359 units = [u"s", u"ms",u'\xb5s',"ns"]
1362 1360 except:
1363 1361 pass
1364 1362 scaling = [1, 1e3, 1e6, 1e9]
1365 1363
1366 1364 if timespan > 0.0:
1367 1365 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1368 1366 else:
1369 1367 order = 3
1370 1368 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,67 +1,66 b''
1 1 """Implementation of magic functions for the extension machinery.
2 2 """
3 from __future__ import print_function
4 3 #-----------------------------------------------------------------------------
5 4 # Copyright (c) 2012 The IPython Development Team.
6 5 #
7 6 # Distributed under the terms of the Modified BSD License.
8 7 #
9 8 # The full license is in the file COPYING.txt, distributed with this software.
10 9 #-----------------------------------------------------------------------------
11 10
12 11 #-----------------------------------------------------------------------------
13 12 # Imports
14 13 #-----------------------------------------------------------------------------
15 14
16 15 # Stdlib
17 16 import os
18 17
19 18 # Our own packages
20 19 from IPython.core.error import UsageError
21 20 from IPython.core.magic import Magics, magics_class, line_magic
22 21 from warnings import warn
23 22
24 23 #-----------------------------------------------------------------------------
25 24 # Magic implementation classes
26 25 #-----------------------------------------------------------------------------
27 26
28 27 @magics_class
29 28 class ExtensionMagics(Magics):
30 29 """Magics to manage the IPython extensions system."""
31 30
32 31 @line_magic
33 32 def load_ext(self, module_str):
34 33 """Load an IPython extension by its module name."""
35 34 if not module_str:
36 35 raise UsageError('Missing module name.')
37 36 res = self.shell.extension_manager.load_extension(module_str)
38 37
39 38 if res == 'already loaded':
40 39 print("The %s extension is already loaded. To reload it, use:" % module_str)
41 40 print(" %reload_ext", module_str)
42 41 elif res == 'no load function':
43 42 print("The %s module is not an IPython extension." % module_str)
44 43
45 44 @line_magic
46 45 def unload_ext(self, module_str):
47 46 """Unload an IPython extension by its module name.
48 47
49 48 Not all extensions can be unloaded, only those which define an
50 49 ``unload_ipython_extension`` function.
51 50 """
52 51 if not module_str:
53 52 raise UsageError('Missing module name.')
54 53
55 54 res = self.shell.extension_manager.unload_extension(module_str)
56 55
57 56 if res == 'no unload function':
58 57 print("The %s extension doesn't define how to unload it." % module_str)
59 58 elif res == "not loaded":
60 59 print("The %s extension is not loaded." % module_str)
61 60
62 61 @line_magic
63 62 def reload_ext(self, module_str):
64 63 """Reload an IPython extension by its module name."""
65 64 if not module_str:
66 65 raise UsageError('Missing module name.')
67 66 self.shell.extension_manager.reload_extension(module_str)
@@ -1,320 +1,319 b''
1 1 """Implementation of magic functions related to History.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012, IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 from __future__ import print_function
15 14
16 15 # Stdlib
17 16 import os
18 17 import sys
19 18 from io import open as io_open
20 19
21 20 # Our own packages
22 21 from IPython.core.error import StdinNotImplementedError
23 22 from IPython.core.magic import Magics, magics_class, line_magic
24 23 from IPython.core.magic_arguments import (argument, magic_arguments,
25 24 parse_argstring)
26 25 from IPython.testing.skipdoctest import skip_doctest
27 26 from IPython.utils import io
28 27 from IPython.utils.py3compat import cast_unicode_py2
29 28
30 29 #-----------------------------------------------------------------------------
31 30 # Magics class implementation
32 31 #-----------------------------------------------------------------------------
33 32
34 33
35 34 _unspecified = object()
36 35
37 36
38 37 @magics_class
39 38 class HistoryMagics(Magics):
40 39
41 40 @magic_arguments()
42 41 @argument(
43 42 '-n', dest='print_nums', action='store_true', default=False,
44 43 help="""
45 44 print line numbers for each input.
46 45 This feature is only available if numbered prompts are in use.
47 46 """)
48 47 @argument(
49 48 '-o', dest='get_output', action='store_true', default=False,
50 49 help="also print outputs for each input.")
51 50 @argument(
52 51 '-p', dest='pyprompts', action='store_true', default=False,
53 52 help="""
54 53 print classic '>>>' python prompts before each input.
55 54 This is useful for making documentation, and in conjunction
56 55 with -o, for producing doctest-ready output.
57 56 """)
58 57 @argument(
59 58 '-t', dest='raw', action='store_false', default=True,
60 59 help="""
61 60 print the 'translated' history, as IPython understands it.
62 61 IPython filters your input and converts it all into valid Python
63 62 source before executing it (things like magics or aliases are turned
64 63 into function calls, for example). With this option, you'll see the
65 64 native history instead of the user-entered version: '%%cd /' will be
66 65 seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
67 66 """)
68 67 @argument(
69 68 '-f', dest='filename',
70 69 help="""
71 70 FILENAME: instead of printing the output to the screen, redirect
72 71 it to the given file. The file is always overwritten, though *when
73 72 it can*, IPython asks for confirmation first. In particular, running
74 73 the command 'history -f FILENAME' from the IPython Notebook
75 74 interface will replace FILENAME even if it already exists *without*
76 75 confirmation.
77 76 """)
78 77 @argument(
79 78 '-g', dest='pattern', nargs='*', default=None,
80 79 help="""
81 80 treat the arg as a glob pattern to search for in (full) history.
82 81 This includes the saved history (almost all commands ever written).
83 82 The pattern may contain '?' to match one unknown character and '*'
84 83 to match any number of unknown characters. Use '%%hist -g' to show
85 84 full saved history (may be very long).
86 85 """)
87 86 @argument(
88 87 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
89 88 help="""
90 89 get the last n lines from all sessions. Specify n as a single
91 90 arg, or the default is the last 10 lines.
92 91 """)
93 92 @argument(
94 93 '-u', dest='unique', action='store_true',
95 94 help="""
96 95 when searching history using `-g`, show only unique history.
97 96 """)
98 97 @argument('range', nargs='*')
99 98 @skip_doctest
100 99 @line_magic
101 100 def history(self, parameter_s = ''):
102 101 """Print input history (_i<n> variables), with most recent last.
103 102
104 103 By default, input history is printed without line numbers so it can be
105 104 directly pasted into an editor. Use -n to show them.
106 105
107 106 By default, all input history from the current session is displayed.
108 107 Ranges of history can be indicated using the syntax:
109 108
110 109 ``4``
111 110 Line 4, current session
112 111 ``4-6``
113 112 Lines 4-6, current session
114 113 ``243/1-5``
115 114 Lines 1-5, session 243
116 115 ``~2/7``
117 116 Line 7, session 2 before current
118 117 ``~8/1-~6/5``
119 118 From the first line of 8 sessions ago, to the fifth line of 6
120 119 sessions ago.
121 120
122 121 Multiple ranges can be entered, separated by spaces
123 122
124 123 The same syntax is used by %macro, %save, %edit, %rerun
125 124
126 125 Examples
127 126 --------
128 127 ::
129 128
130 129 In [6]: %history -n 4-6
131 130 4:a = 12
132 131 5:print a**2
133 132 6:%history -n 4-6
134 133
135 134 """
136 135
137 136 args = parse_argstring(self.history, parameter_s)
138 137
139 138 # For brevity
140 139 history_manager = self.shell.history_manager
141 140
142 141 def _format_lineno(session, line):
143 142 """Helper function to format line numbers properly."""
144 143 if session in (0, history_manager.session_number):
145 144 return str(line)
146 145 return "%s/%s" % (session, line)
147 146
148 147 # Check if output to specific file was requested.
149 148 outfname = args.filename
150 149 if not outfname:
151 150 outfile = sys.stdout # default
152 151 # We don't want to close stdout at the end!
153 152 close_at_end = False
154 153 else:
155 154 if os.path.exists(outfname):
156 155 try:
157 156 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
158 157 except StdinNotImplementedError:
159 158 ans = True
160 159 if not ans:
161 160 print('Aborting.')
162 161 return
163 162 print("Overwriting file.")
164 163 outfile = io_open(outfname, 'w', encoding='utf-8')
165 164 close_at_end = True
166 165
167 166 print_nums = args.print_nums
168 167 get_output = args.get_output
169 168 pyprompts = args.pyprompts
170 169 raw = args.raw
171 170
172 171 pattern = None
173 172 limit = None if args.limit is _unspecified else args.limit
174 173
175 174 if args.pattern is not None:
176 175 if args.pattern:
177 176 pattern = "*" + " ".join(args.pattern) + "*"
178 177 else:
179 178 pattern = "*"
180 179 hist = history_manager.search(pattern, raw=raw, output=get_output,
181 180 n=limit, unique=args.unique)
182 181 print_nums = True
183 182 elif args.limit is not _unspecified:
184 183 n = 10 if limit is None else limit
185 184 hist = history_manager.get_tail(n, raw=raw, output=get_output)
186 185 else:
187 186 if args.range: # Get history by ranges
188 187 hist = history_manager.get_range_by_str(" ".join(args.range),
189 188 raw, get_output)
190 189 else: # Just get history for the current session
191 190 hist = history_manager.get_range(raw=raw, output=get_output)
192 191
193 192 # We could be displaying the entire history, so let's not try to pull
194 193 # it into a list in memory. Anything that needs more space will just
195 194 # misalign.
196 195 width = 4
197 196
198 197 for session, lineno, inline in hist:
199 198 # Print user history with tabs expanded to 4 spaces. The GUI
200 199 # clients use hard tabs for easier usability in auto-indented code,
201 200 # but we want to produce PEP-8 compliant history for safe pasting
202 201 # into an editor.
203 202 if get_output:
204 203 inline, output = inline
205 204 inline = inline.expandtabs(4).rstrip()
206 205
207 206 multiline = "\n" in inline
208 207 line_sep = '\n' if multiline else ' '
209 208 if print_nums:
210 209 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
211 210 line_sep), file=outfile, end=u'')
212 211 if pyprompts:
213 212 print(u">>> ", end=u"", file=outfile)
214 213 if multiline:
215 214 inline = "\n... ".join(inline.splitlines()) + "\n..."
216 215 print(inline, file=outfile)
217 216 if get_output and output:
218 217 print(cast_unicode_py2(output), file=outfile)
219 218
220 219 if close_at_end:
221 220 outfile.close()
222 221
223 222 @line_magic
224 223 def recall(self, arg):
225 224 r"""Repeat a command, or get command to input line for editing.
226 225
227 226 %recall and %rep are equivalent.
228 227
229 228 - %recall (no arguments):
230 229
231 230 Place a string version of last computation result (stored in the
232 231 special '_' variable) to the next input prompt. Allows you to create
233 232 elaborate command lines without using copy-paste::
234 233
235 234 In[1]: l = ["hei", "vaan"]
236 235 In[2]: "".join(l)
237 236 Out[2]: heivaan
238 237 In[3]: %recall
239 238 In[4]: heivaan_ <== cursor blinking
240 239
241 240 %recall 45
242 241
243 242 Place history line 45 on the next input prompt. Use %hist to find
244 243 out the number.
245 244
246 245 %recall 1-4
247 246
248 247 Combine the specified lines into one cell, and place it on the next
249 248 input prompt. See %history for the slice syntax.
250 249
251 250 %recall foo+bar
252 251
253 252 If foo+bar can be evaluated in the user namespace, the result is
254 253 placed at the next input prompt. Otherwise, the history is searched
255 254 for lines which contain that substring, and the most recent one is
256 255 placed at the next input prompt.
257 256 """
258 257 if not arg: # Last output
259 258 self.shell.set_next_input(str(self.shell.user_ns["_"]))
260 259 return
261 260 # Get history range
262 261 histlines = self.shell.history_manager.get_range_by_str(arg)
263 262 cmd = "\n".join(x[2] for x in histlines)
264 263 if cmd:
265 264 self.shell.set_next_input(cmd.rstrip())
266 265 return
267 266
268 267 try: # Variable in user namespace
269 268 cmd = str(eval(arg, self.shell.user_ns))
270 269 except Exception: # Search for term in history
271 270 histlines = self.shell.history_manager.search("*"+arg+"*")
272 271 for h in reversed([x[2] for x in histlines]):
273 272 if 'recall' in h or 'rep' in h:
274 273 continue
275 274 self.shell.set_next_input(h.rstrip())
276 275 return
277 276 else:
278 277 self.shell.set_next_input(cmd.rstrip())
279 278 print("Couldn't evaluate or find in history:", arg)
280 279
281 280 @line_magic
282 281 def rerun(self, parameter_s=''):
283 282 """Re-run previous input
284 283
285 284 By default, you can specify ranges of input history to be repeated
286 285 (as with %history). With no arguments, it will repeat the last line.
287 286
288 287 Options:
289 288
290 289 -l <n> : Repeat the last n lines of input, not including the
291 290 current command.
292 291
293 292 -g foo : Repeat the most recent line which contains foo
294 293 """
295 294 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
296 295 if "l" in opts: # Last n lines
297 296 n = int(opts['l'])
298 297 hist = self.shell.history_manager.get_tail(n)
299 298 elif "g" in opts: # Search
300 299 p = "*"+opts['g']+"*"
301 300 hist = list(self.shell.history_manager.search(p))
302 301 for l in reversed(hist):
303 302 if "rerun" not in l[2]:
304 303 hist = [l] # The last match which isn't a %rerun
305 304 break
306 305 else:
307 306 hist = [] # No matches except %rerun
308 307 elif args: # Specify history ranges
309 308 hist = self.shell.history_manager.get_range_by_str(args)
310 309 else: # Last line
311 310 hist = self.shell.history_manager.get_tail(1)
312 311 hist = [x[2] for x in hist]
313 312 if not hist:
314 313 print("No lines in history match specification")
315 314 return
316 315 histlines = "\n".join(hist)
317 316 print("=== Executing: ===")
318 317 print(histlines)
319 318 print("=== Output: ===")
320 319 self.shell.run_cell("\n".join(hist), store_history=False)
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now