##// 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 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 IPython: tools for interactive and parallel computing in Python.
3 IPython: tools for interactive and parallel computing in Python.
4
4
5 http://ipython.org
5 http://ipython.org
6 """
6 """
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (c) 2008-2011, IPython Development Team.
8 # Copyright (c) 2008-2011, IPython Development Team.
9 # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
9 # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
10 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
10 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
11 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
11 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
12 #
12 #
13 # Distributed under the terms of the Modified BSD License.
13 # Distributed under the terms of the Modified BSD License.
14 #
14 #
15 # The full license is in the file COPYING.txt, distributed with this software.
15 # The full license is in the file COPYING.txt, distributed with this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 from __future__ import absolute_import
22
21
23 import os
22 import os
24 import sys
23 import sys
25
24
26 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
27 # Setup everything
26 # Setup everything
28 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
29
28
30 # Don't forget to also update setup.py when this changes!
29 # Don't forget to also update setup.py when this changes!
31 if sys.version_info < (3,3):
30 if sys.version_info < (3,3):
32 raise ImportError(
31 raise ImportError(
33 """
32 """
34 IPython 6.0+ does not support Python 2.6, 2.7, 3.0, 3.1, or 3.2.
33 IPython 6.0+ does not support Python 2.6, 2.7, 3.0, 3.1, or 3.2.
35 When using Python 2.7, please install IPython 5.x LTS Long Term Support version.
34 When using Python 2.7, please install IPython 5.x LTS Long Term Support version.
36 Beginning with IPython 6.0, Python 3.3 and above is required.
35 Beginning with IPython 6.0, Python 3.3 and above is required.
37
36
38 See IPython `README.rst` file for more information:
37 See IPython `README.rst` file for more information:
39
38
40 https://github.com/ipython/ipython/blob/master/README.rst
39 https://github.com/ipython/ipython/blob/master/README.rst
41
40
42 """)
41 """)
43
42
44 # Make it easy to import extensions - they are always directly on pythonpath.
43 # Make it easy to import extensions - they are always directly on pythonpath.
45 # Therefore, non-IPython modules can be added to extensions directory.
44 # Therefore, non-IPython modules can be added to extensions directory.
46 # This should probably be in ipapp.py.
45 # This should probably be in ipapp.py.
47 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
46 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
48
47
49 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
50 # Setup the top level names
49 # Setup the top level names
51 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
52
51
53 from .core.getipython import get_ipython
52 from .core.getipython import get_ipython
54 from .core import release
53 from .core import release
55 from .core.application import Application
54 from .core.application import Application
56 from .terminal.embed import embed
55 from .terminal.embed import embed
57
56
58 from .core.interactiveshell import InteractiveShell
57 from .core.interactiveshell import InteractiveShell
59 from .testing import test
58 from .testing import test
60 from .utils.sysinfo import sys_info
59 from .utils.sysinfo import sys_info
61 from .utils.frame import extract_module_locals
60 from .utils.frame import extract_module_locals
62
61
63 # Release data
62 # Release data
64 __author__ = '%s <%s>' % (release.author, release.author_email)
63 __author__ = '%s <%s>' % (release.author, release.author_email)
65 __license__ = release.license
64 __license__ = release.license
66 __version__ = release.version
65 __version__ = release.version
67 version_info = release.version_info
66 version_info = release.version_info
68
67
69 def embed_kernel(module=None, local_ns=None, **kwargs):
68 def embed_kernel(module=None, local_ns=None, **kwargs):
70 """Embed and start an IPython kernel in a given scope.
69 """Embed and start an IPython kernel in a given scope.
71
70
72 If you don't want the kernel to initialize the namespace
71 If you don't want the kernel to initialize the namespace
73 from the scope of the surrounding function,
72 from the scope of the surrounding function,
74 and/or you want to load full IPython configuration,
73 and/or you want to load full IPython configuration,
75 you probably want `IPython.start_kernel()` instead.
74 you probably want `IPython.start_kernel()` instead.
76
75
77 Parameters
76 Parameters
78 ----------
77 ----------
79 module : ModuleType, optional
78 module : ModuleType, optional
80 The module to load into IPython globals (default: caller)
79 The module to load into IPython globals (default: caller)
81 local_ns : dict, optional
80 local_ns : dict, optional
82 The namespace to load into IPython user namespace (default: caller)
81 The namespace to load into IPython user namespace (default: caller)
83
82
84 kwargs : various, optional
83 kwargs : various, optional
85 Further keyword args are relayed to the IPKernelApp constructor,
84 Further keyword args are relayed to the IPKernelApp constructor,
86 allowing configuration of the Kernel. Will only have an effect
85 allowing configuration of the Kernel. Will only have an effect
87 on the first embed_kernel call for a given process.
86 on the first embed_kernel call for a given process.
88 """
87 """
89
88
90 (caller_module, caller_locals) = extract_module_locals(1)
89 (caller_module, caller_locals) = extract_module_locals(1)
91 if module is None:
90 if module is None:
92 module = caller_module
91 module = caller_module
93 if local_ns is None:
92 if local_ns is None:
94 local_ns = caller_locals
93 local_ns = caller_locals
95
94
96 # Only import .zmq when we really need it
95 # Only import .zmq when we really need it
97 from ipykernel.embed import embed_kernel as real_embed_kernel
96 from ipykernel.embed import embed_kernel as real_embed_kernel
98 real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
97 real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
99
98
100 def start_ipython(argv=None, **kwargs):
99 def start_ipython(argv=None, **kwargs):
101 """Launch a normal IPython instance (as opposed to embedded)
100 """Launch a normal IPython instance (as opposed to embedded)
102
101
103 `IPython.embed()` puts a shell in a particular calling scope,
102 `IPython.embed()` puts a shell in a particular calling scope,
104 such as a function or method for debugging purposes,
103 such as a function or method for debugging purposes,
105 which is often not desirable.
104 which is often not desirable.
106
105
107 `start_ipython()` does full, regular IPython initialization,
106 `start_ipython()` does full, regular IPython initialization,
108 including loading startup files, configuration, etc.
107 including loading startup files, configuration, etc.
109 much of which is skipped by `embed()`.
108 much of which is skipped by `embed()`.
110
109
111 This is a public API method, and will survive implementation changes.
110 This is a public API method, and will survive implementation changes.
112
111
113 Parameters
112 Parameters
114 ----------
113 ----------
115
114
116 argv : list or None, optional
115 argv : list or None, optional
117 If unspecified or None, IPython will parse command-line options from sys.argv.
116 If unspecified or None, IPython will parse command-line options from sys.argv.
118 To prevent any command-line parsing, pass an empty list: `argv=[]`.
117 To prevent any command-line parsing, pass an empty list: `argv=[]`.
119 user_ns : dict, optional
118 user_ns : dict, optional
120 specify this dictionary to initialize the IPython user namespace with particular values.
119 specify this dictionary to initialize the IPython user namespace with particular values.
121 kwargs : various, optional
120 kwargs : various, optional
122 Any other kwargs will be passed to the Application constructor,
121 Any other kwargs will be passed to the Application constructor,
123 such as `config`.
122 such as `config`.
124 """
123 """
125 from IPython.terminal.ipapp import launch_new_instance
124 from IPython.terminal.ipapp import launch_new_instance
126 return launch_new_instance(argv=argv, **kwargs)
125 return launch_new_instance(argv=argv, **kwargs)
127
126
128 def start_kernel(argv=None, **kwargs):
127 def start_kernel(argv=None, **kwargs):
129 """Launch a normal IPython kernel instance (as opposed to embedded)
128 """Launch a normal IPython kernel instance (as opposed to embedded)
130
129
131 `IPython.embed_kernel()` puts a shell in a particular calling scope,
130 `IPython.embed_kernel()` puts a shell in a particular calling scope,
132 such as a function or method for debugging purposes,
131 such as a function or method for debugging purposes,
133 which is often not desirable.
132 which is often not desirable.
134
133
135 `start_kernel()` does full, regular IPython initialization,
134 `start_kernel()` does full, regular IPython initialization,
136 including loading startup files, configuration, etc.
135 including loading startup files, configuration, etc.
137 much of which is skipped by `embed()`.
136 much of which is skipped by `embed()`.
138
137
139 Parameters
138 Parameters
140 ----------
139 ----------
141
140
142 argv : list or None, optional
141 argv : list or None, optional
143 If unspecified or None, IPython will parse command-line options from sys.argv.
142 If unspecified or None, IPython will parse command-line options from sys.argv.
144 To prevent any command-line parsing, pass an empty list: `argv=[]`.
143 To prevent any command-line parsing, pass an empty list: `argv=[]`.
145 user_ns : dict, optional
144 user_ns : dict, optional
146 specify this dictionary to initialize the IPython user namespace with particular values.
145 specify this dictionary to initialize the IPython user namespace with particular values.
147 kwargs : various, optional
146 kwargs : various, optional
148 Any other kwargs will be passed to the Application constructor,
147 Any other kwargs will be passed to the Application constructor,
149 such as `config`.
148 such as `config`.
150 """
149 """
151 from IPython.kernel.zmq.kernelapp import launch_new_instance
150 from IPython.kernel.zmq.kernelapp import launch_new_instance
152 return launch_new_instance(argv=argv, **kwargs)
151 return launch_new_instance(argv=argv, **kwargs)
@@ -1,144 +1,143 b''
1 """Compiler tools with improved interactive support.
1 """Compiler tools with improved interactive support.
2
2
3 Provides compilation machinery similar to codeop, but with caching support so
3 Provides compilation machinery similar to codeop, but with caching support so
4 we can provide interactive tracebacks.
4 we can provide interactive tracebacks.
5
5
6 Authors
6 Authors
7 -------
7 -------
8 * Robert Kern
8 * Robert Kern
9 * Fernando Perez
9 * Fernando Perez
10 * Thomas Kluyver
10 * Thomas Kluyver
11 """
11 """
12
12
13 # Note: though it might be more natural to name this module 'compiler', that
13 # Note: though it might be more natural to name this module 'compiler', that
14 # name is in the stdlib and name collisions with the stdlib tend to produce
14 # name is in the stdlib and name collisions with the stdlib tend to produce
15 # weird problems (often with third-party tools).
15 # weird problems (often with third-party tools).
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2010-2011 The IPython Development Team.
18 # Copyright (C) 2010-2011 The IPython Development Team.
19 #
19 #
20 # Distributed under the terms of the BSD License.
20 # Distributed under the terms of the BSD License.
21 #
21 #
22 # The full license is in the file COPYING.txt, distributed with this software.
22 # The full license is in the file COPYING.txt, distributed with this software.
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 # Imports
26 # Imports
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 from __future__ import print_function
29
28
30 # Stdlib imports
29 # Stdlib imports
31 import __future__
30 import __future__
32 from ast import PyCF_ONLY_AST
31 from ast import PyCF_ONLY_AST
33 import codeop
32 import codeop
34 import functools
33 import functools
35 import hashlib
34 import hashlib
36 import linecache
35 import linecache
37 import operator
36 import operator
38 import time
37 import time
39
38
40 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
41 # Constants
40 # Constants
42 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
43
42
44 # Roughtly equal to PyCF_MASK | PyCF_MASK_OBSOLETE as defined in pythonrun.h,
43 # Roughtly equal to PyCF_MASK | PyCF_MASK_OBSOLETE as defined in pythonrun.h,
45 # this is used as a bitmask to extract future-related code flags.
44 # this is used as a bitmask to extract future-related code flags.
46 PyCF_MASK = functools.reduce(operator.or_,
45 PyCF_MASK = functools.reduce(operator.or_,
47 (getattr(__future__, fname).compiler_flag
46 (getattr(__future__, fname).compiler_flag
48 for fname in __future__.all_feature_names))
47 for fname in __future__.all_feature_names))
49
48
50 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
51 # Local utilities
50 # Local utilities
52 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
53
52
54 def code_name(code, number=0):
53 def code_name(code, number=0):
55 """ Compute a (probably) unique name for code for caching.
54 """ Compute a (probably) unique name for code for caching.
56
55
57 This now expects code to be unicode.
56 This now expects code to be unicode.
58 """
57 """
59 hash_digest = hashlib.md5(code.encode("utf-8")).hexdigest()
58 hash_digest = hashlib.md5(code.encode("utf-8")).hexdigest()
60 # Include the number and 12 characters of the hash in the name. It's
59 # Include the number and 12 characters of the hash in the name. It's
61 # pretty much impossible that in a single session we'll have collisions
60 # pretty much impossible that in a single session we'll have collisions
62 # even with truncated hashes, and the full one makes tracebacks too long
61 # even with truncated hashes, and the full one makes tracebacks too long
63 return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12])
62 return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12])
64
63
65 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
66 # Classes and functions
65 # Classes and functions
67 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
68
67
69 class CachingCompiler(codeop.Compile):
68 class CachingCompiler(codeop.Compile):
70 """A compiler that caches code compiled from interactive statements.
69 """A compiler that caches code compiled from interactive statements.
71 """
70 """
72
71
73 def __init__(self):
72 def __init__(self):
74 codeop.Compile.__init__(self)
73 codeop.Compile.__init__(self)
75
74
76 # This is ugly, but it must be done this way to allow multiple
75 # This is ugly, but it must be done this way to allow multiple
77 # simultaneous ipython instances to coexist. Since Python itself
76 # simultaneous ipython instances to coexist. Since Python itself
78 # directly accesses the data structures in the linecache module, and
77 # directly accesses the data structures in the linecache module, and
79 # the cache therein is global, we must work with that data structure.
78 # the cache therein is global, we must work with that data structure.
80 # We must hold a reference to the original checkcache routine and call
79 # We must hold a reference to the original checkcache routine and call
81 # that in our own check_cache() below, but the special IPython cache
80 # that in our own check_cache() below, but the special IPython cache
82 # must also be shared by all IPython instances. If we were to hold
81 # must also be shared by all IPython instances. If we were to hold
83 # separate caches (one in each CachingCompiler instance), any call made
82 # separate caches (one in each CachingCompiler instance), any call made
84 # by Python itself to linecache.checkcache() would obliterate the
83 # by Python itself to linecache.checkcache() would obliterate the
85 # cached data from the other IPython instances.
84 # cached data from the other IPython instances.
86 if not hasattr(linecache, '_ipython_cache'):
85 if not hasattr(linecache, '_ipython_cache'):
87 linecache._ipython_cache = {}
86 linecache._ipython_cache = {}
88 if not hasattr(linecache, '_checkcache_ori'):
87 if not hasattr(linecache, '_checkcache_ori'):
89 linecache._checkcache_ori = linecache.checkcache
88 linecache._checkcache_ori = linecache.checkcache
90 # Now, we must monkeypatch the linecache directly so that parts of the
89 # Now, we must monkeypatch the linecache directly so that parts of the
91 # stdlib that call it outside our control go through our codepath
90 # stdlib that call it outside our control go through our codepath
92 # (otherwise we'd lose our tracebacks).
91 # (otherwise we'd lose our tracebacks).
93 linecache.checkcache = check_linecache_ipython
92 linecache.checkcache = check_linecache_ipython
94
93
95 def ast_parse(self, source, filename='<unknown>', symbol='exec'):
94 def ast_parse(self, source, filename='<unknown>', symbol='exec'):
96 """Parse code to an AST with the current compiler flags active.
95 """Parse code to an AST with the current compiler flags active.
97
96
98 Arguments are exactly the same as ast.parse (in the standard library),
97 Arguments are exactly the same as ast.parse (in the standard library),
99 and are passed to the built-in compile function."""
98 and are passed to the built-in compile function."""
100 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
99 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
101
100
102 def reset_compiler_flags(self):
101 def reset_compiler_flags(self):
103 """Reset compiler flags to default state."""
102 """Reset compiler flags to default state."""
104 # This value is copied from codeop.Compile.__init__, so if that ever
103 # This value is copied from codeop.Compile.__init__, so if that ever
105 # changes, it will need to be updated.
104 # changes, it will need to be updated.
106 self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
105 self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
107
106
108 @property
107 @property
109 def compiler_flags(self):
108 def compiler_flags(self):
110 """Flags currently active in the compilation process.
109 """Flags currently active in the compilation process.
111 """
110 """
112 return self.flags
111 return self.flags
113
112
114 def cache(self, code, number=0):
113 def cache(self, code, number=0):
115 """Make a name for a block of code, and cache the code.
114 """Make a name for a block of code, and cache the code.
116
115
117 Parameters
116 Parameters
118 ----------
117 ----------
119 code : str
118 code : str
120 The Python source code to cache.
119 The Python source code to cache.
121 number : int
120 number : int
122 A number which forms part of the code's name. Used for the execution
121 A number which forms part of the code's name. Used for the execution
123 counter.
122 counter.
124
123
125 Returns
124 Returns
126 -------
125 -------
127 The name of the cached code (as a string). Pass this as the filename
126 The name of the cached code (as a string). Pass this as the filename
128 argument to compilation, so that tracebacks are correctly hooked up.
127 argument to compilation, so that tracebacks are correctly hooked up.
129 """
128 """
130 name = code_name(code, number)
129 name = code_name(code, number)
131 entry = (len(code), time.time(),
130 entry = (len(code), time.time(),
132 [line+'\n' for line in code.splitlines()], name)
131 [line+'\n' for line in code.splitlines()], name)
133 linecache.cache[name] = entry
132 linecache.cache[name] = entry
134 linecache._ipython_cache[name] = entry
133 linecache._ipython_cache[name] = entry
135 return name
134 return name
136
135
137 def check_linecache_ipython(*args):
136 def check_linecache_ipython(*args):
138 """Call linecache.checkcache() safely protecting our cached values.
137 """Call linecache.checkcache() safely protecting our cached values.
139 """
138 """
140 # First call the orignal checkcache as intended
139 # First call the orignal checkcache as intended
141 linecache._checkcache_ori(*args)
140 linecache._checkcache_ori(*args)
142 # Then, update back the cache with our data, so that tracebacks related
141 # Then, update back the cache with our data, so that tracebacks related
143 # to our compiled codes can be produced.
142 # to our compiled codes can be produced.
144 linecache.cache.update(linecache._ipython_cache)
143 linecache.cache.update(linecache._ipython_cache)
@@ -1,1237 +1,1236 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Word completion for IPython.
2 """Word completion for IPython.
3
3
4 This module started as fork of the rlcompleter module in the Python standard
4 This module started as fork of the rlcompleter module in the Python standard
5 library. The original enhancements made to rlcompleter have been sent
5 library. The original enhancements made to rlcompleter have been sent
6 upstream and were accepted as of Python 2.3,
6 upstream and were accepted as of Python 2.3,
7
7
8 """
8 """
9
9
10 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12 #
12 #
13 # Some of this code originated from rlcompleter in the Python standard library
13 # Some of this code originated from rlcompleter in the Python standard library
14 # Copyright (C) 2001 Python Software Foundation, www.python.org
14 # Copyright (C) 2001 Python Software Foundation, www.python.org
15
15
16 from __future__ import print_function
17
16
18 import __main__
17 import __main__
19 import glob
18 import glob
20 import inspect
19 import inspect
21 import itertools
20 import itertools
22 import keyword
21 import keyword
23 import os
22 import os
24 import re
23 import re
25 import sys
24 import sys
26 import unicodedata
25 import unicodedata
27 import string
26 import string
28 import warnings
27 import warnings
29 from importlib import import_module
28 from importlib import import_module
30
29
31 from traitlets.config.configurable import Configurable
30 from traitlets.config.configurable import Configurable
32 from IPython.core.error import TryNext
31 from IPython.core.error import TryNext
33 from IPython.core.inputsplitter import ESC_MAGIC
32 from IPython.core.inputsplitter import ESC_MAGIC
34 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
33 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
35 from IPython.utils import generics
34 from IPython.utils import generics
36 from IPython.utils.decorators import undoc
35 from IPython.utils.decorators import undoc
37 from IPython.utils.dir2 import dir2, get_real_method
36 from IPython.utils.dir2 import dir2, get_real_method
38 from IPython.utils.process import arg_split
37 from IPython.utils.process import arg_split
39 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
38 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
40 from traitlets import Bool, Enum, observe
39 from traitlets import Bool, Enum, observe
41
40
42 from functools import wraps
41 from functools import wraps
43
42
44 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
45 # Globals
44 # Globals
46 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
47
46
48 # Public API
47 # Public API
49 __all__ = ['Completer','IPCompleter']
48 __all__ = ['Completer','IPCompleter']
50
49
51 if sys.platform == 'win32':
50 if sys.platform == 'win32':
52 PROTECTABLES = ' '
51 PROTECTABLES = ' '
53 else:
52 else:
54 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
53 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
55
54
56
55
57 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
58 # Work around BUG decorators.
57 # Work around BUG decorators.
59 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
60
59
61 def _strip_single_trailing_space(complete):
60 def _strip_single_trailing_space(complete):
62 """
61 """
63 This is a workaround for a weird IPython/Prompt_toolkit behavior,
62 This is a workaround for a weird IPython/Prompt_toolkit behavior,
64 that can be removed once we rely on a slightly more recent prompt_toolkit
63 that can be removed once we rely on a slightly more recent prompt_toolkit
65 version (likely > 1.0.3). So this can likely be removed in IPython 6.0
64 version (likely > 1.0.3). So this can likely be removed in IPython 6.0
66
65
67 cf https://github.com/ipython/ipython/issues/9658
66 cf https://github.com/ipython/ipython/issues/9658
68 and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328
67 and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328
69
68
70 The bug is due to the fact that in PTK the completer will reinvoke itself
69 The bug is due to the fact that in PTK the completer will reinvoke itself
71 after trying to completer to the longuest common prefix of all the
70 after trying to completer to the longuest common prefix of all the
72 completions, unless only one completion is available.
71 completions, unless only one completion is available.
73
72
74 This logic is faulty if the completion ends with space, which can happen in
73 This logic is faulty if the completion ends with space, which can happen in
75 case like::
74 case like::
76
75
77 from foo import im<ta>
76 from foo import im<ta>
78
77
79 which only matching completion is `import `. Note the leading space at the
78 which only matching completion is `import `. Note the leading space at the
80 end. So leaving a space at the end is a reasonable request, but for now
79 end. So leaving a space at the end is a reasonable request, but for now
81 we'll strip it.
80 we'll strip it.
82 """
81 """
83
82
84 @wraps(complete)
83 @wraps(complete)
85 def comp(*args, **kwargs):
84 def comp(*args, **kwargs):
86 text, matches = complete(*args, **kwargs)
85 text, matches = complete(*args, **kwargs)
87 if len(matches) == 1:
86 if len(matches) == 1:
88 return text, [matches[0].rstrip()]
87 return text, [matches[0].rstrip()]
89 return text, matches
88 return text, matches
90
89
91 return comp
90 return comp
92
91
93
92
94
93
95 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
96 # Main functions and classes
95 # Main functions and classes
97 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
98
97
99 def has_open_quotes(s):
98 def has_open_quotes(s):
100 """Return whether a string has open quotes.
99 """Return whether a string has open quotes.
101
100
102 This simply counts whether the number of quote characters of either type in
101 This simply counts whether the number of quote characters of either type in
103 the string is odd.
102 the string is odd.
104
103
105 Returns
104 Returns
106 -------
105 -------
107 If there is an open quote, the quote character is returned. Else, return
106 If there is an open quote, the quote character is returned. Else, return
108 False.
107 False.
109 """
108 """
110 # We check " first, then ', so complex cases with nested quotes will get
109 # We check " first, then ', so complex cases with nested quotes will get
111 # the " to take precedence.
110 # the " to take precedence.
112 if s.count('"') % 2:
111 if s.count('"') % 2:
113 return '"'
112 return '"'
114 elif s.count("'") % 2:
113 elif s.count("'") % 2:
115 return "'"
114 return "'"
116 else:
115 else:
117 return False
116 return False
118
117
119
118
120 def protect_filename(s):
119 def protect_filename(s):
121 """Escape a string to protect certain characters."""
120 """Escape a string to protect certain characters."""
122 if set(s) & set(PROTECTABLES):
121 if set(s) & set(PROTECTABLES):
123 if sys.platform == "win32":
122 if sys.platform == "win32":
124 return '"' + s + '"'
123 return '"' + s + '"'
125 else:
124 else:
126 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
125 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
127 else:
126 else:
128 return s
127 return s
129
128
130
129
131 def expand_user(path):
130 def expand_user(path):
132 """Expand '~'-style usernames in strings.
131 """Expand '~'-style usernames in strings.
133
132
134 This is similar to :func:`os.path.expanduser`, but it computes and returns
133 This is similar to :func:`os.path.expanduser`, but it computes and returns
135 extra information that will be useful if the input was being used in
134 extra information that will be useful if the input was being used in
136 computing completions, and you wish to return the completions with the
135 computing completions, and you wish to return the completions with the
137 original '~' instead of its expanded value.
136 original '~' instead of its expanded value.
138
137
139 Parameters
138 Parameters
140 ----------
139 ----------
141 path : str
140 path : str
142 String to be expanded. If no ~ is present, the output is the same as the
141 String to be expanded. If no ~ is present, the output is the same as the
143 input.
142 input.
144
143
145 Returns
144 Returns
146 -------
145 -------
147 newpath : str
146 newpath : str
148 Result of ~ expansion in the input path.
147 Result of ~ expansion in the input path.
149 tilde_expand : bool
148 tilde_expand : bool
150 Whether any expansion was performed or not.
149 Whether any expansion was performed or not.
151 tilde_val : str
150 tilde_val : str
152 The value that ~ was replaced with.
151 The value that ~ was replaced with.
153 """
152 """
154 # Default values
153 # Default values
155 tilde_expand = False
154 tilde_expand = False
156 tilde_val = ''
155 tilde_val = ''
157 newpath = path
156 newpath = path
158
157
159 if path.startswith('~'):
158 if path.startswith('~'):
160 tilde_expand = True
159 tilde_expand = True
161 rest = len(path)-1
160 rest = len(path)-1
162 newpath = os.path.expanduser(path)
161 newpath = os.path.expanduser(path)
163 if rest:
162 if rest:
164 tilde_val = newpath[:-rest]
163 tilde_val = newpath[:-rest]
165 else:
164 else:
166 tilde_val = newpath
165 tilde_val = newpath
167
166
168 return newpath, tilde_expand, tilde_val
167 return newpath, tilde_expand, tilde_val
169
168
170
169
171 def compress_user(path, tilde_expand, tilde_val):
170 def compress_user(path, tilde_expand, tilde_val):
172 """Does the opposite of expand_user, with its outputs.
171 """Does the opposite of expand_user, with its outputs.
173 """
172 """
174 if tilde_expand:
173 if tilde_expand:
175 return path.replace(tilde_val, '~')
174 return path.replace(tilde_val, '~')
176 else:
175 else:
177 return path
176 return path
178
177
179
178
180 def completions_sorting_key(word):
179 def completions_sorting_key(word):
181 """key for sorting completions
180 """key for sorting completions
182
181
183 This does several things:
182 This does several things:
184
183
185 - Lowercase all completions, so they are sorted alphabetically with
184 - Lowercase all completions, so they are sorted alphabetically with
186 upper and lower case words mingled
185 upper and lower case words mingled
187 - Demote any completions starting with underscores to the end
186 - Demote any completions starting with underscores to the end
188 - Insert any %magic and %%cellmagic completions in the alphabetical order
187 - Insert any %magic and %%cellmagic completions in the alphabetical order
189 by their name
188 by their name
190 """
189 """
191 # Case insensitive sort
190 # Case insensitive sort
192 word = word.lower()
191 word = word.lower()
193
192
194 prio1, prio2 = 0, 0
193 prio1, prio2 = 0, 0
195
194
196 if word.startswith('__'):
195 if word.startswith('__'):
197 prio1 = 2
196 prio1 = 2
198 elif word.startswith('_'):
197 elif word.startswith('_'):
199 prio1 = 1
198 prio1 = 1
200
199
201 if word.endswith('='):
200 if word.endswith('='):
202 prio1 = -1
201 prio1 = -1
203
202
204 if word.startswith('%%'):
203 if word.startswith('%%'):
205 # If there's another % in there, this is something else, so leave it alone
204 # If there's another % in there, this is something else, so leave it alone
206 if not "%" in word[2:]:
205 if not "%" in word[2:]:
207 word = word[2:]
206 word = word[2:]
208 prio2 = 2
207 prio2 = 2
209 elif word.startswith('%'):
208 elif word.startswith('%'):
210 if not "%" in word[1:]:
209 if not "%" in word[1:]:
211 word = word[1:]
210 word = word[1:]
212 prio2 = 1
211 prio2 = 1
213
212
214 return prio1, word, prio2
213 return prio1, word, prio2
215
214
216
215
217 @undoc
216 @undoc
218 class Bunch(object): pass
217 class Bunch(object): pass
219
218
220
219
221 if sys.platform == 'win32':
220 if sys.platform == 'win32':
222 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
221 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
223 else:
222 else:
224 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
223 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
225
224
226 GREEDY_DELIMS = ' =\r\n'
225 GREEDY_DELIMS = ' =\r\n'
227
226
228
227
229 class CompletionSplitter(object):
228 class CompletionSplitter(object):
230 """An object to split an input line in a manner similar to readline.
229 """An object to split an input line in a manner similar to readline.
231
230
232 By having our own implementation, we can expose readline-like completion in
231 By having our own implementation, we can expose readline-like completion in
233 a uniform manner to all frontends. This object only needs to be given the
232 a uniform manner to all frontends. This object only needs to be given the
234 line of text to be split and the cursor position on said line, and it
233 line of text to be split and the cursor position on said line, and it
235 returns the 'word' to be completed on at the cursor after splitting the
234 returns the 'word' to be completed on at the cursor after splitting the
236 entire line.
235 entire line.
237
236
238 What characters are used as splitting delimiters can be controlled by
237 What characters are used as splitting delimiters can be controlled by
239 setting the `delims` attribute (this is a property that internally
238 setting the `delims` attribute (this is a property that internally
240 automatically builds the necessary regular expression)"""
239 automatically builds the necessary regular expression)"""
241
240
242 # Private interface
241 # Private interface
243
242
244 # A string of delimiter characters. The default value makes sense for
243 # A string of delimiter characters. The default value makes sense for
245 # IPython's most typical usage patterns.
244 # IPython's most typical usage patterns.
246 _delims = DELIMS
245 _delims = DELIMS
247
246
248 # The expression (a normal string) to be compiled into a regular expression
247 # The expression (a normal string) to be compiled into a regular expression
249 # for actual splitting. We store it as an attribute mostly for ease of
248 # for actual splitting. We store it as an attribute mostly for ease of
250 # debugging, since this type of code can be so tricky to debug.
249 # debugging, since this type of code can be so tricky to debug.
251 _delim_expr = None
250 _delim_expr = None
252
251
253 # The regular expression that does the actual splitting
252 # The regular expression that does the actual splitting
254 _delim_re = None
253 _delim_re = None
255
254
256 def __init__(self, delims=None):
255 def __init__(self, delims=None):
257 delims = CompletionSplitter._delims if delims is None else delims
256 delims = CompletionSplitter._delims if delims is None else delims
258 self.delims = delims
257 self.delims = delims
259
258
260 @property
259 @property
261 def delims(self):
260 def delims(self):
262 """Return the string of delimiter characters."""
261 """Return the string of delimiter characters."""
263 return self._delims
262 return self._delims
264
263
265 @delims.setter
264 @delims.setter
266 def delims(self, delims):
265 def delims(self, delims):
267 """Set the delimiters for line splitting."""
266 """Set the delimiters for line splitting."""
268 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
267 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
269 self._delim_re = re.compile(expr)
268 self._delim_re = re.compile(expr)
270 self._delims = delims
269 self._delims = delims
271 self._delim_expr = expr
270 self._delim_expr = expr
272
271
273 def split_line(self, line, cursor_pos=None):
272 def split_line(self, line, cursor_pos=None):
274 """Split a line of text with a cursor at the given position.
273 """Split a line of text with a cursor at the given position.
275 """
274 """
276 l = line if cursor_pos is None else line[:cursor_pos]
275 l = line if cursor_pos is None else line[:cursor_pos]
277 return self._delim_re.split(l)[-1]
276 return self._delim_re.split(l)[-1]
278
277
279
278
280 class Completer(Configurable):
279 class Completer(Configurable):
281
280
282 greedy = Bool(False,
281 greedy = Bool(False,
283 help="""Activate greedy completion
282 help="""Activate greedy completion
284 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
283 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
285
284
286 This will enable completion on elements of lists, results of function calls, etc.,
285 This will enable completion on elements of lists, results of function calls, etc.,
287 but can be unsafe because the code is actually evaluated on TAB.
286 but can be unsafe because the code is actually evaluated on TAB.
288 """
287 """
289 ).tag(config=True)
288 ).tag(config=True)
290
289
291
290
292 def __init__(self, namespace=None, global_namespace=None, **kwargs):
291 def __init__(self, namespace=None, global_namespace=None, **kwargs):
293 """Create a new completer for the command line.
292 """Create a new completer for the command line.
294
293
295 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
294 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
296
295
297 If unspecified, the default namespace where completions are performed
296 If unspecified, the default namespace where completions are performed
298 is __main__ (technically, __main__.__dict__). Namespaces should be
297 is __main__ (technically, __main__.__dict__). Namespaces should be
299 given as dictionaries.
298 given as dictionaries.
300
299
301 An optional second namespace can be given. This allows the completer
300 An optional second namespace can be given. This allows the completer
302 to handle cases where both the local and global scopes need to be
301 to handle cases where both the local and global scopes need to be
303 distinguished.
302 distinguished.
304
303
305 Completer instances should be used as the completion mechanism of
304 Completer instances should be used as the completion mechanism of
306 readline via the set_completer() call:
305 readline via the set_completer() call:
307
306
308 readline.set_completer(Completer(my_namespace).complete)
307 readline.set_completer(Completer(my_namespace).complete)
309 """
308 """
310
309
311 # Don't bind to namespace quite yet, but flag whether the user wants a
310 # Don't bind to namespace quite yet, but flag whether the user wants a
312 # specific namespace or to use __main__.__dict__. This will allow us
311 # specific namespace or to use __main__.__dict__. This will allow us
313 # to bind to __main__.__dict__ at completion time, not now.
312 # to bind to __main__.__dict__ at completion time, not now.
314 if namespace is None:
313 if namespace is None:
315 self.use_main_ns = 1
314 self.use_main_ns = 1
316 else:
315 else:
317 self.use_main_ns = 0
316 self.use_main_ns = 0
318 self.namespace = namespace
317 self.namespace = namespace
319
318
320 # The global namespace, if given, can be bound directly
319 # The global namespace, if given, can be bound directly
321 if global_namespace is None:
320 if global_namespace is None:
322 self.global_namespace = {}
321 self.global_namespace = {}
323 else:
322 else:
324 self.global_namespace = global_namespace
323 self.global_namespace = global_namespace
325
324
326 super(Completer, self).__init__(**kwargs)
325 super(Completer, self).__init__(**kwargs)
327
326
328 def complete(self, text, state):
327 def complete(self, text, state):
329 """Return the next possible completion for 'text'.
328 """Return the next possible completion for 'text'.
330
329
331 This is called successively with state == 0, 1, 2, ... until it
330 This is called successively with state == 0, 1, 2, ... until it
332 returns None. The completion should begin with 'text'.
331 returns None. The completion should begin with 'text'.
333
332
334 """
333 """
335 if self.use_main_ns:
334 if self.use_main_ns:
336 self.namespace = __main__.__dict__
335 self.namespace = __main__.__dict__
337
336
338 if state == 0:
337 if state == 0:
339 if "." in text:
338 if "." in text:
340 self.matches = self.attr_matches(text)
339 self.matches = self.attr_matches(text)
341 else:
340 else:
342 self.matches = self.global_matches(text)
341 self.matches = self.global_matches(text)
343 try:
342 try:
344 return self.matches[state]
343 return self.matches[state]
345 except IndexError:
344 except IndexError:
346 return None
345 return None
347
346
348 def global_matches(self, text):
347 def global_matches(self, text):
349 """Compute matches when text is a simple name.
348 """Compute matches when text is a simple name.
350
349
351 Return a list of all keywords, built-in functions and names currently
350 Return a list of all keywords, built-in functions and names currently
352 defined in self.namespace or self.global_namespace that match.
351 defined in self.namespace or self.global_namespace that match.
353
352
354 """
353 """
355 matches = []
354 matches = []
356 match_append = matches.append
355 match_append = matches.append
357 n = len(text)
356 n = len(text)
358 for lst in [keyword.kwlist,
357 for lst in [keyword.kwlist,
359 builtin_mod.__dict__.keys(),
358 builtin_mod.__dict__.keys(),
360 self.namespace.keys(),
359 self.namespace.keys(),
361 self.global_namespace.keys()]:
360 self.global_namespace.keys()]:
362 for word in lst:
361 for word in lst:
363 if word[:n] == text and word != "__builtins__":
362 if word[:n] == text and word != "__builtins__":
364 match_append(word)
363 match_append(word)
365 return [cast_unicode_py2(m) for m in matches]
364 return [cast_unicode_py2(m) for m in matches]
366
365
367 def attr_matches(self, text):
366 def attr_matches(self, text):
368 """Compute matches when text contains a dot.
367 """Compute matches when text contains a dot.
369
368
370 Assuming the text is of the form NAME.NAME....[NAME], and is
369 Assuming the text is of the form NAME.NAME....[NAME], and is
371 evaluatable in self.namespace or self.global_namespace, it will be
370 evaluatable in self.namespace or self.global_namespace, it will be
372 evaluated and its attributes (as revealed by dir()) are used as
371 evaluated and its attributes (as revealed by dir()) are used as
373 possible completions. (For class instances, class members are are
372 possible completions. (For class instances, class members are are
374 also considered.)
373 also considered.)
375
374
376 WARNING: this can still invoke arbitrary C code, if an object
375 WARNING: this can still invoke arbitrary C code, if an object
377 with a __getattr__ hook is evaluated.
376 with a __getattr__ hook is evaluated.
378
377
379 """
378 """
380
379
381 # Another option, seems to work great. Catches things like ''.<tab>
380 # Another option, seems to work great. Catches things like ''.<tab>
382 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
381 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
383
382
384 if m:
383 if m:
385 expr, attr = m.group(1, 3)
384 expr, attr = m.group(1, 3)
386 elif self.greedy:
385 elif self.greedy:
387 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
386 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
388 if not m2:
387 if not m2:
389 return []
388 return []
390 expr, attr = m2.group(1,2)
389 expr, attr = m2.group(1,2)
391 else:
390 else:
392 return []
391 return []
393
392
394 try:
393 try:
395 obj = eval(expr, self.namespace)
394 obj = eval(expr, self.namespace)
396 except:
395 except:
397 try:
396 try:
398 obj = eval(expr, self.global_namespace)
397 obj = eval(expr, self.global_namespace)
399 except:
398 except:
400 return []
399 return []
401
400
402 if self.limit_to__all__ and hasattr(obj, '__all__'):
401 if self.limit_to__all__ and hasattr(obj, '__all__'):
403 words = get__all__entries(obj)
402 words = get__all__entries(obj)
404 else:
403 else:
405 words = dir2(obj)
404 words = dir2(obj)
406
405
407 try:
406 try:
408 words = generics.complete_object(obj, words)
407 words = generics.complete_object(obj, words)
409 except TryNext:
408 except TryNext:
410 pass
409 pass
411 except Exception:
410 except Exception:
412 # Silence errors from completion function
411 # Silence errors from completion function
413 #raise # dbg
412 #raise # dbg
414 pass
413 pass
415 # Build match list to return
414 # Build match list to return
416 n = len(attr)
415 n = len(attr)
417 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
416 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
418
417
419
418
420 def get__all__entries(obj):
419 def get__all__entries(obj):
421 """returns the strings in the __all__ attribute"""
420 """returns the strings in the __all__ attribute"""
422 try:
421 try:
423 words = getattr(obj, '__all__')
422 words = getattr(obj, '__all__')
424 except:
423 except:
425 return []
424 return []
426
425
427 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
426 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
428
427
429
428
430 def match_dict_keys(keys, prefix, delims):
429 def match_dict_keys(keys, prefix, delims):
431 """Used by dict_key_matches, matching the prefix to a list of keys"""
430 """Used by dict_key_matches, matching the prefix to a list of keys"""
432 if not prefix:
431 if not prefix:
433 return None, 0, [repr(k) for k in keys
432 return None, 0, [repr(k) for k in keys
434 if isinstance(k, (string_types, bytes))]
433 if isinstance(k, (string_types, bytes))]
435 quote_match = re.search('["\']', prefix)
434 quote_match = re.search('["\']', prefix)
436 quote = quote_match.group()
435 quote = quote_match.group()
437 try:
436 try:
438 prefix_str = eval(prefix + quote, {})
437 prefix_str = eval(prefix + quote, {})
439 except Exception:
438 except Exception:
440 return None, 0, []
439 return None, 0, []
441
440
442 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
441 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
443 token_match = re.search(pattern, prefix, re.UNICODE)
442 token_match = re.search(pattern, prefix, re.UNICODE)
444 token_start = token_match.start()
443 token_start = token_match.start()
445 token_prefix = token_match.group()
444 token_prefix = token_match.group()
446
445
447 # TODO: support bytes in Py3k
446 # TODO: support bytes in Py3k
448 matched = []
447 matched = []
449 for key in keys:
448 for key in keys:
450 try:
449 try:
451 if not key.startswith(prefix_str):
450 if not key.startswith(prefix_str):
452 continue
451 continue
453 except (AttributeError, TypeError, UnicodeError):
452 except (AttributeError, TypeError, UnicodeError):
454 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
453 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
455 continue
454 continue
456
455
457 # reformat remainder of key to begin with prefix
456 # reformat remainder of key to begin with prefix
458 rem = key[len(prefix_str):]
457 rem = key[len(prefix_str):]
459 # force repr wrapped in '
458 # force repr wrapped in '
460 rem_repr = repr(rem + '"')
459 rem_repr = repr(rem + '"')
461 if rem_repr.startswith('u') and prefix[0] not in 'uU':
460 if rem_repr.startswith('u') and prefix[0] not in 'uU':
462 # Found key is unicode, but prefix is Py2 string.
461 # Found key is unicode, but prefix is Py2 string.
463 # Therefore attempt to interpret key as string.
462 # Therefore attempt to interpret key as string.
464 try:
463 try:
465 rem_repr = repr(rem.encode('ascii') + '"')
464 rem_repr = repr(rem.encode('ascii') + '"')
466 except UnicodeEncodeError:
465 except UnicodeEncodeError:
467 continue
466 continue
468
467
469 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
468 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
470 if quote == '"':
469 if quote == '"':
471 # The entered prefix is quoted with ",
470 # The entered prefix is quoted with ",
472 # but the match is quoted with '.
471 # but the match is quoted with '.
473 # A contained " hence needs escaping for comparison:
472 # A contained " hence needs escaping for comparison:
474 rem_repr = rem_repr.replace('"', '\\"')
473 rem_repr = rem_repr.replace('"', '\\"')
475
474
476 # then reinsert prefix from start of token
475 # then reinsert prefix from start of token
477 matched.append('%s%s' % (token_prefix, rem_repr))
476 matched.append('%s%s' % (token_prefix, rem_repr))
478 return quote, token_start, matched
477 return quote, token_start, matched
479
478
480
479
481 def _safe_isinstance(obj, module, class_name):
480 def _safe_isinstance(obj, module, class_name):
482 """Checks if obj is an instance of module.class_name if loaded
481 """Checks if obj is an instance of module.class_name if loaded
483 """
482 """
484 return (module in sys.modules and
483 return (module in sys.modules and
485 isinstance(obj, getattr(import_module(module), class_name)))
484 isinstance(obj, getattr(import_module(module), class_name)))
486
485
487
486
488 def back_unicode_name_matches(text):
487 def back_unicode_name_matches(text):
489 u"""Match unicode characters back to unicode name
488 u"""Match unicode characters back to unicode name
490
489
491 This does ☃ -> \\snowman
490 This does ☃ -> \\snowman
492
491
493 Note that snowman is not a valid python3 combining character but will be expanded.
492 Note that snowman is not a valid python3 combining character but will be expanded.
494 Though it will not recombine back to the snowman character by the completion machinery.
493 Though it will not recombine back to the snowman character by the completion machinery.
495
494
496 This will not either back-complete standard sequences like \\n, \\b ...
495 This will not either back-complete standard sequences like \\n, \\b ...
497
496
498 Used on Python 3 only.
497 Used on Python 3 only.
499 """
498 """
500 if len(text)<2:
499 if len(text)<2:
501 return u'', ()
500 return u'', ()
502 maybe_slash = text[-2]
501 maybe_slash = text[-2]
503 if maybe_slash != '\\':
502 if maybe_slash != '\\':
504 return u'', ()
503 return u'', ()
505
504
506 char = text[-1]
505 char = text[-1]
507 # no expand on quote for completion in strings.
506 # no expand on quote for completion in strings.
508 # nor backcomplete standard ascii keys
507 # nor backcomplete standard ascii keys
509 if char in string.ascii_letters or char in ['"',"'"]:
508 if char in string.ascii_letters or char in ['"',"'"]:
510 return u'', ()
509 return u'', ()
511 try :
510 try :
512 unic = unicodedata.name(char)
511 unic = unicodedata.name(char)
513 return '\\'+char,['\\'+unic]
512 return '\\'+char,['\\'+unic]
514 except KeyError:
513 except KeyError:
515 pass
514 pass
516 return u'', ()
515 return u'', ()
517
516
518 def back_latex_name_matches(text):
517 def back_latex_name_matches(text):
519 u"""Match latex characters back to unicode name
518 u"""Match latex characters back to unicode name
520
519
521 This does ->\\sqrt
520 This does ->\\sqrt
522
521
523 Used on Python 3 only.
522 Used on Python 3 only.
524 """
523 """
525 if len(text)<2:
524 if len(text)<2:
526 return u'', ()
525 return u'', ()
527 maybe_slash = text[-2]
526 maybe_slash = text[-2]
528 if maybe_slash != '\\':
527 if maybe_slash != '\\':
529 return u'', ()
528 return u'', ()
530
529
531
530
532 char = text[-1]
531 char = text[-1]
533 # no expand on quote for completion in strings.
532 # no expand on quote for completion in strings.
534 # nor backcomplete standard ascii keys
533 # nor backcomplete standard ascii keys
535 if char in string.ascii_letters or char in ['"',"'"]:
534 if char in string.ascii_letters or char in ['"',"'"]:
536 return u'', ()
535 return u'', ()
537 try :
536 try :
538 latex = reverse_latex_symbol[char]
537 latex = reverse_latex_symbol[char]
539 # '\\' replace the \ as well
538 # '\\' replace the \ as well
540 return '\\'+char,[latex]
539 return '\\'+char,[latex]
541 except KeyError:
540 except KeyError:
542 pass
541 pass
543 return u'', ()
542 return u'', ()
544
543
545
544
546 class IPCompleter(Completer):
545 class IPCompleter(Completer):
547 """Extension of the completer class with IPython-specific features"""
546 """Extension of the completer class with IPython-specific features"""
548
547
549 @observe('greedy')
548 @observe('greedy')
550 def _greedy_changed(self, change):
549 def _greedy_changed(self, change):
551 """update the splitter and readline delims when greedy is changed"""
550 """update the splitter and readline delims when greedy is changed"""
552 if change['new']:
551 if change['new']:
553 self.splitter.delims = GREEDY_DELIMS
552 self.splitter.delims = GREEDY_DELIMS
554 else:
553 else:
555 self.splitter.delims = DELIMS
554 self.splitter.delims = DELIMS
556
555
557 merge_completions = Bool(True,
556 merge_completions = Bool(True,
558 help="""Whether to merge completion results into a single list
557 help="""Whether to merge completion results into a single list
559
558
560 If False, only the completion results from the first non-empty
559 If False, only the completion results from the first non-empty
561 completer will be returned.
560 completer will be returned.
562 """
561 """
563 ).tag(config=True)
562 ).tag(config=True)
564 omit__names = Enum((0,1,2), default_value=2,
563 omit__names = Enum((0,1,2), default_value=2,
565 help="""Instruct the completer to omit private method names
564 help="""Instruct the completer to omit private method names
566
565
567 Specifically, when completing on ``object.<tab>``.
566 Specifically, when completing on ``object.<tab>``.
568
567
569 When 2 [default]: all names that start with '_' will be excluded.
568 When 2 [default]: all names that start with '_' will be excluded.
570
569
571 When 1: all 'magic' names (``__foo__``) will be excluded.
570 When 1: all 'magic' names (``__foo__``) will be excluded.
572
571
573 When 0: nothing will be excluded.
572 When 0: nothing will be excluded.
574 """
573 """
575 ).tag(config=True)
574 ).tag(config=True)
576 limit_to__all__ = Bool(False,
575 limit_to__all__ = Bool(False,
577 help="""
576 help="""
578 DEPRECATED as of version 5.0.
577 DEPRECATED as of version 5.0.
579
578
580 Instruct the completer to use __all__ for the completion
579 Instruct the completer to use __all__ for the completion
581
580
582 Specifically, when completing on ``object.<tab>``.
581 Specifically, when completing on ``object.<tab>``.
583
582
584 When True: only those names in obj.__all__ will be included.
583 When True: only those names in obj.__all__ will be included.
585
584
586 When False [default]: the __all__ attribute is ignored
585 When False [default]: the __all__ attribute is ignored
587 """,
586 """,
588 ).tag(config=True)
587 ).tag(config=True)
589
588
590 def __init__(self, shell=None, namespace=None, global_namespace=None,
589 def __init__(self, shell=None, namespace=None, global_namespace=None,
591 use_readline=False, config=None, **kwargs):
590 use_readline=False, config=None, **kwargs):
592 """IPCompleter() -> completer
591 """IPCompleter() -> completer
593
592
594 Return a completer object suitable for use by the readline library
593 Return a completer object suitable for use by the readline library
595 via readline.set_completer().
594 via readline.set_completer().
596
595
597 Inputs:
596 Inputs:
598
597
599 - shell: a pointer to the ipython shell itself. This is needed
598 - shell: a pointer to the ipython shell itself. This is needed
600 because this completer knows about magic functions, and those can
599 because this completer knows about magic functions, and those can
601 only be accessed via the ipython instance.
600 only be accessed via the ipython instance.
602
601
603 - namespace: an optional dict where completions are performed.
602 - namespace: an optional dict where completions are performed.
604
603
605 - global_namespace: secondary optional dict for completions, to
604 - global_namespace: secondary optional dict for completions, to
606 handle cases (such as IPython embedded inside functions) where
605 handle cases (such as IPython embedded inside functions) where
607 both Python scopes are visible.
606 both Python scopes are visible.
608
607
609 use_readline : bool, optional
608 use_readline : bool, optional
610 DEPRECATED, ignored.
609 DEPRECATED, ignored.
611 """
610 """
612
611
613 self.magic_escape = ESC_MAGIC
612 self.magic_escape = ESC_MAGIC
614 self.splitter = CompletionSplitter()
613 self.splitter = CompletionSplitter()
615
614
616 if use_readline:
615 if use_readline:
617 warnings.warn('The use_readline parameter is deprecated and ignored since IPython 6.0.',
616 warnings.warn('The use_readline parameter is deprecated and ignored since IPython 6.0.',
618 DeprecationWarning, stacklevel=2)
617 DeprecationWarning, stacklevel=2)
619
618
620 # _greedy_changed() depends on splitter and readline being defined:
619 # _greedy_changed() depends on splitter and readline being defined:
621 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
620 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
622 config=config, **kwargs)
621 config=config, **kwargs)
623
622
624 # List where completion matches will be stored
623 # List where completion matches will be stored
625 self.matches = []
624 self.matches = []
626 self.shell = shell
625 self.shell = shell
627 # Regexp to split filenames with spaces in them
626 # Regexp to split filenames with spaces in them
628 self.space_name_re = re.compile(r'([^\\] )')
627 self.space_name_re = re.compile(r'([^\\] )')
629 # Hold a local ref. to glob.glob for speed
628 # Hold a local ref. to glob.glob for speed
630 self.glob = glob.glob
629 self.glob = glob.glob
631
630
632 # Determine if we are running on 'dumb' terminals, like (X)Emacs
631 # Determine if we are running on 'dumb' terminals, like (X)Emacs
633 # buffers, to avoid completion problems.
632 # buffers, to avoid completion problems.
634 term = os.environ.get('TERM','xterm')
633 term = os.environ.get('TERM','xterm')
635 self.dumb_terminal = term in ['dumb','emacs']
634 self.dumb_terminal = term in ['dumb','emacs']
636
635
637 # Special handling of backslashes needed in win32 platforms
636 # Special handling of backslashes needed in win32 platforms
638 if sys.platform == "win32":
637 if sys.platform == "win32":
639 self.clean_glob = self._clean_glob_win32
638 self.clean_glob = self._clean_glob_win32
640 else:
639 else:
641 self.clean_glob = self._clean_glob
640 self.clean_glob = self._clean_glob
642
641
643 #regexp to parse docstring for function signature
642 #regexp to parse docstring for function signature
644 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
643 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
645 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
644 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
646 #use this if positional argument name is also needed
645 #use this if positional argument name is also needed
647 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
646 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
648
647
649 # All active matcher routines for completion
648 # All active matcher routines for completion
650 self.matchers = [
649 self.matchers = [
651 self.python_matches,
650 self.python_matches,
652 self.file_matches,
651 self.file_matches,
653 self.magic_matches,
652 self.magic_matches,
654 self.python_func_kw_matches,
653 self.python_func_kw_matches,
655 self.dict_key_matches,
654 self.dict_key_matches,
656 ]
655 ]
657
656
658 # This is set externally by InteractiveShell
657 # This is set externally by InteractiveShell
659 self.custom_completers = None
658 self.custom_completers = None
660
659
661 def all_completions(self, text):
660 def all_completions(self, text):
662 """
661 """
663 Wrapper around the complete method for the benefit of emacs.
662 Wrapper around the complete method for the benefit of emacs.
664 """
663 """
665 return self.complete(text)[1]
664 return self.complete(text)[1]
666
665
667 def _clean_glob(self, text):
666 def _clean_glob(self, text):
668 return self.glob("%s*" % text)
667 return self.glob("%s*" % text)
669
668
670 def _clean_glob_win32(self,text):
669 def _clean_glob_win32(self,text):
671 return [f.replace("\\","/")
670 return [f.replace("\\","/")
672 for f in self.glob("%s*" % text)]
671 for f in self.glob("%s*" % text)]
673
672
674 def file_matches(self, text):
673 def file_matches(self, text):
675 """Match filenames, expanding ~USER type strings.
674 """Match filenames, expanding ~USER type strings.
676
675
677 Most of the seemingly convoluted logic in this completer is an
676 Most of the seemingly convoluted logic in this completer is an
678 attempt to handle filenames with spaces in them. And yet it's not
677 attempt to handle filenames with spaces in them. And yet it's not
679 quite perfect, because Python's readline doesn't expose all of the
678 quite perfect, because Python's readline doesn't expose all of the
680 GNU readline details needed for this to be done correctly.
679 GNU readline details needed for this to be done correctly.
681
680
682 For a filename with a space in it, the printed completions will be
681 For a filename with a space in it, the printed completions will be
683 only the parts after what's already been typed (instead of the
682 only the parts after what's already been typed (instead of the
684 full completions, as is normally done). I don't think with the
683 full completions, as is normally done). I don't think with the
685 current (as of Python 2.3) Python readline it's possible to do
684 current (as of Python 2.3) Python readline it's possible to do
686 better."""
685 better."""
687
686
688 # chars that require escaping with backslash - i.e. chars
687 # chars that require escaping with backslash - i.e. chars
689 # that readline treats incorrectly as delimiters, but we
688 # that readline treats incorrectly as delimiters, but we
690 # don't want to treat as delimiters in filename matching
689 # don't want to treat as delimiters in filename matching
691 # when escaped with backslash
690 # when escaped with backslash
692 if text.startswith('!'):
691 if text.startswith('!'):
693 text = text[1:]
692 text = text[1:]
694 text_prefix = u'!'
693 text_prefix = u'!'
695 else:
694 else:
696 text_prefix = u''
695 text_prefix = u''
697
696
698 text_until_cursor = self.text_until_cursor
697 text_until_cursor = self.text_until_cursor
699 # track strings with open quotes
698 # track strings with open quotes
700 open_quotes = has_open_quotes(text_until_cursor)
699 open_quotes = has_open_quotes(text_until_cursor)
701
700
702 if '(' in text_until_cursor or '[' in text_until_cursor:
701 if '(' in text_until_cursor or '[' in text_until_cursor:
703 lsplit = text
702 lsplit = text
704 else:
703 else:
705 try:
704 try:
706 # arg_split ~ shlex.split, but with unicode bugs fixed by us
705 # arg_split ~ shlex.split, but with unicode bugs fixed by us
707 lsplit = arg_split(text_until_cursor)[-1]
706 lsplit = arg_split(text_until_cursor)[-1]
708 except ValueError:
707 except ValueError:
709 # typically an unmatched ", or backslash without escaped char.
708 # typically an unmatched ", or backslash without escaped char.
710 if open_quotes:
709 if open_quotes:
711 lsplit = text_until_cursor.split(open_quotes)[-1]
710 lsplit = text_until_cursor.split(open_quotes)[-1]
712 else:
711 else:
713 return []
712 return []
714 except IndexError:
713 except IndexError:
715 # tab pressed on empty line
714 # tab pressed on empty line
716 lsplit = ""
715 lsplit = ""
717
716
718 if not open_quotes and lsplit != protect_filename(lsplit):
717 if not open_quotes and lsplit != protect_filename(lsplit):
719 # if protectables are found, do matching on the whole escaped name
718 # if protectables are found, do matching on the whole escaped name
720 has_protectables = True
719 has_protectables = True
721 text0,text = text,lsplit
720 text0,text = text,lsplit
722 else:
721 else:
723 has_protectables = False
722 has_protectables = False
724 text = os.path.expanduser(text)
723 text = os.path.expanduser(text)
725
724
726 if text == "":
725 if text == "":
727 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
726 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
728
727
729 # Compute the matches from the filesystem
728 # Compute the matches from the filesystem
730 if sys.platform == 'win32':
729 if sys.platform == 'win32':
731 m0 = self.clean_glob(text)
730 m0 = self.clean_glob(text)
732 else:
731 else:
733 m0 = self.clean_glob(text.replace('\\', ''))
732 m0 = self.clean_glob(text.replace('\\', ''))
734
733
735 if has_protectables:
734 if has_protectables:
736 # If we had protectables, we need to revert our changes to the
735 # If we had protectables, we need to revert our changes to the
737 # beginning of filename so that we don't double-write the part
736 # beginning of filename so that we don't double-write the part
738 # of the filename we have so far
737 # of the filename we have so far
739 len_lsplit = len(lsplit)
738 len_lsplit = len(lsplit)
740 matches = [text_prefix + text0 +
739 matches = [text_prefix + text0 +
741 protect_filename(f[len_lsplit:]) for f in m0]
740 protect_filename(f[len_lsplit:]) for f in m0]
742 else:
741 else:
743 if open_quotes:
742 if open_quotes:
744 # if we have a string with an open quote, we don't need to
743 # if we have a string with an open quote, we don't need to
745 # protect the names at all (and we _shouldn't_, as it
744 # protect the names at all (and we _shouldn't_, as it
746 # would cause bugs when the filesystem call is made).
745 # would cause bugs when the filesystem call is made).
747 matches = m0
746 matches = m0
748 else:
747 else:
749 matches = [text_prefix +
748 matches = [text_prefix +
750 protect_filename(f) for f in m0]
749 protect_filename(f) for f in m0]
751
750
752 # Mark directories in input list by appending '/' to their names.
751 # Mark directories in input list by appending '/' to their names.
753 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
752 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
754
753
755 def magic_matches(self, text):
754 def magic_matches(self, text):
756 """Match magics"""
755 """Match magics"""
757 # Get all shell magics now rather than statically, so magics loaded at
756 # Get all shell magics now rather than statically, so magics loaded at
758 # runtime show up too.
757 # runtime show up too.
759 lsm = self.shell.magics_manager.lsmagic()
758 lsm = self.shell.magics_manager.lsmagic()
760 line_magics = lsm['line']
759 line_magics = lsm['line']
761 cell_magics = lsm['cell']
760 cell_magics = lsm['cell']
762 pre = self.magic_escape
761 pre = self.magic_escape
763 pre2 = pre+pre
762 pre2 = pre+pre
764
763
765 # Completion logic:
764 # Completion logic:
766 # - user gives %%: only do cell magics
765 # - user gives %%: only do cell magics
767 # - user gives %: do both line and cell magics
766 # - user gives %: do both line and cell magics
768 # - no prefix: do both
767 # - no prefix: do both
769 # In other words, line magics are skipped if the user gives %% explicitly
768 # In other words, line magics are skipped if the user gives %% explicitly
770 bare_text = text.lstrip(pre)
769 bare_text = text.lstrip(pre)
771 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
770 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
772 if not text.startswith(pre2):
771 if not text.startswith(pre2):
773 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
772 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
774 return [cast_unicode_py2(c) for c in comp]
773 return [cast_unicode_py2(c) for c in comp]
775
774
776
775
777 def python_matches(self, text):
776 def python_matches(self, text):
778 """Match attributes or global python names"""
777 """Match attributes or global python names"""
779 if "." in text:
778 if "." in text:
780 try:
779 try:
781 matches = self.attr_matches(text)
780 matches = self.attr_matches(text)
782 if text.endswith('.') and self.omit__names:
781 if text.endswith('.') and self.omit__names:
783 if self.omit__names == 1:
782 if self.omit__names == 1:
784 # true if txt is _not_ a __ name, false otherwise:
783 # true if txt is _not_ a __ name, false otherwise:
785 no__name = (lambda txt:
784 no__name = (lambda txt:
786 re.match(r'.*\.__.*?__',txt) is None)
785 re.match(r'.*\.__.*?__',txt) is None)
787 else:
786 else:
788 # true if txt is _not_ a _ name, false otherwise:
787 # true if txt is _not_ a _ name, false otherwise:
789 no__name = (lambda txt:
788 no__name = (lambda txt:
790 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
789 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
791 matches = filter(no__name, matches)
790 matches = filter(no__name, matches)
792 except NameError:
791 except NameError:
793 # catches <undefined attributes>.<tab>
792 # catches <undefined attributes>.<tab>
794 matches = []
793 matches = []
795 else:
794 else:
796 matches = self.global_matches(text)
795 matches = self.global_matches(text)
797 return matches
796 return matches
798
797
799 def _default_arguments_from_docstring(self, doc):
798 def _default_arguments_from_docstring(self, doc):
800 """Parse the first line of docstring for call signature.
799 """Parse the first line of docstring for call signature.
801
800
802 Docstring should be of the form 'min(iterable[, key=func])\n'.
801 Docstring should be of the form 'min(iterable[, key=func])\n'.
803 It can also parse cython docstring of the form
802 It can also parse cython docstring of the form
804 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
803 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
805 """
804 """
806 if doc is None:
805 if doc is None:
807 return []
806 return []
808
807
809 #care only the firstline
808 #care only the firstline
810 line = doc.lstrip().splitlines()[0]
809 line = doc.lstrip().splitlines()[0]
811
810
812 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
811 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
813 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
812 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
814 sig = self.docstring_sig_re.search(line)
813 sig = self.docstring_sig_re.search(line)
815 if sig is None:
814 if sig is None:
816 return []
815 return []
817 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
816 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
818 sig = sig.groups()[0].split(',')
817 sig = sig.groups()[0].split(',')
819 ret = []
818 ret = []
820 for s in sig:
819 for s in sig:
821 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
820 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
822 ret += self.docstring_kwd_re.findall(s)
821 ret += self.docstring_kwd_re.findall(s)
823 return ret
822 return ret
824
823
825 def _default_arguments(self, obj):
824 def _default_arguments(self, obj):
826 """Return the list of default arguments of obj if it is callable,
825 """Return the list of default arguments of obj if it is callable,
827 or empty list otherwise."""
826 or empty list otherwise."""
828 call_obj = obj
827 call_obj = obj
829 ret = []
828 ret = []
830 if inspect.isbuiltin(obj):
829 if inspect.isbuiltin(obj):
831 pass
830 pass
832 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
831 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
833 if inspect.isclass(obj):
832 if inspect.isclass(obj):
834 #for cython embededsignature=True the constructor docstring
833 #for cython embededsignature=True the constructor docstring
835 #belongs to the object itself not __init__
834 #belongs to the object itself not __init__
836 ret += self._default_arguments_from_docstring(
835 ret += self._default_arguments_from_docstring(
837 getattr(obj, '__doc__', ''))
836 getattr(obj, '__doc__', ''))
838 # for classes, check for __init__,__new__
837 # for classes, check for __init__,__new__
839 call_obj = (getattr(obj, '__init__', None) or
838 call_obj = (getattr(obj, '__init__', None) or
840 getattr(obj, '__new__', None))
839 getattr(obj, '__new__', None))
841 # for all others, check if they are __call__able
840 # for all others, check if they are __call__able
842 elif hasattr(obj, '__call__'):
841 elif hasattr(obj, '__call__'):
843 call_obj = obj.__call__
842 call_obj = obj.__call__
844 ret += self._default_arguments_from_docstring(
843 ret += self._default_arguments_from_docstring(
845 getattr(call_obj, '__doc__', ''))
844 getattr(call_obj, '__doc__', ''))
846
845
847 if PY3:
846 if PY3:
848 _keeps = (inspect.Parameter.KEYWORD_ONLY,
847 _keeps = (inspect.Parameter.KEYWORD_ONLY,
849 inspect.Parameter.POSITIONAL_OR_KEYWORD)
848 inspect.Parameter.POSITIONAL_OR_KEYWORD)
850 signature = inspect.signature
849 signature = inspect.signature
851 else:
850 else:
852 import IPython.utils.signatures
851 import IPython.utils.signatures
853 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
852 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
854 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
853 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
855 signature = IPython.utils.signatures.signature
854 signature = IPython.utils.signatures.signature
856
855
857 try:
856 try:
858 sig = signature(call_obj)
857 sig = signature(call_obj)
859 ret.extend(k for k, v in sig.parameters.items() if
858 ret.extend(k for k, v in sig.parameters.items() if
860 v.kind in _keeps)
859 v.kind in _keeps)
861 except ValueError:
860 except ValueError:
862 pass
861 pass
863
862
864 return list(set(ret))
863 return list(set(ret))
865
864
866 def python_func_kw_matches(self,text):
865 def python_func_kw_matches(self,text):
867 """Match named parameters (kwargs) of the last open function"""
866 """Match named parameters (kwargs) of the last open function"""
868
867
869 if "." in text: # a parameter cannot be dotted
868 if "." in text: # a parameter cannot be dotted
870 return []
869 return []
871 try: regexp = self.__funcParamsRegex
870 try: regexp = self.__funcParamsRegex
872 except AttributeError:
871 except AttributeError:
873 regexp = self.__funcParamsRegex = re.compile(r'''
872 regexp = self.__funcParamsRegex = re.compile(r'''
874 '.*?(?<!\\)' | # single quoted strings or
873 '.*?(?<!\\)' | # single quoted strings or
875 ".*?(?<!\\)" | # double quoted strings or
874 ".*?(?<!\\)" | # double quoted strings or
876 \w+ | # identifier
875 \w+ | # identifier
877 \S # other characters
876 \S # other characters
878 ''', re.VERBOSE | re.DOTALL)
877 ''', re.VERBOSE | re.DOTALL)
879 # 1. find the nearest identifier that comes before an unclosed
878 # 1. find the nearest identifier that comes before an unclosed
880 # parenthesis before the cursor
879 # parenthesis before the cursor
881 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
880 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
882 tokens = regexp.findall(self.text_until_cursor)
881 tokens = regexp.findall(self.text_until_cursor)
883 iterTokens = reversed(tokens); openPar = 0
882 iterTokens = reversed(tokens); openPar = 0
884
883
885 for token in iterTokens:
884 for token in iterTokens:
886 if token == ')':
885 if token == ')':
887 openPar -= 1
886 openPar -= 1
888 elif token == '(':
887 elif token == '(':
889 openPar += 1
888 openPar += 1
890 if openPar > 0:
889 if openPar > 0:
891 # found the last unclosed parenthesis
890 # found the last unclosed parenthesis
892 break
891 break
893 else:
892 else:
894 return []
893 return []
895 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
894 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
896 ids = []
895 ids = []
897 isId = re.compile(r'\w+$').match
896 isId = re.compile(r'\w+$').match
898
897
899 while True:
898 while True:
900 try:
899 try:
901 ids.append(next(iterTokens))
900 ids.append(next(iterTokens))
902 if not isId(ids[-1]):
901 if not isId(ids[-1]):
903 ids.pop(); break
902 ids.pop(); break
904 if not next(iterTokens) == '.':
903 if not next(iterTokens) == '.':
905 break
904 break
906 except StopIteration:
905 except StopIteration:
907 break
906 break
908
907
909 # Find all named arguments already assigned to, as to avoid suggesting
908 # Find all named arguments already assigned to, as to avoid suggesting
910 # them again
909 # them again
911 usedNamedArgs = set()
910 usedNamedArgs = set()
912 par_level = -1
911 par_level = -1
913 for token, next_token in zip(tokens, tokens[1:]):
912 for token, next_token in zip(tokens, tokens[1:]):
914 if token == '(':
913 if token == '(':
915 par_level += 1
914 par_level += 1
916 elif token == ')':
915 elif token == ')':
917 par_level -= 1
916 par_level -= 1
918
917
919 if par_level != 0:
918 if par_level != 0:
920 continue
919 continue
921
920
922 if next_token != '=':
921 if next_token != '=':
923 continue
922 continue
924
923
925 usedNamedArgs.add(token)
924 usedNamedArgs.add(token)
926
925
927 # lookup the candidate callable matches either using global_matches
926 # lookup the candidate callable matches either using global_matches
928 # or attr_matches for dotted names
927 # or attr_matches for dotted names
929 if len(ids) == 1:
928 if len(ids) == 1:
930 callableMatches = self.global_matches(ids[0])
929 callableMatches = self.global_matches(ids[0])
931 else:
930 else:
932 callableMatches = self.attr_matches('.'.join(ids[::-1]))
931 callableMatches = self.attr_matches('.'.join(ids[::-1]))
933 argMatches = []
932 argMatches = []
934 for callableMatch in callableMatches:
933 for callableMatch in callableMatches:
935 try:
934 try:
936 namedArgs = self._default_arguments(eval(callableMatch,
935 namedArgs = self._default_arguments(eval(callableMatch,
937 self.namespace))
936 self.namespace))
938 except:
937 except:
939 continue
938 continue
940
939
941 # Remove used named arguments from the list, no need to show twice
940 # Remove used named arguments from the list, no need to show twice
942 for namedArg in set(namedArgs) - usedNamedArgs:
941 for namedArg in set(namedArgs) - usedNamedArgs:
943 if namedArg.startswith(text):
942 if namedArg.startswith(text):
944 argMatches.append(u"%s=" %namedArg)
943 argMatches.append(u"%s=" %namedArg)
945 return argMatches
944 return argMatches
946
945
947 def dict_key_matches(self, text):
946 def dict_key_matches(self, text):
948 "Match string keys in a dictionary, after e.g. 'foo[' "
947 "Match string keys in a dictionary, after e.g. 'foo[' "
949 def get_keys(obj):
948 def get_keys(obj):
950 # Objects can define their own completions by defining an
949 # Objects can define their own completions by defining an
951 # _ipy_key_completions_() method.
950 # _ipy_key_completions_() method.
952 method = get_real_method(obj, '_ipython_key_completions_')
951 method = get_real_method(obj, '_ipython_key_completions_')
953 if method is not None:
952 if method is not None:
954 return method()
953 return method()
955
954
956 # Special case some common in-memory dict-like types
955 # Special case some common in-memory dict-like types
957 if isinstance(obj, dict) or\
956 if isinstance(obj, dict) or\
958 _safe_isinstance(obj, 'pandas', 'DataFrame'):
957 _safe_isinstance(obj, 'pandas', 'DataFrame'):
959 try:
958 try:
960 return list(obj.keys())
959 return list(obj.keys())
961 except Exception:
960 except Exception:
962 return []
961 return []
963 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
962 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
964 _safe_isinstance(obj, 'numpy', 'void'):
963 _safe_isinstance(obj, 'numpy', 'void'):
965 return obj.dtype.names or []
964 return obj.dtype.names or []
966 return []
965 return []
967
966
968 try:
967 try:
969 regexps = self.__dict_key_regexps
968 regexps = self.__dict_key_regexps
970 except AttributeError:
969 except AttributeError:
971 dict_key_re_fmt = r'''(?x)
970 dict_key_re_fmt = r'''(?x)
972 ( # match dict-referring expression wrt greedy setting
971 ( # match dict-referring expression wrt greedy setting
973 %s
972 %s
974 )
973 )
975 \[ # open bracket
974 \[ # open bracket
976 \s* # and optional whitespace
975 \s* # and optional whitespace
977 ([uUbB]? # string prefix (r not handled)
976 ([uUbB]? # string prefix (r not handled)
978 (?: # unclosed string
977 (?: # unclosed string
979 '(?:[^']|(?<!\\)\\')*
978 '(?:[^']|(?<!\\)\\')*
980 |
979 |
981 "(?:[^"]|(?<!\\)\\")*
980 "(?:[^"]|(?<!\\)\\")*
982 )
981 )
983 )?
982 )?
984 $
983 $
985 '''
984 '''
986 regexps = self.__dict_key_regexps = {
985 regexps = self.__dict_key_regexps = {
987 False: re.compile(dict_key_re_fmt % '''
986 False: re.compile(dict_key_re_fmt % '''
988 # identifiers separated by .
987 # identifiers separated by .
989 (?!\d)\w+
988 (?!\d)\w+
990 (?:\.(?!\d)\w+)*
989 (?:\.(?!\d)\w+)*
991 '''),
990 '''),
992 True: re.compile(dict_key_re_fmt % '''
991 True: re.compile(dict_key_re_fmt % '''
993 .+
992 .+
994 ''')
993 ''')
995 }
994 }
996
995
997 match = regexps[self.greedy].search(self.text_until_cursor)
996 match = regexps[self.greedy].search(self.text_until_cursor)
998 if match is None:
997 if match is None:
999 return []
998 return []
1000
999
1001 expr, prefix = match.groups()
1000 expr, prefix = match.groups()
1002 try:
1001 try:
1003 obj = eval(expr, self.namespace)
1002 obj = eval(expr, self.namespace)
1004 except Exception:
1003 except Exception:
1005 try:
1004 try:
1006 obj = eval(expr, self.global_namespace)
1005 obj = eval(expr, self.global_namespace)
1007 except Exception:
1006 except Exception:
1008 return []
1007 return []
1009
1008
1010 keys = get_keys(obj)
1009 keys = get_keys(obj)
1011 if not keys:
1010 if not keys:
1012 return keys
1011 return keys
1013 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1012 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1014 if not matches:
1013 if not matches:
1015 return matches
1014 return matches
1016
1015
1017 # get the cursor position of
1016 # get the cursor position of
1018 # - the text being completed
1017 # - the text being completed
1019 # - the start of the key text
1018 # - the start of the key text
1020 # - the start of the completion
1019 # - the start of the completion
1021 text_start = len(self.text_until_cursor) - len(text)
1020 text_start = len(self.text_until_cursor) - len(text)
1022 if prefix:
1021 if prefix:
1023 key_start = match.start(2)
1022 key_start = match.start(2)
1024 completion_start = key_start + token_offset
1023 completion_start = key_start + token_offset
1025 else:
1024 else:
1026 key_start = completion_start = match.end()
1025 key_start = completion_start = match.end()
1027
1026
1028 # grab the leading prefix, to make sure all completions start with `text`
1027 # grab the leading prefix, to make sure all completions start with `text`
1029 if text_start > key_start:
1028 if text_start > key_start:
1030 leading = ''
1029 leading = ''
1031 else:
1030 else:
1032 leading = text[text_start:completion_start]
1031 leading = text[text_start:completion_start]
1033
1032
1034 # the index of the `[` character
1033 # the index of the `[` character
1035 bracket_idx = match.end(1)
1034 bracket_idx = match.end(1)
1036
1035
1037 # append closing quote and bracket as appropriate
1036 # append closing quote and bracket as appropriate
1038 # this is *not* appropriate if the opening quote or bracket is outside
1037 # this is *not* appropriate if the opening quote or bracket is outside
1039 # the text given to this method
1038 # the text given to this method
1040 suf = ''
1039 suf = ''
1041 continuation = self.line_buffer[len(self.text_until_cursor):]
1040 continuation = self.line_buffer[len(self.text_until_cursor):]
1042 if key_start > text_start and closing_quote:
1041 if key_start > text_start and closing_quote:
1043 # quotes were opened inside text, maybe close them
1042 # quotes were opened inside text, maybe close them
1044 if continuation.startswith(closing_quote):
1043 if continuation.startswith(closing_quote):
1045 continuation = continuation[len(closing_quote):]
1044 continuation = continuation[len(closing_quote):]
1046 else:
1045 else:
1047 suf += closing_quote
1046 suf += closing_quote
1048 if bracket_idx > text_start:
1047 if bracket_idx > text_start:
1049 # brackets were opened inside text, maybe close them
1048 # brackets were opened inside text, maybe close them
1050 if not continuation.startswith(']'):
1049 if not continuation.startswith(']'):
1051 suf += ']'
1050 suf += ']'
1052
1051
1053 return [leading + k + suf for k in matches]
1052 return [leading + k + suf for k in matches]
1054
1053
1055 def unicode_name_matches(self, text):
1054 def unicode_name_matches(self, text):
1056 u"""Match Latex-like syntax for unicode characters base
1055 u"""Match Latex-like syntax for unicode characters base
1057 on the name of the character.
1056 on the name of the character.
1058
1057
1059 This does \\GREEK SMALL LETTER ETA -> η
1058 This does \\GREEK SMALL LETTER ETA -> η
1060
1059
1061 Works only on valid python 3 identifier, or on combining characters that
1060 Works only on valid python 3 identifier, or on combining characters that
1062 will combine to form a valid identifier.
1061 will combine to form a valid identifier.
1063
1062
1064 Used on Python 3 only.
1063 Used on Python 3 only.
1065 """
1064 """
1066 slashpos = text.rfind('\\')
1065 slashpos = text.rfind('\\')
1067 if slashpos > -1:
1066 if slashpos > -1:
1068 s = text[slashpos+1:]
1067 s = text[slashpos+1:]
1069 try :
1068 try :
1070 unic = unicodedata.lookup(s)
1069 unic = unicodedata.lookup(s)
1071 # allow combining chars
1070 # allow combining chars
1072 if ('a'+unic).isidentifier():
1071 if ('a'+unic).isidentifier():
1073 return '\\'+s,[unic]
1072 return '\\'+s,[unic]
1074 except KeyError:
1073 except KeyError:
1075 pass
1074 pass
1076 return u'', []
1075 return u'', []
1077
1076
1078
1077
1079
1078
1080
1079
1081 def latex_matches(self, text):
1080 def latex_matches(self, text):
1082 u"""Match Latex syntax for unicode characters.
1081 u"""Match Latex syntax for unicode characters.
1083
1082
1084 This does both \\alp -> \\alpha and \\alpha -> α
1083 This does both \\alp -> \\alpha and \\alpha -> α
1085
1084
1086 Used on Python 3 only.
1085 Used on Python 3 only.
1087 """
1086 """
1088 slashpos = text.rfind('\\')
1087 slashpos = text.rfind('\\')
1089 if slashpos > -1:
1088 if slashpos > -1:
1090 s = text[slashpos:]
1089 s = text[slashpos:]
1091 if s in latex_symbols:
1090 if s in latex_symbols:
1092 # Try to complete a full latex symbol to unicode
1091 # Try to complete a full latex symbol to unicode
1093 # \\alpha -> α
1092 # \\alpha -> α
1094 return s, [latex_symbols[s]]
1093 return s, [latex_symbols[s]]
1095 else:
1094 else:
1096 # If a user has partially typed a latex symbol, give them
1095 # If a user has partially typed a latex symbol, give them
1097 # a full list of options \al -> [\aleph, \alpha]
1096 # a full list of options \al -> [\aleph, \alpha]
1098 matches = [k for k in latex_symbols if k.startswith(s)]
1097 matches = [k for k in latex_symbols if k.startswith(s)]
1099 return s, matches
1098 return s, matches
1100 return u'', []
1099 return u'', []
1101
1100
1102 def dispatch_custom_completer(self, text):
1101 def dispatch_custom_completer(self, text):
1103 if not self.custom_completers:
1102 if not self.custom_completers:
1104 return
1103 return
1105
1104
1106 line = self.line_buffer
1105 line = self.line_buffer
1107 if not line.strip():
1106 if not line.strip():
1108 return None
1107 return None
1109
1108
1110 # Create a little structure to pass all the relevant information about
1109 # Create a little structure to pass all the relevant information about
1111 # the current completion to any custom completer.
1110 # the current completion to any custom completer.
1112 event = Bunch()
1111 event = Bunch()
1113 event.line = line
1112 event.line = line
1114 event.symbol = text
1113 event.symbol = text
1115 cmd = line.split(None,1)[0]
1114 cmd = line.split(None,1)[0]
1116 event.command = cmd
1115 event.command = cmd
1117 event.text_until_cursor = self.text_until_cursor
1116 event.text_until_cursor = self.text_until_cursor
1118
1117
1119 # for foo etc, try also to find completer for %foo
1118 # for foo etc, try also to find completer for %foo
1120 if not cmd.startswith(self.magic_escape):
1119 if not cmd.startswith(self.magic_escape):
1121 try_magic = self.custom_completers.s_matches(
1120 try_magic = self.custom_completers.s_matches(
1122 self.magic_escape + cmd)
1121 self.magic_escape + cmd)
1123 else:
1122 else:
1124 try_magic = []
1123 try_magic = []
1125
1124
1126 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1125 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1127 try_magic,
1126 try_magic,
1128 self.custom_completers.flat_matches(self.text_until_cursor)):
1127 self.custom_completers.flat_matches(self.text_until_cursor)):
1129 try:
1128 try:
1130 res = c(event)
1129 res = c(event)
1131 if res:
1130 if res:
1132 # first, try case sensitive match
1131 # first, try case sensitive match
1133 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1132 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1134 if withcase:
1133 if withcase:
1135 return withcase
1134 return withcase
1136 # if none, then case insensitive ones are ok too
1135 # if none, then case insensitive ones are ok too
1137 text_low = text.lower()
1136 text_low = text.lower()
1138 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1137 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1139 except TryNext:
1138 except TryNext:
1140 pass
1139 pass
1141
1140
1142 return None
1141 return None
1143
1142
1144 @_strip_single_trailing_space
1143 @_strip_single_trailing_space
1145 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1144 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1146 """Find completions for the given text and line context.
1145 """Find completions for the given text and line context.
1147
1146
1148 Note that both the text and the line_buffer are optional, but at least
1147 Note that both the text and the line_buffer are optional, but at least
1149 one of them must be given.
1148 one of them must be given.
1150
1149
1151 Parameters
1150 Parameters
1152 ----------
1151 ----------
1153 text : string, optional
1152 text : string, optional
1154 Text to perform the completion on. If not given, the line buffer
1153 Text to perform the completion on. If not given, the line buffer
1155 is split using the instance's CompletionSplitter object.
1154 is split using the instance's CompletionSplitter object.
1156
1155
1157 line_buffer : string, optional
1156 line_buffer : string, optional
1158 If not given, the completer attempts to obtain the current line
1157 If not given, the completer attempts to obtain the current line
1159 buffer via readline. This keyword allows clients which are
1158 buffer via readline. This keyword allows clients which are
1160 requesting for text completions in non-readline contexts to inform
1159 requesting for text completions in non-readline contexts to inform
1161 the completer of the entire text.
1160 the completer of the entire text.
1162
1161
1163 cursor_pos : int, optional
1162 cursor_pos : int, optional
1164 Index of the cursor in the full line buffer. Should be provided by
1163 Index of the cursor in the full line buffer. Should be provided by
1165 remote frontends where kernel has no access to frontend state.
1164 remote frontends where kernel has no access to frontend state.
1166
1165
1167 Returns
1166 Returns
1168 -------
1167 -------
1169 text : str
1168 text : str
1170 Text that was actually used in the completion.
1169 Text that was actually used in the completion.
1171
1170
1172 matches : list
1171 matches : list
1173 A list of completion matches.
1172 A list of completion matches.
1174 """
1173 """
1175 # if the cursor position isn't given, the only sane assumption we can
1174 # if the cursor position isn't given, the only sane assumption we can
1176 # make is that it's at the end of the line (the common case)
1175 # make is that it's at the end of the line (the common case)
1177 if cursor_pos is None:
1176 if cursor_pos is None:
1178 cursor_pos = len(line_buffer) if text is None else len(text)
1177 cursor_pos = len(line_buffer) if text is None else len(text)
1179
1178
1180 if self.use_main_ns:
1179 if self.use_main_ns:
1181 self.namespace = __main__.__dict__
1180 self.namespace = __main__.__dict__
1182
1181
1183 if PY3:
1182 if PY3:
1184
1183
1185 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1184 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1186 latex_text, latex_matches = self.latex_matches(base_text)
1185 latex_text, latex_matches = self.latex_matches(base_text)
1187 if latex_matches:
1186 if latex_matches:
1188 return latex_text, latex_matches
1187 return latex_text, latex_matches
1189 name_text = ''
1188 name_text = ''
1190 name_matches = []
1189 name_matches = []
1191 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1190 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1192 name_text, name_matches = meth(base_text)
1191 name_text, name_matches = meth(base_text)
1193 if name_text:
1192 if name_text:
1194 return name_text, name_matches
1193 return name_text, name_matches
1195
1194
1196 # if text is either None or an empty string, rely on the line buffer
1195 # if text is either None or an empty string, rely on the line buffer
1197 if not text:
1196 if not text:
1198 text = self.splitter.split_line(line_buffer, cursor_pos)
1197 text = self.splitter.split_line(line_buffer, cursor_pos)
1199
1198
1200 # If no line buffer is given, assume the input text is all there was
1199 # If no line buffer is given, assume the input text is all there was
1201 if line_buffer is None:
1200 if line_buffer is None:
1202 line_buffer = text
1201 line_buffer = text
1203
1202
1204 self.line_buffer = line_buffer
1203 self.line_buffer = line_buffer
1205 self.text_until_cursor = self.line_buffer[:cursor_pos]
1204 self.text_until_cursor = self.line_buffer[:cursor_pos]
1206
1205
1207 # Start with a clean slate of completions
1206 # Start with a clean slate of completions
1208 self.matches[:] = []
1207 self.matches[:] = []
1209 custom_res = self.dispatch_custom_completer(text)
1208 custom_res = self.dispatch_custom_completer(text)
1210 if custom_res is not None:
1209 if custom_res is not None:
1211 # did custom completers produce something?
1210 # did custom completers produce something?
1212 self.matches = custom_res
1211 self.matches = custom_res
1213 else:
1212 else:
1214 # Extend the list of completions with the results of each
1213 # Extend the list of completions with the results of each
1215 # matcher, so we return results to the user from all
1214 # matcher, so we return results to the user from all
1216 # namespaces.
1215 # namespaces.
1217 if self.merge_completions:
1216 if self.merge_completions:
1218 self.matches = []
1217 self.matches = []
1219 for matcher in self.matchers:
1218 for matcher in self.matchers:
1220 try:
1219 try:
1221 self.matches.extend(matcher(text))
1220 self.matches.extend(matcher(text))
1222 except:
1221 except:
1223 # Show the ugly traceback if the matcher causes an
1222 # Show the ugly traceback if the matcher causes an
1224 # exception, but do NOT crash the kernel!
1223 # exception, but do NOT crash the kernel!
1225 sys.excepthook(*sys.exc_info())
1224 sys.excepthook(*sys.exc_info())
1226 else:
1225 else:
1227 for matcher in self.matchers:
1226 for matcher in self.matchers:
1228 self.matches = matcher(text)
1227 self.matches = matcher(text)
1229 if self.matches:
1228 if self.matches:
1230 break
1229 break
1231 # FIXME: we should extend our api to return a dict with completions for
1230 # FIXME: we should extend our api to return a dict with completions for
1232 # different types of objects. The rlcomplete() method could then
1231 # different types of objects. The rlcomplete() method could then
1233 # simply collapse the dict into a list for readline, but we'd have
1232 # simply collapse the dict into a list for readline, but we'd have
1234 # richer completion semantics in other evironments.
1233 # richer completion semantics in other evironments.
1235 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1234 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1236
1235
1237 return text, self.matches
1236 return text, self.matches
@@ -1,349 +1,348 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Implementations for various useful completers.
2 """Implementations for various useful completers.
3
3
4 These are all loaded by default by IPython.
4 These are all loaded by default by IPython.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2010-2011 The IPython Development Team.
7 # Copyright (C) 2010-2011 The IPython Development Team.
8 #
8 #
9 # Distributed under the terms of the BSD License.
9 # Distributed under the terms of the BSD License.
10 #
10 #
11 # The full license is in the file COPYING.txt, distributed with this software.
11 # The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 from __future__ import print_function
18
17
19 # Stdlib imports
18 # Stdlib imports
20 import glob
19 import glob
21 import inspect
20 import inspect
22 import os
21 import os
23 import re
22 import re
24 import sys
23 import sys
25 from importlib import import_module
24 from importlib import import_module
26
25
27 try:
26 try:
28 # Python >= 3.3
27 # Python >= 3.3
29 from importlib.machinery import all_suffixes
28 from importlib.machinery import all_suffixes
30 _suffixes = all_suffixes()
29 _suffixes = all_suffixes()
31 except ImportError:
30 except ImportError:
32 from imp import get_suffixes
31 from imp import get_suffixes
33 _suffixes = [ s[0] for s in get_suffixes() ]
32 _suffixes = [ s[0] for s in get_suffixes() ]
34
33
35 # Third-party imports
34 # Third-party imports
36 from time import time
35 from time import time
37 from zipimport import zipimporter
36 from zipimport import zipimporter
38
37
39 # Our own imports
38 # Our own imports
40 from IPython.core.completer import expand_user, compress_user
39 from IPython.core.completer import expand_user, compress_user
41 from IPython.core.error import TryNext
40 from IPython.core.error import TryNext
42 from IPython.utils._process_common import arg_split
41 from IPython.utils._process_common import arg_split
43 from IPython.utils.py3compat import string_types
42 from IPython.utils.py3compat import string_types
44
43
45 # FIXME: this should be pulled in with the right call via the component system
44 # FIXME: this should be pulled in with the right call via the component system
46 from IPython import get_ipython
45 from IPython import get_ipython
47
46
48 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
49 # Globals and constants
48 # Globals and constants
50 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
51
50
52 # Time in seconds after which the rootmodules will be stored permanently in the
51 # Time in seconds after which the rootmodules will be stored permanently in the
53 # ipython ip.db database (kept in the user's .ipython dir).
52 # ipython ip.db database (kept in the user's .ipython dir).
54 TIMEOUT_STORAGE = 2
53 TIMEOUT_STORAGE = 2
55
54
56 # Time in seconds after which we give up
55 # Time in seconds after which we give up
57 TIMEOUT_GIVEUP = 20
56 TIMEOUT_GIVEUP = 20
58
57
59 # Regular expression for the python import statement
58 # Regular expression for the python import statement
60 import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
59 import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
61 r'(?P<package>[/\\]__init__)?'
60 r'(?P<package>[/\\]__init__)?'
62 r'(?P<suffix>%s)$' %
61 r'(?P<suffix>%s)$' %
63 r'|'.join(re.escape(s) for s in _suffixes))
62 r'|'.join(re.escape(s) for s in _suffixes))
64
63
65 # RE for the ipython %run command (python + ipython scripts)
64 # RE for the ipython %run command (python + ipython scripts)
66 magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
65 magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
67
66
68 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
69 # Local utilities
68 # Local utilities
70 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
71
70
72 def module_list(path):
71 def module_list(path):
73 """
72 """
74 Return the list containing the names of the modules available in the given
73 Return the list containing the names of the modules available in the given
75 folder.
74 folder.
76 """
75 """
77 # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
76 # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
78 if path == '':
77 if path == '':
79 path = '.'
78 path = '.'
80
79
81 # A few local constants to be used in loops below
80 # A few local constants to be used in loops below
82 pjoin = os.path.join
81 pjoin = os.path.join
83
82
84 if os.path.isdir(path):
83 if os.path.isdir(path):
85 # Build a list of all files in the directory and all files
84 # Build a list of all files in the directory and all files
86 # in its subdirectories. For performance reasons, do not
85 # in its subdirectories. For performance reasons, do not
87 # recurse more than one level into subdirectories.
86 # recurse more than one level into subdirectories.
88 files = []
87 files = []
89 for root, dirs, nondirs in os.walk(path, followlinks=True):
88 for root, dirs, nondirs in os.walk(path, followlinks=True):
90 subdir = root[len(path)+1:]
89 subdir = root[len(path)+1:]
91 if subdir:
90 if subdir:
92 files.extend(pjoin(subdir, f) for f in nondirs)
91 files.extend(pjoin(subdir, f) for f in nondirs)
93 dirs[:] = [] # Do not recurse into additional subdirectories.
92 dirs[:] = [] # Do not recurse into additional subdirectories.
94 else:
93 else:
95 files.extend(nondirs)
94 files.extend(nondirs)
96
95
97 else:
96 else:
98 try:
97 try:
99 files = list(zipimporter(path)._files.keys())
98 files = list(zipimporter(path)._files.keys())
100 except:
99 except:
101 files = []
100 files = []
102
101
103 # Build a list of modules which match the import_re regex.
102 # Build a list of modules which match the import_re regex.
104 modules = []
103 modules = []
105 for f in files:
104 for f in files:
106 m = import_re.match(f)
105 m = import_re.match(f)
107 if m:
106 if m:
108 modules.append(m.group('name'))
107 modules.append(m.group('name'))
109 return list(set(modules))
108 return list(set(modules))
110
109
111
110
112 def get_root_modules():
111 def get_root_modules():
113 """
112 """
114 Returns a list containing the names of all the modules available in the
113 Returns a list containing the names of all the modules available in the
115 folders of the pythonpath.
114 folders of the pythonpath.
116
115
117 ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
116 ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
118 """
117 """
119 ip = get_ipython()
118 ip = get_ipython()
120 rootmodules_cache = ip.db.get('rootmodules_cache', {})
119 rootmodules_cache = ip.db.get('rootmodules_cache', {})
121 rootmodules = list(sys.builtin_module_names)
120 rootmodules = list(sys.builtin_module_names)
122 start_time = time()
121 start_time = time()
123 store = False
122 store = False
124 for path in sys.path:
123 for path in sys.path:
125 try:
124 try:
126 modules = rootmodules_cache[path]
125 modules = rootmodules_cache[path]
127 except KeyError:
126 except KeyError:
128 modules = module_list(path)
127 modules = module_list(path)
129 try:
128 try:
130 modules.remove('__init__')
129 modules.remove('__init__')
131 except ValueError:
130 except ValueError:
132 pass
131 pass
133 if path not in ('', '.'): # cwd modules should not be cached
132 if path not in ('', '.'): # cwd modules should not be cached
134 rootmodules_cache[path] = modules
133 rootmodules_cache[path] = modules
135 if time() - start_time > TIMEOUT_STORAGE and not store:
134 if time() - start_time > TIMEOUT_STORAGE and not store:
136 store = True
135 store = True
137 print("\nCaching the list of root modules, please wait!")
136 print("\nCaching the list of root modules, please wait!")
138 print("(This will only be done once - type '%rehashx' to "
137 print("(This will only be done once - type '%rehashx' to "
139 "reset cache!)\n")
138 "reset cache!)\n")
140 sys.stdout.flush()
139 sys.stdout.flush()
141 if time() - start_time > TIMEOUT_GIVEUP:
140 if time() - start_time > TIMEOUT_GIVEUP:
142 print("This is taking too long, we give up.\n")
141 print("This is taking too long, we give up.\n")
143 return []
142 return []
144 rootmodules.extend(modules)
143 rootmodules.extend(modules)
145 if store:
144 if store:
146 ip.db['rootmodules_cache'] = rootmodules_cache
145 ip.db['rootmodules_cache'] = rootmodules_cache
147 rootmodules = list(set(rootmodules))
146 rootmodules = list(set(rootmodules))
148 return rootmodules
147 return rootmodules
149
148
150
149
151 def is_importable(module, attr, only_modules):
150 def is_importable(module, attr, only_modules):
152 if only_modules:
151 if only_modules:
153 return inspect.ismodule(getattr(module, attr))
152 return inspect.ismodule(getattr(module, attr))
154 else:
153 else:
155 return not(attr[:2] == '__' and attr[-2:] == '__')
154 return not(attr[:2] == '__' and attr[-2:] == '__')
156
155
157 def try_import(mod, only_modules=False):
156 def try_import(mod, only_modules=False):
158 try:
157 try:
159 m = import_module(mod)
158 m = import_module(mod)
160 except:
159 except:
161 return []
160 return []
162
161
163 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
162 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
164
163
165 completions = []
164 completions = []
166 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
165 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
167 completions.extend( [attr for attr in dir(m) if
166 completions.extend( [attr for attr in dir(m) if
168 is_importable(m, attr, only_modules)])
167 is_importable(m, attr, only_modules)])
169
168
170 completions.extend(getattr(m, '__all__', []))
169 completions.extend(getattr(m, '__all__', []))
171 if m_is_init:
170 if m_is_init:
172 completions.extend(module_list(os.path.dirname(m.__file__)))
171 completions.extend(module_list(os.path.dirname(m.__file__)))
173 completions = {c for c in completions if isinstance(c, string_types)}
172 completions = {c for c in completions if isinstance(c, string_types)}
174 completions.discard('__init__')
173 completions.discard('__init__')
175 return list(completions)
174 return list(completions)
176
175
177
176
178 #-----------------------------------------------------------------------------
177 #-----------------------------------------------------------------------------
179 # Completion-related functions.
178 # Completion-related functions.
180 #-----------------------------------------------------------------------------
179 #-----------------------------------------------------------------------------
181
180
182 def quick_completer(cmd, completions):
181 def quick_completer(cmd, completions):
183 """ Easily create a trivial completer for a command.
182 """ Easily create a trivial completer for a command.
184
183
185 Takes either a list of completions, or all completions in string (that will
184 Takes either a list of completions, or all completions in string (that will
186 be split on whitespace).
185 be split on whitespace).
187
186
188 Example::
187 Example::
189
188
190 [d:\ipython]|1> import ipy_completers
189 [d:\ipython]|1> import ipy_completers
191 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
190 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
192 [d:\ipython]|3> foo b<TAB>
191 [d:\ipython]|3> foo b<TAB>
193 bar baz
192 bar baz
194 [d:\ipython]|3> foo ba
193 [d:\ipython]|3> foo ba
195 """
194 """
196
195
197 if isinstance(completions, string_types):
196 if isinstance(completions, string_types):
198 completions = completions.split()
197 completions = completions.split()
199
198
200 def do_complete(self, event):
199 def do_complete(self, event):
201 return completions
200 return completions
202
201
203 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
202 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
204
203
205 def module_completion(line):
204 def module_completion(line):
206 """
205 """
207 Returns a list containing the completion possibilities for an import line.
206 Returns a list containing the completion possibilities for an import line.
208
207
209 The line looks like this :
208 The line looks like this :
210 'import xml.d'
209 'import xml.d'
211 'from xml.dom import'
210 'from xml.dom import'
212 """
211 """
213
212
214 words = line.split(' ')
213 words = line.split(' ')
215 nwords = len(words)
214 nwords = len(words)
216
215
217 # from whatever <tab> -> 'import '
216 # from whatever <tab> -> 'import '
218 if nwords == 3 and words[0] == 'from':
217 if nwords == 3 and words[0] == 'from':
219 return ['import ']
218 return ['import ']
220
219
221 # 'from xy<tab>' or 'import xy<tab>'
220 # 'from xy<tab>' or 'import xy<tab>'
222 if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
221 if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
223 if nwords == 1:
222 if nwords == 1:
224 return get_root_modules()
223 return get_root_modules()
225 mod = words[1].split('.')
224 mod = words[1].split('.')
226 if len(mod) < 2:
225 if len(mod) < 2:
227 return get_root_modules()
226 return get_root_modules()
228 completion_list = try_import('.'.join(mod[:-1]), True)
227 completion_list = try_import('.'.join(mod[:-1]), True)
229 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
228 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
230
229
231 # 'from xyz import abc<tab>'
230 # 'from xyz import abc<tab>'
232 if nwords >= 3 and words[0] == 'from':
231 if nwords >= 3 and words[0] == 'from':
233 mod = words[1]
232 mod = words[1]
234 return try_import(mod)
233 return try_import(mod)
235
234
236 #-----------------------------------------------------------------------------
235 #-----------------------------------------------------------------------------
237 # Completers
236 # Completers
238 #-----------------------------------------------------------------------------
237 #-----------------------------------------------------------------------------
239 # These all have the func(self, event) signature to be used as custom
238 # These all have the func(self, event) signature to be used as custom
240 # completers
239 # completers
241
240
242 def module_completer(self,event):
241 def module_completer(self,event):
243 """Give completions after user has typed 'import ...' or 'from ...'"""
242 """Give completions after user has typed 'import ...' or 'from ...'"""
244
243
245 # This works in all versions of python. While 2.5 has
244 # This works in all versions of python. While 2.5 has
246 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
245 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
247 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
246 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
248 # of possibly problematic side effects.
247 # of possibly problematic side effects.
249 # This search the folders in the sys.path for available modules.
248 # This search the folders in the sys.path for available modules.
250
249
251 return module_completion(event.line)
250 return module_completion(event.line)
252
251
253 # FIXME: there's a lot of logic common to the run, cd and builtin file
252 # FIXME: there's a lot of logic common to the run, cd and builtin file
254 # completers, that is currently reimplemented in each.
253 # completers, that is currently reimplemented in each.
255
254
256 def magic_run_completer(self, event):
255 def magic_run_completer(self, event):
257 """Complete files that end in .py or .ipy or .ipynb for the %run command.
256 """Complete files that end in .py or .ipy or .ipynb for the %run command.
258 """
257 """
259 comps = arg_split(event.line, strict=False)
258 comps = arg_split(event.line, strict=False)
260 # relpath should be the current token that we need to complete.
259 # relpath should be the current token that we need to complete.
261 if (len(comps) > 1) and (not event.line.endswith(' ')):
260 if (len(comps) > 1) and (not event.line.endswith(' ')):
262 relpath = comps[-1].strip("'\"")
261 relpath = comps[-1].strip("'\"")
263 else:
262 else:
264 relpath = ''
263 relpath = ''
265
264
266 #print("\nev=", event) # dbg
265 #print("\nev=", event) # dbg
267 #print("rp=", relpath) # dbg
266 #print("rp=", relpath) # dbg
268 #print('comps=', comps) # dbg
267 #print('comps=', comps) # dbg
269
268
270 lglob = glob.glob
269 lglob = glob.glob
271 isdir = os.path.isdir
270 isdir = os.path.isdir
272 relpath, tilde_expand, tilde_val = expand_user(relpath)
271 relpath, tilde_expand, tilde_val = expand_user(relpath)
273
272
274 # Find if the user has already typed the first filename, after which we
273 # Find if the user has already typed the first filename, after which we
275 # should complete on all files, since after the first one other files may
274 # should complete on all files, since after the first one other files may
276 # be arguments to the input script.
275 # be arguments to the input script.
277
276
278 if any(magic_run_re.match(c) for c in comps):
277 if any(magic_run_re.match(c) for c in comps):
279 matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
278 matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
280 for f in lglob(relpath+'*')]
279 for f in lglob(relpath+'*')]
281 else:
280 else:
282 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
281 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
283 pys = [f.replace('\\','/')
282 pys = [f.replace('\\','/')
284 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
283 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
285 lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
284 lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
286
285
287 matches = dirs + pys
286 matches = dirs + pys
288
287
289 #print('run comp:', dirs+pys) # dbg
288 #print('run comp:', dirs+pys) # dbg
290 return [compress_user(p, tilde_expand, tilde_val) for p in matches]
289 return [compress_user(p, tilde_expand, tilde_val) for p in matches]
291
290
292
291
293 def cd_completer(self, event):
292 def cd_completer(self, event):
294 """Completer function for cd, which only returns directories."""
293 """Completer function for cd, which only returns directories."""
295 ip = get_ipython()
294 ip = get_ipython()
296 relpath = event.symbol
295 relpath = event.symbol
297
296
298 #print(event) # dbg
297 #print(event) # dbg
299 if event.line.endswith('-b') or ' -b ' in event.line:
298 if event.line.endswith('-b') or ' -b ' in event.line:
300 # return only bookmark completions
299 # return only bookmark completions
301 bkms = self.db.get('bookmarks', None)
300 bkms = self.db.get('bookmarks', None)
302 if bkms:
301 if bkms:
303 return bkms.keys()
302 return bkms.keys()
304 else:
303 else:
305 return []
304 return []
306
305
307 if event.symbol == '-':
306 if event.symbol == '-':
308 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
307 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
309 # jump in directory history by number
308 # jump in directory history by number
310 fmt = '-%0' + width_dh +'d [%s]'
309 fmt = '-%0' + width_dh +'d [%s]'
311 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
310 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
312 if len(ents) > 1:
311 if len(ents) > 1:
313 return ents
312 return ents
314 return []
313 return []
315
314
316 if event.symbol.startswith('--'):
315 if event.symbol.startswith('--'):
317 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
316 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
318
317
319 # Expand ~ in path and normalize directory separators.
318 # Expand ~ in path and normalize directory separators.
320 relpath, tilde_expand, tilde_val = expand_user(relpath)
319 relpath, tilde_expand, tilde_val = expand_user(relpath)
321 relpath = relpath.replace('\\','/')
320 relpath = relpath.replace('\\','/')
322
321
323 found = []
322 found = []
324 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
323 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
325 if os.path.isdir(f)]:
324 if os.path.isdir(f)]:
326 if ' ' in d:
325 if ' ' in d:
327 # we don't want to deal with any of that, complex code
326 # we don't want to deal with any of that, complex code
328 # for this is elsewhere
327 # for this is elsewhere
329 raise TryNext
328 raise TryNext
330
329
331 found.append(d)
330 found.append(d)
332
331
333 if not found:
332 if not found:
334 if os.path.isdir(relpath):
333 if os.path.isdir(relpath):
335 return [compress_user(relpath, tilde_expand, tilde_val)]
334 return [compress_user(relpath, tilde_expand, tilde_val)]
336
335
337 # if no completions so far, try bookmarks
336 # if no completions so far, try bookmarks
338 bks = self.db.get('bookmarks',{})
337 bks = self.db.get('bookmarks',{})
339 bkmatches = [s for s in bks if s.startswith(event.symbol)]
338 bkmatches = [s for s in bks if s.startswith(event.symbol)]
340 if bkmatches:
339 if bkmatches:
341 return bkmatches
340 return bkmatches
342
341
343 raise TryNext
342 raise TryNext
344
343
345 return [compress_user(p, tilde_expand, tilde_val) for p in found]
344 return [compress_user(p, tilde_expand, tilde_val) for p in found]
346
345
347 def reset_completer(self, event):
346 def reset_completer(self, event):
348 "A completer for %reset magic"
347 "A completer for %reset magic"
349 return '-f -s in out array dhist'.split()
348 return '-f -s in out array dhist'.split()
@@ -1,216 +1,215 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
3
4 Authors:
4 Authors:
5
5
6 * Fernando Perez
6 * Fernando Perez
7 * Brian E. Granger
7 * Brian E. Granger
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2008-2011 The IPython Development Team
12 # Copyright (C) 2008-2011 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 from __future__ import print_function
22
21
23 import os
22 import os
24 import sys
23 import sys
25 import traceback
24 import traceback
26 from pprint import pformat
25 from pprint import pformat
27
26
28 from IPython.core import ultratb
27 from IPython.core import ultratb
29 from IPython.core.release import author_email
28 from IPython.core.release import author_email
30 from IPython.utils.sysinfo import sys_info
29 from IPython.utils.sysinfo import sys_info
31 from IPython.utils.py3compat import input, getcwd
30 from IPython.utils.py3compat import input, getcwd
32
31
33 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
34 # Code
33 # Code
35 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
36
35
37 # Template for the user message.
36 # Template for the user message.
38 _default_message_template = """\
37 _default_message_template = """\
39 Oops, {app_name} crashed. We do our best to make it stable, but...
38 Oops, {app_name} crashed. We do our best to make it stable, but...
40
39
41 A crash report was automatically generated with the following information:
40 A crash report was automatically generated with the following information:
42 - A verbatim copy of the crash traceback.
41 - A verbatim copy of the crash traceback.
43 - A copy of your input history during this session.
42 - A copy of your input history during this session.
44 - Data on your current {app_name} configuration.
43 - Data on your current {app_name} configuration.
45
44
46 It was left in the file named:
45 It was left in the file named:
47 \t'{crash_report_fname}'
46 \t'{crash_report_fname}'
48 If you can email this file to the developers, the information in it will help
47 If you can email this file to the developers, the information in it will help
49 them in understanding and correcting the problem.
48 them in understanding and correcting the problem.
50
49
51 You can mail it to: {contact_name} at {contact_email}
50 You can mail it to: {contact_name} at {contact_email}
52 with the subject '{app_name} Crash Report'.
51 with the subject '{app_name} Crash Report'.
53
52
54 If you want to do it now, the following command will work (under Unix):
53 If you want to do it now, the following command will work (under Unix):
55 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
54 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
56
55
57 To ensure accurate tracking of this issue, please file a report about it at:
56 To ensure accurate tracking of this issue, please file a report about it at:
58 {bug_tracker}
57 {bug_tracker}
59 """
58 """
60
59
61 _lite_message_template = """
60 _lite_message_template = """
62 If you suspect this is an IPython bug, please report it at:
61 If you suspect this is an IPython bug, please report it at:
63 https://github.com/ipython/ipython/issues
62 https://github.com/ipython/ipython/issues
64 or send an email to the mailing list at {email}
63 or send an email to the mailing list at {email}
65
64
66 You can print a more detailed traceback right now with "%tb", or use "%debug"
65 You can print a more detailed traceback right now with "%tb", or use "%debug"
67 to interactively debug it.
66 to interactively debug it.
68
67
69 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
68 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
70 {config}Application.verbose_crash=True
69 {config}Application.verbose_crash=True
71 """
70 """
72
71
73
72
74 class CrashHandler(object):
73 class CrashHandler(object):
75 """Customizable crash handlers for IPython applications.
74 """Customizable crash handlers for IPython applications.
76
75
77 Instances of this class provide a :meth:`__call__` method which can be
76 Instances of this class provide a :meth:`__call__` method which can be
78 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
77 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
79
78
80 def __call__(self, etype, evalue, etb)
79 def __call__(self, etype, evalue, etb)
81 """
80 """
82
81
83 message_template = _default_message_template
82 message_template = _default_message_template
84 section_sep = '\n\n'+'*'*75+'\n\n'
83 section_sep = '\n\n'+'*'*75+'\n\n'
85
84
86 def __init__(self, app, contact_name=None, contact_email=None,
85 def __init__(self, app, contact_name=None, contact_email=None,
87 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
86 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
88 """Create a new crash handler
87 """Create a new crash handler
89
88
90 Parameters
89 Parameters
91 ----------
90 ----------
92 app : Application
91 app : Application
93 A running :class:`Application` instance, which will be queried at
92 A running :class:`Application` instance, which will be queried at
94 crash time for internal information.
93 crash time for internal information.
95
94
96 contact_name : str
95 contact_name : str
97 A string with the name of the person to contact.
96 A string with the name of the person to contact.
98
97
99 contact_email : str
98 contact_email : str
100 A string with the email address of the contact.
99 A string with the email address of the contact.
101
100
102 bug_tracker : str
101 bug_tracker : str
103 A string with the URL for your project's bug tracker.
102 A string with the URL for your project's bug tracker.
104
103
105 show_crash_traceback : bool
104 show_crash_traceback : bool
106 If false, don't print the crash traceback on stderr, only generate
105 If false, don't print the crash traceback on stderr, only generate
107 the on-disk report
106 the on-disk report
108
107
109 Non-argument instance attributes:
108 Non-argument instance attributes:
110
109
111 These instances contain some non-argument attributes which allow for
110 These instances contain some non-argument attributes which allow for
112 further customization of the crash handler's behavior. Please see the
111 further customization of the crash handler's behavior. Please see the
113 source for further details.
112 source for further details.
114 """
113 """
115 self.crash_report_fname = "Crash_report_%s.txt" % app.name
114 self.crash_report_fname = "Crash_report_%s.txt" % app.name
116 self.app = app
115 self.app = app
117 self.call_pdb = call_pdb
116 self.call_pdb = call_pdb
118 #self.call_pdb = True # dbg
117 #self.call_pdb = True # dbg
119 self.show_crash_traceback = show_crash_traceback
118 self.show_crash_traceback = show_crash_traceback
120 self.info = dict(app_name = app.name,
119 self.info = dict(app_name = app.name,
121 contact_name = contact_name,
120 contact_name = contact_name,
122 contact_email = contact_email,
121 contact_email = contact_email,
123 bug_tracker = bug_tracker,
122 bug_tracker = bug_tracker,
124 crash_report_fname = self.crash_report_fname)
123 crash_report_fname = self.crash_report_fname)
125
124
126
125
127 def __call__(self, etype, evalue, etb):
126 def __call__(self, etype, evalue, etb):
128 """Handle an exception, call for compatible with sys.excepthook"""
127 """Handle an exception, call for compatible with sys.excepthook"""
129
128
130 # do not allow the crash handler to be called twice without reinstalling it
129 # do not allow the crash handler to be called twice without reinstalling it
131 # this prevents unlikely errors in the crash handling from entering an
130 # this prevents unlikely errors in the crash handling from entering an
132 # infinite loop.
131 # infinite loop.
133 sys.excepthook = sys.__excepthook__
132 sys.excepthook = sys.__excepthook__
134
133
135 # Report tracebacks shouldn't use color in general (safer for users)
134 # Report tracebacks shouldn't use color in general (safer for users)
136 color_scheme = 'NoColor'
135 color_scheme = 'NoColor'
137
136
138 # Use this ONLY for developer debugging (keep commented out for release)
137 # Use this ONLY for developer debugging (keep commented out for release)
139 #color_scheme = 'Linux' # dbg
138 #color_scheme = 'Linux' # dbg
140 try:
139 try:
141 rptdir = self.app.ipython_dir
140 rptdir = self.app.ipython_dir
142 except:
141 except:
143 rptdir = getcwd()
142 rptdir = getcwd()
144 if rptdir is None or not os.path.isdir(rptdir):
143 if rptdir is None or not os.path.isdir(rptdir):
145 rptdir = getcwd()
144 rptdir = getcwd()
146 report_name = os.path.join(rptdir,self.crash_report_fname)
145 report_name = os.path.join(rptdir,self.crash_report_fname)
147 # write the report filename into the instance dict so it can get
146 # write the report filename into the instance dict so it can get
148 # properly expanded out in the user message template
147 # properly expanded out in the user message template
149 self.crash_report_fname = report_name
148 self.crash_report_fname = report_name
150 self.info['crash_report_fname'] = report_name
149 self.info['crash_report_fname'] = report_name
151 TBhandler = ultratb.VerboseTB(
150 TBhandler = ultratb.VerboseTB(
152 color_scheme=color_scheme,
151 color_scheme=color_scheme,
153 long_header=1,
152 long_header=1,
154 call_pdb=self.call_pdb,
153 call_pdb=self.call_pdb,
155 )
154 )
156 if self.call_pdb:
155 if self.call_pdb:
157 TBhandler(etype,evalue,etb)
156 TBhandler(etype,evalue,etb)
158 return
157 return
159 else:
158 else:
160 traceback = TBhandler.text(etype,evalue,etb,context=31)
159 traceback = TBhandler.text(etype,evalue,etb,context=31)
161
160
162 # print traceback to screen
161 # print traceback to screen
163 if self.show_crash_traceback:
162 if self.show_crash_traceback:
164 print(traceback, file=sys.stderr)
163 print(traceback, file=sys.stderr)
165
164
166 # and generate a complete report on disk
165 # and generate a complete report on disk
167 try:
166 try:
168 report = open(report_name,'w')
167 report = open(report_name,'w')
169 except:
168 except:
170 print('Could not create crash report on disk.', file=sys.stderr)
169 print('Could not create crash report on disk.', file=sys.stderr)
171 return
170 return
172
171
173 # Inform user on stderr of what happened
172 # Inform user on stderr of what happened
174 print('\n'+'*'*70+'\n', file=sys.stderr)
173 print('\n'+'*'*70+'\n', file=sys.stderr)
175 print(self.message_template.format(**self.info), file=sys.stderr)
174 print(self.message_template.format(**self.info), file=sys.stderr)
176
175
177 # Construct report on disk
176 # Construct report on disk
178 report.write(self.make_report(traceback))
177 report.write(self.make_report(traceback))
179 report.close()
178 report.close()
180 input("Hit <Enter> to quit (your terminal may close):")
179 input("Hit <Enter> to quit (your terminal may close):")
181
180
182 def make_report(self,traceback):
181 def make_report(self,traceback):
183 """Return a string containing a crash report."""
182 """Return a string containing a crash report."""
184
183
185 sec_sep = self.section_sep
184 sec_sep = self.section_sep
186
185
187 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
186 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
188 rpt_add = report.append
187 rpt_add = report.append
189 rpt_add(sys_info())
188 rpt_add(sys_info())
190
189
191 try:
190 try:
192 config = pformat(self.app.config)
191 config = pformat(self.app.config)
193 rpt_add(sec_sep)
192 rpt_add(sec_sep)
194 rpt_add('Application name: %s\n\n' % self.app_name)
193 rpt_add('Application name: %s\n\n' % self.app_name)
195 rpt_add('Current user configuration structure:\n\n')
194 rpt_add('Current user configuration structure:\n\n')
196 rpt_add(config)
195 rpt_add(config)
197 except:
196 except:
198 pass
197 pass
199 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
198 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
200
199
201 return ''.join(report)
200 return ''.join(report)
202
201
203
202
204 def crash_handler_lite(etype, evalue, tb):
203 def crash_handler_lite(etype, evalue, tb):
205 """a light excepthook, adding a small message to the usual traceback"""
204 """a light excepthook, adding a small message to the usual traceback"""
206 traceback.print_exception(etype, evalue, tb)
205 traceback.print_exception(etype, evalue, tb)
207
206
208 from IPython.core.interactiveshell import InteractiveShell
207 from IPython.core.interactiveshell import InteractiveShell
209 if InteractiveShell.initialized():
208 if InteractiveShell.initialized():
210 # we are in a Shell environment, give %magic example
209 # we are in a Shell environment, give %magic example
211 config = "%config "
210 config = "%config "
212 else:
211 else:
213 # we are not in a shell, show generic config
212 # we are not in a shell, show generic config
214 config = "c."
213 config = "c."
215 print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
214 print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
216
215
@@ -1,630 +1,629 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 http://www.python.org/2.2.3/license.html"""
16 http://www.python.org/2.2.3/license.html"""
17
17
18 #*****************************************************************************
18 #*****************************************************************************
19 #
19 #
20 # This file is licensed under the PSF license.
20 # This file is licensed under the PSF license.
21 #
21 #
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 #
24 #
25 #
25 #
26 #*****************************************************************************
26 #*****************************************************************************
27 from __future__ import print_function
28
27
29 import bdb
28 import bdb
30 import functools
29 import functools
31 import inspect
30 import inspect
32 import sys
31 import sys
33 import warnings
32 import warnings
34
33
35 from IPython import get_ipython
34 from IPython import get_ipython
36 from IPython.utils import PyColorize, ulinecache
35 from IPython.utils import PyColorize, ulinecache
37 from IPython.utils import coloransi, py3compat
36 from IPython.utils import coloransi, py3compat
38 from IPython.core.excolors import exception_colors
37 from IPython.core.excolors import exception_colors
39 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.testing.skipdoctest import skip_doctest
40
39
41
40
42 prompt = 'ipdb> '
41 prompt = 'ipdb> '
43
42
44 #We have to check this directly from sys.argv, config struct not yet available
43 #We have to check this directly from sys.argv, config struct not yet available
45 from pdb import Pdb as OldPdb
44 from pdb import Pdb as OldPdb
46
45
47 # Allow the set_trace code to operate outside of an ipython instance, even if
46 # Allow the set_trace code to operate outside of an ipython instance, even if
48 # it does so with some limitations. The rest of this support is implemented in
47 # it does so with some limitations. The rest of this support is implemented in
49 # the Tracer constructor.
48 # the Tracer constructor.
50
49
51 def make_arrow(pad):
50 def make_arrow(pad):
52 """generate the leading arrow in front of traceback or debugger"""
51 """generate the leading arrow in front of traceback or debugger"""
53 if pad >= 2:
52 if pad >= 2:
54 return '-'*(pad-2) + '> '
53 return '-'*(pad-2) + '> '
55 elif pad == 1:
54 elif pad == 1:
56 return '>'
55 return '>'
57 return ''
56 return ''
58
57
59
58
60 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
59 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
61 """Exception hook which handles `BdbQuit` exceptions.
60 """Exception hook which handles `BdbQuit` exceptions.
62
61
63 All other exceptions are processed using the `excepthook`
62 All other exceptions are processed using the `excepthook`
64 parameter.
63 parameter.
65 """
64 """
66 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
65 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
67 DeprecationWarning)
66 DeprecationWarning)
68 if et==bdb.BdbQuit:
67 if et==bdb.BdbQuit:
69 print('Exiting Debugger.')
68 print('Exiting Debugger.')
70 elif excepthook is not None:
69 elif excepthook is not None:
71 excepthook(et, ev, tb)
70 excepthook(et, ev, tb)
72 else:
71 else:
73 # Backwards compatibility. Raise deprecation warning?
72 # Backwards compatibility. Raise deprecation warning?
74 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
73 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
75
74
76
75
77 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
76 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
78 warnings.warn(
77 warnings.warn(
79 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
78 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
80 DeprecationWarning)
79 DeprecationWarning)
81 print('Exiting Debugger.')
80 print('Exiting Debugger.')
82
81
83
82
84 class Tracer(object):
83 class Tracer(object):
85 """
84 """
86 DEPRECATED
85 DEPRECATED
87
86
88 Class for local debugging, similar to pdb.set_trace.
87 Class for local debugging, similar to pdb.set_trace.
89
88
90 Instances of this class, when called, behave like pdb.set_trace, but
89 Instances of this class, when called, behave like pdb.set_trace, but
91 providing IPython's enhanced capabilities.
90 providing IPython's enhanced capabilities.
92
91
93 This is implemented as a class which must be initialized in your own code
92 This is implemented as a class which must be initialized in your own code
94 and not as a standalone function because we need to detect at runtime
93 and not as a standalone function because we need to detect at runtime
95 whether IPython is already active or not. That detection is done in the
94 whether IPython is already active or not. That detection is done in the
96 constructor, ensuring that this code plays nicely with a running IPython,
95 constructor, ensuring that this code plays nicely with a running IPython,
97 while functioning acceptably (though with limitations) if outside of it.
96 while functioning acceptably (though with limitations) if outside of it.
98 """
97 """
99
98
100 @skip_doctest
99 @skip_doctest
101 def __init__(self, colors=None):
100 def __init__(self, colors=None):
102 """
101 """
103 DEPRECATED
102 DEPRECATED
104
103
105 Create a local debugger instance.
104 Create a local debugger instance.
106
105
107 Parameters
106 Parameters
108 ----------
107 ----------
109
108
110 colors : str, optional
109 colors : str, optional
111 The name of the color scheme to use, it must be one of IPython's
110 The name of the color scheme to use, it must be one of IPython's
112 valid color schemes. If not given, the function will default to
111 valid color schemes. If not given, the function will default to
113 the current IPython scheme when running inside IPython, and to
112 the current IPython scheme when running inside IPython, and to
114 'NoColor' otherwise.
113 'NoColor' otherwise.
115
114
116 Examples
115 Examples
117 --------
116 --------
118 ::
117 ::
119
118
120 from IPython.core.debugger import Tracer; debug_here = Tracer()
119 from IPython.core.debugger import Tracer; debug_here = Tracer()
121
120
122 Later in your code::
121 Later in your code::
123
122
124 debug_here() # -> will open up the debugger at that point.
123 debug_here() # -> will open up the debugger at that point.
125
124
126 Once the debugger activates, you can use all of its regular commands to
125 Once the debugger activates, you can use all of its regular commands to
127 step through code, set breakpoints, etc. See the pdb documentation
126 step through code, set breakpoints, etc. See the pdb documentation
128 from the Python standard library for usage details.
127 from the Python standard library for usage details.
129 """
128 """
130 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
129 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
131 "`IPython.core.debugger.Pdb.set_trace()`",
130 "`IPython.core.debugger.Pdb.set_trace()`",
132 DeprecationWarning)
131 DeprecationWarning)
133
132
134 ip = get_ipython()
133 ip = get_ipython()
135 if ip is None:
134 if ip is None:
136 # Outside of ipython, we set our own exception hook manually
135 # Outside of ipython, we set our own exception hook manually
137 sys.excepthook = functools.partial(BdbQuit_excepthook,
136 sys.excepthook = functools.partial(BdbQuit_excepthook,
138 excepthook=sys.excepthook)
137 excepthook=sys.excepthook)
139 def_colors = 'NoColor'
138 def_colors = 'NoColor'
140 else:
139 else:
141 # In ipython, we use its custom exception handler mechanism
140 # In ipython, we use its custom exception handler mechanism
142 def_colors = ip.colors
141 def_colors = ip.colors
143 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
142 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
144
143
145 if colors is None:
144 if colors is None:
146 colors = def_colors
145 colors = def_colors
147
146
148 # The stdlib debugger internally uses a modified repr from the `repr`
147 # The stdlib debugger internally uses a modified repr from the `repr`
149 # module, that limits the length of printed strings to a hardcoded
148 # module, that limits the length of printed strings to a hardcoded
150 # limit of 30 characters. That much trimming is too aggressive, let's
149 # limit of 30 characters. That much trimming is too aggressive, let's
151 # at least raise that limit to 80 chars, which should be enough for
150 # at least raise that limit to 80 chars, which should be enough for
152 # most interactive uses.
151 # most interactive uses.
153 try:
152 try:
154 try:
153 try:
155 from reprlib import aRepr # Py 3
154 from reprlib import aRepr # Py 3
156 except ImportError:
155 except ImportError:
157 from repr import aRepr # Py 2
156 from repr import aRepr # Py 2
158 aRepr.maxstring = 80
157 aRepr.maxstring = 80
159 except:
158 except:
160 # This is only a user-facing convenience, so any error we encounter
159 # This is only a user-facing convenience, so any error we encounter
161 # here can be warned about but can be otherwise ignored. These
160 # here can be warned about but can be otherwise ignored. These
162 # printouts will tell us about problems if this API changes
161 # printouts will tell us about problems if this API changes
163 import traceback
162 import traceback
164 traceback.print_exc()
163 traceback.print_exc()
165
164
166 self.debugger = Pdb(colors)
165 self.debugger = Pdb(colors)
167
166
168 def __call__(self):
167 def __call__(self):
169 """Starts an interactive debugger at the point where called.
168 """Starts an interactive debugger at the point where called.
170
169
171 This is similar to the pdb.set_trace() function from the std lib, but
170 This is similar to the pdb.set_trace() function from the std lib, but
172 using IPython's enhanced debugger."""
171 using IPython's enhanced debugger."""
173
172
174 self.debugger.set_trace(sys._getframe().f_back)
173 self.debugger.set_trace(sys._getframe().f_back)
175
174
176
175
177 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
176 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
178 """Make new_fn have old_fn's doc string. This is particularly useful
177 """Make new_fn have old_fn's doc string. This is particularly useful
179 for the ``do_...`` commands that hook into the help system.
178 for the ``do_...`` commands that hook into the help system.
180 Adapted from from a comp.lang.python posting
179 Adapted from from a comp.lang.python posting
181 by Duncan Booth."""
180 by Duncan Booth."""
182 def wrapper(*args, **kw):
181 def wrapper(*args, **kw):
183 return new_fn(*args, **kw)
182 return new_fn(*args, **kw)
184 if old_fn.__doc__:
183 if old_fn.__doc__:
185 wrapper.__doc__ = old_fn.__doc__ + additional_text
184 wrapper.__doc__ = old_fn.__doc__ + additional_text
186 return wrapper
185 return wrapper
187
186
188
187
189 def _file_lines(fname):
188 def _file_lines(fname):
190 """Return the contents of a named file as a list of lines.
189 """Return the contents of a named file as a list of lines.
191
190
192 This function never raises an IOError exception: if the file can't be
191 This function never raises an IOError exception: if the file can't be
193 read, it simply returns an empty list."""
192 read, it simply returns an empty list."""
194
193
195 try:
194 try:
196 outfile = open(fname)
195 outfile = open(fname)
197 except IOError:
196 except IOError:
198 return []
197 return []
199 else:
198 else:
200 out = outfile.readlines()
199 out = outfile.readlines()
201 outfile.close()
200 outfile.close()
202 return out
201 return out
203
202
204
203
205 class Pdb(OldPdb, object):
204 class Pdb(OldPdb, object):
206 """Modified Pdb class, does not load readline.
205 """Modified Pdb class, does not load readline.
207
206
208 for a standalone version that uses prompt_toolkit, see
207 for a standalone version that uses prompt_toolkit, see
209 `IPython.terminal.debugger.TerminalPdb` and
208 `IPython.terminal.debugger.TerminalPdb` and
210 `IPython.terminal.debugger.set_trace()`
209 `IPython.terminal.debugger.set_trace()`
211 """
210 """
212
211
213 def __init__(self, color_scheme=None, completekey=None,
212 def __init__(self, color_scheme=None, completekey=None,
214 stdin=None, stdout=None, context=5):
213 stdin=None, stdout=None, context=5):
215
214
216 # Parent constructor:
215 # Parent constructor:
217 try:
216 try:
218 self.context = int(context)
217 self.context = int(context)
219 if self.context <= 0:
218 if self.context <= 0:
220 raise ValueError("Context must be a positive integer")
219 raise ValueError("Context must be a positive integer")
221 except (TypeError, ValueError):
220 except (TypeError, ValueError):
222 raise ValueError("Context must be a positive integer")
221 raise ValueError("Context must be a positive integer")
223
222
224 OldPdb.__init__(self, completekey, stdin, stdout)
223 OldPdb.__init__(self, completekey, stdin, stdout)
225
224
226 # IPython changes...
225 # IPython changes...
227 self.shell = get_ipython()
226 self.shell = get_ipython()
228
227
229 if self.shell is None:
228 if self.shell is None:
230 save_main = sys.modules['__main__']
229 save_main = sys.modules['__main__']
231 # No IPython instance running, we must create one
230 # No IPython instance running, we must create one
232 from IPython.terminal.interactiveshell import \
231 from IPython.terminal.interactiveshell import \
233 TerminalInteractiveShell
232 TerminalInteractiveShell
234 self.shell = TerminalInteractiveShell.instance()
233 self.shell = TerminalInteractiveShell.instance()
235 # needed by any code which calls __import__("__main__") after
234 # needed by any code which calls __import__("__main__") after
236 # the debugger was entered. See also #9941.
235 # the debugger was entered. See also #9941.
237 sys.modules['__main__'] = save_main
236 sys.modules['__main__'] = save_main
238
237
239 if color_scheme is not None:
238 if color_scheme is not None:
240 warnings.warn(
239 warnings.warn(
241 "The `color_scheme` argument is deprecated since version 5.1",
240 "The `color_scheme` argument is deprecated since version 5.1",
242 DeprecationWarning, stacklevel=2)
241 DeprecationWarning, stacklevel=2)
243 else:
242 else:
244 color_scheme = self.shell.colors
243 color_scheme = self.shell.colors
245
244
246 self.aliases = {}
245 self.aliases = {}
247
246
248 # Create color table: we copy the default one from the traceback
247 # Create color table: we copy the default one from the traceback
249 # module and add a few attributes needed for debugging
248 # module and add a few attributes needed for debugging
250 self.color_scheme_table = exception_colors()
249 self.color_scheme_table = exception_colors()
251
250
252 # shorthands
251 # shorthands
253 C = coloransi.TermColors
252 C = coloransi.TermColors
254 cst = self.color_scheme_table
253 cst = self.color_scheme_table
255
254
256 cst['NoColor'].colors.prompt = C.NoColor
255 cst['NoColor'].colors.prompt = C.NoColor
257 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
256 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
258 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
257 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
259
258
260 cst['Linux'].colors.prompt = C.Green
259 cst['Linux'].colors.prompt = C.Green
261 cst['Linux'].colors.breakpoint_enabled = C.LightRed
260 cst['Linux'].colors.breakpoint_enabled = C.LightRed
262 cst['Linux'].colors.breakpoint_disabled = C.Red
261 cst['Linux'].colors.breakpoint_disabled = C.Red
263
262
264 cst['LightBG'].colors.prompt = C.Blue
263 cst['LightBG'].colors.prompt = C.Blue
265 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
264 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
266 cst['LightBG'].colors.breakpoint_disabled = C.Red
265 cst['LightBG'].colors.breakpoint_disabled = C.Red
267
266
268 cst['Neutral'].colors.prompt = C.Blue
267 cst['Neutral'].colors.prompt = C.Blue
269 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
268 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
270 cst['Neutral'].colors.breakpoint_disabled = C.Red
269 cst['Neutral'].colors.breakpoint_disabled = C.Red
271
270
272
271
273 # Add a python parser so we can syntax highlight source while
272 # Add a python parser so we can syntax highlight source while
274 # debugging.
273 # debugging.
275 self.parser = PyColorize.Parser(style=color_scheme)
274 self.parser = PyColorize.Parser(style=color_scheme)
276 self.set_colors(color_scheme)
275 self.set_colors(color_scheme)
277
276
278 # Set the prompt - the default prompt is '(Pdb)'
277 # Set the prompt - the default prompt is '(Pdb)'
279 self.prompt = prompt
278 self.prompt = prompt
280
279
281 def set_colors(self, scheme):
280 def set_colors(self, scheme):
282 """Shorthand access to the color table scheme selector method."""
281 """Shorthand access to the color table scheme selector method."""
283 self.color_scheme_table.set_active_scheme(scheme)
282 self.color_scheme_table.set_active_scheme(scheme)
284 self.parser.style = scheme
283 self.parser.style = scheme
285
284
286 def interaction(self, frame, traceback):
285 def interaction(self, frame, traceback):
287 try:
286 try:
288 OldPdb.interaction(self, frame, traceback)
287 OldPdb.interaction(self, frame, traceback)
289 except KeyboardInterrupt:
288 except KeyboardInterrupt:
290 sys.stdout.write('\n' + self.shell.get_exception_only())
289 sys.stdout.write('\n' + self.shell.get_exception_only())
291
290
292 def parseline(self, line):
291 def parseline(self, line):
293 if line.startswith("!!"):
292 if line.startswith("!!"):
294 # Force standard behavior.
293 # Force standard behavior.
295 return super(Pdb, self).parseline(line[2:])
294 return super(Pdb, self).parseline(line[2:])
296 # "Smart command mode" from pdb++: don't execute commands if a variable
295 # "Smart command mode" from pdb++: don't execute commands if a variable
297 # with the same name exists.
296 # with the same name exists.
298 cmd, arg, newline = super(Pdb, self).parseline(line)
297 cmd, arg, newline = super(Pdb, self).parseline(line)
299 # Fix for #9611: Do not trigger smart command if the command is `exit`
298 # Fix for #9611: Do not trigger smart command if the command is `exit`
300 # or `quit` and it would resolve to their *global* value (the
299 # or `quit` and it would resolve to their *global* value (the
301 # `ExitAutocall` object). Just checking that it is not present in the
300 # `ExitAutocall` object). Just checking that it is not present in the
302 # locals dict is not enough as locals and globals match at the
301 # locals dict is not enough as locals and globals match at the
303 # toplevel.
302 # toplevel.
304 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
303 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
305 and not (cmd in ["exit", "quit"]
304 and not (cmd in ["exit", "quit"]
306 and (self.curframe.f_locals is self.curframe.f_globals
305 and (self.curframe.f_locals is self.curframe.f_globals
307 or cmd not in self.curframe.f_locals))):
306 or cmd not in self.curframe.f_locals))):
308 return super(Pdb, self).parseline("!" + line)
307 return super(Pdb, self).parseline("!" + line)
309 return super(Pdb, self).parseline(line)
308 return super(Pdb, self).parseline(line)
310
309
311 def new_do_up(self, arg):
310 def new_do_up(self, arg):
312 OldPdb.do_up(self, arg)
311 OldPdb.do_up(self, arg)
313 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
312 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
314
313
315 def new_do_down(self, arg):
314 def new_do_down(self, arg):
316 OldPdb.do_down(self, arg)
315 OldPdb.do_down(self, arg)
317
316
318 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
317 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
319
318
320 def new_do_frame(self, arg):
319 def new_do_frame(self, arg):
321 OldPdb.do_frame(self, arg)
320 OldPdb.do_frame(self, arg)
322
321
323 def new_do_quit(self, arg):
322 def new_do_quit(self, arg):
324
323
325 if hasattr(self, 'old_all_completions'):
324 if hasattr(self, 'old_all_completions'):
326 self.shell.Completer.all_completions=self.old_all_completions
325 self.shell.Completer.all_completions=self.old_all_completions
327
326
328 return OldPdb.do_quit(self, arg)
327 return OldPdb.do_quit(self, arg)
329
328
330 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
329 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
331
330
332 def new_do_restart(self, arg):
331 def new_do_restart(self, arg):
333 """Restart command. In the context of ipython this is exactly the same
332 """Restart command. In the context of ipython this is exactly the same
334 thing as 'quit'."""
333 thing as 'quit'."""
335 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
334 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
336 return self.do_quit(arg)
335 return self.do_quit(arg)
337
336
338 def print_stack_trace(self, context=None):
337 def print_stack_trace(self, context=None):
339 if context is None:
338 if context is None:
340 context = self.context
339 context = self.context
341 try:
340 try:
342 context=int(context)
341 context=int(context)
343 if context <= 0:
342 if context <= 0:
344 raise ValueError("Context must be a positive integer")
343 raise ValueError("Context must be a positive integer")
345 except (TypeError, ValueError):
344 except (TypeError, ValueError):
346 raise ValueError("Context must be a positive integer")
345 raise ValueError("Context must be a positive integer")
347 try:
346 try:
348 for frame_lineno in self.stack:
347 for frame_lineno in self.stack:
349 self.print_stack_entry(frame_lineno, context=context)
348 self.print_stack_entry(frame_lineno, context=context)
350 except KeyboardInterrupt:
349 except KeyboardInterrupt:
351 pass
350 pass
352
351
353 def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
352 def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
354 context=None):
353 context=None):
355 if context is None:
354 if context is None:
356 context = self.context
355 context = self.context
357 try:
356 try:
358 context=int(context)
357 context=int(context)
359 if context <= 0:
358 if context <= 0:
360 raise ValueError("Context must be a positive integer")
359 raise ValueError("Context must be a positive integer")
361 except (TypeError, ValueError):
360 except (TypeError, ValueError):
362 raise ValueError("Context must be a positive integer")
361 raise ValueError("Context must be a positive integer")
363 print(self.format_stack_entry(frame_lineno, '', context))
362 print(self.format_stack_entry(frame_lineno, '', context))
364
363
365 # vds: >>
364 # vds: >>
366 frame, lineno = frame_lineno
365 frame, lineno = frame_lineno
367 filename = frame.f_code.co_filename
366 filename = frame.f_code.co_filename
368 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
367 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
369 # vds: <<
368 # vds: <<
370
369
371 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
370 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
372 if context is None:
371 if context is None:
373 context = self.context
372 context = self.context
374 try:
373 try:
375 context=int(context)
374 context=int(context)
376 if context <= 0:
375 if context <= 0:
377 print("Context must be a positive integer")
376 print("Context must be a positive integer")
378 except (TypeError, ValueError):
377 except (TypeError, ValueError):
379 print("Context must be a positive integer")
378 print("Context must be a positive integer")
380 try:
379 try:
381 import reprlib # Py 3
380 import reprlib # Py 3
382 except ImportError:
381 except ImportError:
383 import repr as reprlib # Py 2
382 import repr as reprlib # Py 2
384
383
385 ret = []
384 ret = []
386
385
387 Colors = self.color_scheme_table.active_colors
386 Colors = self.color_scheme_table.active_colors
388 ColorsNormal = Colors.Normal
387 ColorsNormal = Colors.Normal
389 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
388 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
390 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
389 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
391 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
390 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
392 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
391 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
393 ColorsNormal)
392 ColorsNormal)
394
393
395 frame, lineno = frame_lineno
394 frame, lineno = frame_lineno
396
395
397 return_value = ''
396 return_value = ''
398 if '__return__' in frame.f_locals:
397 if '__return__' in frame.f_locals:
399 rv = frame.f_locals['__return__']
398 rv = frame.f_locals['__return__']
400 #return_value += '->'
399 #return_value += '->'
401 return_value += reprlib.repr(rv) + '\n'
400 return_value += reprlib.repr(rv) + '\n'
402 ret.append(return_value)
401 ret.append(return_value)
403
402
404 #s = filename + '(' + `lineno` + ')'
403 #s = filename + '(' + `lineno` + ')'
405 filename = self.canonic(frame.f_code.co_filename)
404 filename = self.canonic(frame.f_code.co_filename)
406 link = tpl_link % py3compat.cast_unicode(filename)
405 link = tpl_link % py3compat.cast_unicode(filename)
407
406
408 if frame.f_code.co_name:
407 if frame.f_code.co_name:
409 func = frame.f_code.co_name
408 func = frame.f_code.co_name
410 else:
409 else:
411 func = "<lambda>"
410 func = "<lambda>"
412
411
413 call = ''
412 call = ''
414 if func != '?':
413 if func != '?':
415 if '__args__' in frame.f_locals:
414 if '__args__' in frame.f_locals:
416 args = reprlib.repr(frame.f_locals['__args__'])
415 args = reprlib.repr(frame.f_locals['__args__'])
417 else:
416 else:
418 args = '()'
417 args = '()'
419 call = tpl_call % (func, args)
418 call = tpl_call % (func, args)
420
419
421 # The level info should be generated in the same format pdb uses, to
420 # The level info should be generated in the same format pdb uses, to
422 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
421 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
423 if frame is self.curframe:
422 if frame is self.curframe:
424 ret.append('> ')
423 ret.append('> ')
425 else:
424 else:
426 ret.append(' ')
425 ret.append(' ')
427 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
426 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
428
427
429 start = lineno - 1 - context//2
428 start = lineno - 1 - context//2
430 lines = ulinecache.getlines(filename)
429 lines = ulinecache.getlines(filename)
431 start = min(start, len(lines) - context)
430 start = min(start, len(lines) - context)
432 start = max(start, 0)
431 start = max(start, 0)
433 lines = lines[start : start + context]
432 lines = lines[start : start + context]
434
433
435 for i,line in enumerate(lines):
434 for i,line in enumerate(lines):
436 show_arrow = (start + 1 + i == lineno)
435 show_arrow = (start + 1 + i == lineno)
437 linetpl = (frame is self.curframe or show_arrow) \
436 linetpl = (frame is self.curframe or show_arrow) \
438 and tpl_line_em \
437 and tpl_line_em \
439 or tpl_line
438 or tpl_line
440 ret.append(self.__format_line(linetpl, filename,
439 ret.append(self.__format_line(linetpl, filename,
441 start + 1 + i, line,
440 start + 1 + i, line,
442 arrow = show_arrow) )
441 arrow = show_arrow) )
443 return ''.join(ret)
442 return ''.join(ret)
444
443
445 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
444 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
446 bp_mark = ""
445 bp_mark = ""
447 bp_mark_color = ""
446 bp_mark_color = ""
448
447
449 new_line, err = self.parser.format2(line, 'str')
448 new_line, err = self.parser.format2(line, 'str')
450 if not err:
449 if not err:
451 line = new_line
450 line = new_line
452
451
453 bp = None
452 bp = None
454 if lineno in self.get_file_breaks(filename):
453 if lineno in self.get_file_breaks(filename):
455 bps = self.get_breaks(filename, lineno)
454 bps = self.get_breaks(filename, lineno)
456 bp = bps[-1]
455 bp = bps[-1]
457
456
458 if bp:
457 if bp:
459 Colors = self.color_scheme_table.active_colors
458 Colors = self.color_scheme_table.active_colors
460 bp_mark = str(bp.number)
459 bp_mark = str(bp.number)
461 bp_mark_color = Colors.breakpoint_enabled
460 bp_mark_color = Colors.breakpoint_enabled
462 if not bp.enabled:
461 if not bp.enabled:
463 bp_mark_color = Colors.breakpoint_disabled
462 bp_mark_color = Colors.breakpoint_disabled
464
463
465 numbers_width = 7
464 numbers_width = 7
466 if arrow:
465 if arrow:
467 # This is the line with the error
466 # This is the line with the error
468 pad = numbers_width - len(str(lineno)) - len(bp_mark)
467 pad = numbers_width - len(str(lineno)) - len(bp_mark)
469 num = '%s%s' % (make_arrow(pad), str(lineno))
468 num = '%s%s' % (make_arrow(pad), str(lineno))
470 else:
469 else:
471 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
470 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
472
471
473 return tpl_line % (bp_mark_color + bp_mark, num, line)
472 return tpl_line % (bp_mark_color + bp_mark, num, line)
474
473
475
474
476 def print_list_lines(self, filename, first, last):
475 def print_list_lines(self, filename, first, last):
477 """The printing (as opposed to the parsing part of a 'list'
476 """The printing (as opposed to the parsing part of a 'list'
478 command."""
477 command."""
479 try:
478 try:
480 Colors = self.color_scheme_table.active_colors
479 Colors = self.color_scheme_table.active_colors
481 ColorsNormal = Colors.Normal
480 ColorsNormal = Colors.Normal
482 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
481 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
483 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
482 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
484 src = []
483 src = []
485 if filename == "<string>" and hasattr(self, "_exec_filename"):
484 if filename == "<string>" and hasattr(self, "_exec_filename"):
486 filename = self._exec_filename
485 filename = self._exec_filename
487
486
488 for lineno in range(first, last+1):
487 for lineno in range(first, last+1):
489 line = ulinecache.getline(filename, lineno)
488 line = ulinecache.getline(filename, lineno)
490 if not line:
489 if not line:
491 break
490 break
492
491
493 if lineno == self.curframe.f_lineno:
492 if lineno == self.curframe.f_lineno:
494 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
493 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
495 else:
494 else:
496 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
495 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
497
496
498 src.append(line)
497 src.append(line)
499 self.lineno = lineno
498 self.lineno = lineno
500
499
501 print(''.join(src))
500 print(''.join(src))
502
501
503 except KeyboardInterrupt:
502 except KeyboardInterrupt:
504 pass
503 pass
505
504
506 def do_list(self, arg):
505 def do_list(self, arg):
507 self.lastcmd = 'list'
506 self.lastcmd = 'list'
508 last = None
507 last = None
509 if arg:
508 if arg:
510 try:
509 try:
511 x = eval(arg, {}, {})
510 x = eval(arg, {}, {})
512 if type(x) == type(()):
511 if type(x) == type(()):
513 first, last = x
512 first, last = x
514 first = int(first)
513 first = int(first)
515 last = int(last)
514 last = int(last)
516 if last < first:
515 if last < first:
517 # Assume it's a count
516 # Assume it's a count
518 last = first + last
517 last = first + last
519 else:
518 else:
520 first = max(1, int(x) - 5)
519 first = max(1, int(x) - 5)
521 except:
520 except:
522 print('*** Error in argument:', repr(arg))
521 print('*** Error in argument:', repr(arg))
523 return
522 return
524 elif self.lineno is None:
523 elif self.lineno is None:
525 first = max(1, self.curframe.f_lineno - 5)
524 first = max(1, self.curframe.f_lineno - 5)
526 else:
525 else:
527 first = self.lineno + 1
526 first = self.lineno + 1
528 if last is None:
527 if last is None:
529 last = first + 10
528 last = first + 10
530 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
529 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
531
530
532 # vds: >>
531 # vds: >>
533 lineno = first
532 lineno = first
534 filename = self.curframe.f_code.co_filename
533 filename = self.curframe.f_code.co_filename
535 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
534 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
536 # vds: <<
535 # vds: <<
537
536
538 do_l = do_list
537 do_l = do_list
539
538
540 def getsourcelines(self, obj):
539 def getsourcelines(self, obj):
541 lines, lineno = inspect.findsource(obj)
540 lines, lineno = inspect.findsource(obj)
542 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
541 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
543 # must be a module frame: do not try to cut a block out of it
542 # must be a module frame: do not try to cut a block out of it
544 return lines, 1
543 return lines, 1
545 elif inspect.ismodule(obj):
544 elif inspect.ismodule(obj):
546 return lines, 1
545 return lines, 1
547 return inspect.getblock(lines[lineno:]), lineno+1
546 return inspect.getblock(lines[lineno:]), lineno+1
548
547
549 def do_longlist(self, arg):
548 def do_longlist(self, arg):
550 self.lastcmd = 'longlist'
549 self.lastcmd = 'longlist'
551 try:
550 try:
552 lines, lineno = self.getsourcelines(self.curframe)
551 lines, lineno = self.getsourcelines(self.curframe)
553 except OSError as err:
552 except OSError as err:
554 self.error(err)
553 self.error(err)
555 return
554 return
556 last = lineno + len(lines)
555 last = lineno + len(lines)
557 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
556 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
558 do_ll = do_longlist
557 do_ll = do_longlist
559
558
560 def do_pdef(self, arg):
559 def do_pdef(self, arg):
561 """Print the call signature for any callable object.
560 """Print the call signature for any callable object.
562
561
563 The debugger interface to %pdef"""
562 The debugger interface to %pdef"""
564 namespaces = [('Locals', self.curframe.f_locals),
563 namespaces = [('Locals', self.curframe.f_locals),
565 ('Globals', self.curframe.f_globals)]
564 ('Globals', self.curframe.f_globals)]
566 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
565 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
567
566
568 def do_pdoc(self, arg):
567 def do_pdoc(self, arg):
569 """Print the docstring for an object.
568 """Print the docstring for an object.
570
569
571 The debugger interface to %pdoc."""
570 The debugger interface to %pdoc."""
572 namespaces = [('Locals', self.curframe.f_locals),
571 namespaces = [('Locals', self.curframe.f_locals),
573 ('Globals', self.curframe.f_globals)]
572 ('Globals', self.curframe.f_globals)]
574 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
573 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
575
574
576 def do_pfile(self, arg):
575 def do_pfile(self, arg):
577 """Print (or run through pager) the file where an object is defined.
576 """Print (or run through pager) the file where an object is defined.
578
577
579 The debugger interface to %pfile.
578 The debugger interface to %pfile.
580 """
579 """
581 namespaces = [('Locals', self.curframe.f_locals),
580 namespaces = [('Locals', self.curframe.f_locals),
582 ('Globals', self.curframe.f_globals)]
581 ('Globals', self.curframe.f_globals)]
583 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
582 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
584
583
585 def do_pinfo(self, arg):
584 def do_pinfo(self, arg):
586 """Provide detailed information about an object.
585 """Provide detailed information about an object.
587
586
588 The debugger interface to %pinfo, i.e., obj?."""
587 The debugger interface to %pinfo, i.e., obj?."""
589 namespaces = [('Locals', self.curframe.f_locals),
588 namespaces = [('Locals', self.curframe.f_locals),
590 ('Globals', self.curframe.f_globals)]
589 ('Globals', self.curframe.f_globals)]
591 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
590 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
592
591
593 def do_pinfo2(self, arg):
592 def do_pinfo2(self, arg):
594 """Provide extra detailed information about an object.
593 """Provide extra detailed information about an object.
595
594
596 The debugger interface to %pinfo2, i.e., obj??."""
595 The debugger interface to %pinfo2, i.e., obj??."""
597 namespaces = [('Locals', self.curframe.f_locals),
596 namespaces = [('Locals', self.curframe.f_locals),
598 ('Globals', self.curframe.f_globals)]
597 ('Globals', self.curframe.f_globals)]
599 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
598 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
600
599
601 def do_psource(self, arg):
600 def do_psource(self, arg):
602 """Print (or run through pager) the source code for an object."""
601 """Print (or run through pager) the source code for an object."""
603 namespaces = [('Locals', self.curframe.f_locals),
602 namespaces = [('Locals', self.curframe.f_locals),
604 ('Globals', self.curframe.f_globals)]
603 ('Globals', self.curframe.f_globals)]
605 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
604 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
606
605
607 def do_where(self, arg):
606 def do_where(self, arg):
608 """w(here)
607 """w(here)
609 Print a stack trace, with the most recent frame at the bottom.
608 Print a stack trace, with the most recent frame at the bottom.
610 An arrow indicates the "current frame", which determines the
609 An arrow indicates the "current frame", which determines the
611 context of most commands. 'bt' is an alias for this command.
610 context of most commands. 'bt' is an alias for this command.
612
611
613 Take a number as argument as an (optional) number of context line to
612 Take a number as argument as an (optional) number of context line to
614 print"""
613 print"""
615 if arg:
614 if arg:
616 context = int(arg)
615 context = int(arg)
617 self.print_stack_trace(context)
616 self.print_stack_trace(context)
618 else:
617 else:
619 self.print_stack_trace()
618 self.print_stack_trace()
620
619
621 do_w = do_where
620 do_w = do_where
622
621
623
622
624 def set_trace(frame=None):
623 def set_trace(frame=None):
625 """
624 """
626 Start debugging from `frame`.
625 Start debugging from `frame`.
627
626
628 If frame is not specified, debugging starts from caller's frame.
627 If frame is not specified, debugging starts from caller's frame.
629 """
628 """
630 Pdb().set_trace(frame or sys._getframe().f_back)
629 Pdb().set_trace(frame or sys._getframe().f_back)
@@ -1,1031 +1,1030 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Top-level display functions for displaying object in different formats."""
2 """Top-level display functions for displaying object in different formats."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 from __future__ import print_function
8
7
9 try:
8 try:
10 from base64 import encodebytes as base64_encode
9 from base64 import encodebytes as base64_encode
11 except ImportError:
10 except ImportError:
12 from base64 import encodestring as base64_encode
11 from base64 import encodestring as base64_encode
13
12
14 import json
13 import json
15 import mimetypes
14 import mimetypes
16 import os
15 import os
17 import struct
16 import struct
18 import sys
17 import sys
19 import warnings
18 import warnings
20
19
21 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
20 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
22 unicode_type)
21 unicode_type)
23 from IPython.testing.skipdoctest import skip_doctest
22 from IPython.testing.skipdoctest import skip_doctest
24
23
25 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
24 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
26 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
25 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
27 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
26 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
28 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript',
27 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript',
29 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
28 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
30 'publish_display_data']
29 'publish_display_data']
31
30
32 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
33 # utility functions
32 # utility functions
34 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
35
34
36 def _safe_exists(path):
35 def _safe_exists(path):
37 """Check path, but don't let exceptions raise"""
36 """Check path, but don't let exceptions raise"""
38 try:
37 try:
39 return os.path.exists(path)
38 return os.path.exists(path)
40 except Exception:
39 except Exception:
41 return False
40 return False
42
41
43 def _merge(d1, d2):
42 def _merge(d1, d2):
44 """Like update, but merges sub-dicts instead of clobbering at the top level.
43 """Like update, but merges sub-dicts instead of clobbering at the top level.
45
44
46 Updates d1 in-place
45 Updates d1 in-place
47 """
46 """
48
47
49 if not isinstance(d2, dict) or not isinstance(d1, dict):
48 if not isinstance(d2, dict) or not isinstance(d1, dict):
50 return d2
49 return d2
51 for key, value in d2.items():
50 for key, value in d2.items():
52 d1[key] = _merge(d1.get(key), value)
51 d1[key] = _merge(d1.get(key), value)
53 return d1
52 return d1
54
53
55 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
54 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
56 """internal implementation of all display_foo methods
55 """internal implementation of all display_foo methods
57
56
58 Parameters
57 Parameters
59 ----------
58 ----------
60 mimetype : str
59 mimetype : str
61 The mimetype to be published (e.g. 'image/png')
60 The mimetype to be published (e.g. 'image/png')
62 objs : tuple of objects
61 objs : tuple of objects
63 The Python objects to display, or if raw=True raw text data to
62 The Python objects to display, or if raw=True raw text data to
64 display.
63 display.
65 raw : bool
64 raw : bool
66 Are the data objects raw data or Python objects that need to be
65 Are the data objects raw data or Python objects that need to be
67 formatted before display? [default: False]
66 formatted before display? [default: False]
68 metadata : dict (optional)
67 metadata : dict (optional)
69 Metadata to be associated with the specific mimetype output.
68 Metadata to be associated with the specific mimetype output.
70 """
69 """
71 if metadata:
70 if metadata:
72 metadata = {mimetype: metadata}
71 metadata = {mimetype: metadata}
73 if raw:
72 if raw:
74 # turn list of pngdata into list of { 'image/png': pngdata }
73 # turn list of pngdata into list of { 'image/png': pngdata }
75 objs = [ {mimetype: obj} for obj in objs ]
74 objs = [ {mimetype: obj} for obj in objs ]
76 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
75 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
77
76
78 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
79 # Main functions
78 # Main functions
80 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
81
80
82 def publish_display_data(data, metadata=None, source=None):
81 def publish_display_data(data, metadata=None, source=None):
83 """Publish data and metadata to all frontends.
82 """Publish data and metadata to all frontends.
84
83
85 See the ``display_data`` message in the messaging documentation for
84 See the ``display_data`` message in the messaging documentation for
86 more details about this message type.
85 more details about this message type.
87
86
88 The following MIME types are currently implemented:
87 The following MIME types are currently implemented:
89
88
90 * text/plain
89 * text/plain
91 * text/html
90 * text/html
92 * text/markdown
91 * text/markdown
93 * text/latex
92 * text/latex
94 * application/json
93 * application/json
95 * application/javascript
94 * application/javascript
96 * image/png
95 * image/png
97 * image/jpeg
96 * image/jpeg
98 * image/svg+xml
97 * image/svg+xml
99
98
100 Parameters
99 Parameters
101 ----------
100 ----------
102 data : dict
101 data : dict
103 A dictionary having keys that are valid MIME types (like
102 A dictionary having keys that are valid MIME types (like
104 'text/plain' or 'image/svg+xml') and values that are the data for
103 'text/plain' or 'image/svg+xml') and values that are the data for
105 that MIME type. The data itself must be a JSON'able data
104 that MIME type. The data itself must be a JSON'able data
106 structure. Minimally all data should have the 'text/plain' data,
105 structure. Minimally all data should have the 'text/plain' data,
107 which can be displayed by all frontends. If more than the plain
106 which can be displayed by all frontends. If more than the plain
108 text is given, it is up to the frontend to decide which
107 text is given, it is up to the frontend to decide which
109 representation to use.
108 representation to use.
110 metadata : dict
109 metadata : dict
111 A dictionary for metadata related to the data. This can contain
110 A dictionary for metadata related to the data. This can contain
112 arbitrary key, value pairs that frontends can use to interpret
111 arbitrary key, value pairs that frontends can use to interpret
113 the data. mime-type keys matching those in data can be used
112 the data. mime-type keys matching those in data can be used
114 to specify metadata about particular representations.
113 to specify metadata about particular representations.
115 source : str, deprecated
114 source : str, deprecated
116 Unused.
115 Unused.
117 """
116 """
118 from IPython.core.interactiveshell import InteractiveShell
117 from IPython.core.interactiveshell import InteractiveShell
119 InteractiveShell.instance().display_pub.publish(
118 InteractiveShell.instance().display_pub.publish(
120 data=data,
119 data=data,
121 metadata=metadata,
120 metadata=metadata,
122 )
121 )
123
122
124 def display(*objs, **kwargs):
123 def display(*objs, **kwargs):
125 """Display a Python object in all frontends.
124 """Display a Python object in all frontends.
126
125
127 By default all representations will be computed and sent to the frontends.
126 By default all representations will be computed and sent to the frontends.
128 Frontends can decide which representation is used and how.
127 Frontends can decide which representation is used and how.
129
128
130 Parameters
129 Parameters
131 ----------
130 ----------
132 objs : tuple of objects
131 objs : tuple of objects
133 The Python objects to display.
132 The Python objects to display.
134 raw : bool, optional
133 raw : bool, optional
135 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
134 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
136 or Python objects that need to be formatted before display? [default: False]
135 or Python objects that need to be formatted before display? [default: False]
137 include : list or tuple, optional
136 include : list or tuple, optional
138 A list of format type strings (MIME types) to include in the
137 A list of format type strings (MIME types) to include in the
139 format data dict. If this is set *only* the format types included
138 format data dict. If this is set *only* the format types included
140 in this list will be computed.
139 in this list will be computed.
141 exclude : list or tuple, optional
140 exclude : list or tuple, optional
142 A list of format type strings (MIME types) to exclude in the format
141 A list of format type strings (MIME types) to exclude in the format
143 data dict. If this is set all format types will be computed,
142 data dict. If this is set all format types will be computed,
144 except for those included in this argument.
143 except for those included in this argument.
145 metadata : dict, optional
144 metadata : dict, optional
146 A dictionary of metadata to associate with the output.
145 A dictionary of metadata to associate with the output.
147 mime-type keys in this dictionary will be associated with the individual
146 mime-type keys in this dictionary will be associated with the individual
148 representation formats, if they exist.
147 representation formats, if they exist.
149 """
148 """
150 raw = kwargs.get('raw', False)
149 raw = kwargs.get('raw', False)
151 include = kwargs.get('include')
150 include = kwargs.get('include')
152 exclude = kwargs.get('exclude')
151 exclude = kwargs.get('exclude')
153 metadata = kwargs.get('metadata')
152 metadata = kwargs.get('metadata')
154
153
155 from IPython.core.interactiveshell import InteractiveShell
154 from IPython.core.interactiveshell import InteractiveShell
156
155
157 if not raw:
156 if not raw:
158 format = InteractiveShell.instance().display_formatter.format
157 format = InteractiveShell.instance().display_formatter.format
159
158
160 for obj in objs:
159 for obj in objs:
161 if raw:
160 if raw:
162 publish_display_data(data=obj, metadata=metadata)
161 publish_display_data(data=obj, metadata=metadata)
163 else:
162 else:
164 format_dict, md_dict = format(obj, include=include, exclude=exclude)
163 format_dict, md_dict = format(obj, include=include, exclude=exclude)
165 if not format_dict:
164 if not format_dict:
166 # nothing to display (e.g. _ipython_display_ took over)
165 # nothing to display (e.g. _ipython_display_ took over)
167 continue
166 continue
168 if metadata:
167 if metadata:
169 # kwarg-specified metadata gets precedence
168 # kwarg-specified metadata gets precedence
170 _merge(md_dict, metadata)
169 _merge(md_dict, metadata)
171 publish_display_data(data=format_dict, metadata=md_dict)
170 publish_display_data(data=format_dict, metadata=md_dict)
172
171
173
172
174 def display_pretty(*objs, **kwargs):
173 def display_pretty(*objs, **kwargs):
175 """Display the pretty (default) representation of an object.
174 """Display the pretty (default) representation of an object.
176
175
177 Parameters
176 Parameters
178 ----------
177 ----------
179 objs : tuple of objects
178 objs : tuple of objects
180 The Python objects to display, or if raw=True raw text data to
179 The Python objects to display, or if raw=True raw text data to
181 display.
180 display.
182 raw : bool
181 raw : bool
183 Are the data objects raw data or Python objects that need to be
182 Are the data objects raw data or Python objects that need to be
184 formatted before display? [default: False]
183 formatted before display? [default: False]
185 metadata : dict (optional)
184 metadata : dict (optional)
186 Metadata to be associated with the specific mimetype output.
185 Metadata to be associated with the specific mimetype output.
187 """
186 """
188 _display_mimetype('text/plain', objs, **kwargs)
187 _display_mimetype('text/plain', objs, **kwargs)
189
188
190
189
191 def display_html(*objs, **kwargs):
190 def display_html(*objs, **kwargs):
192 """Display the HTML representation of an object.
191 """Display the HTML representation of an object.
193
192
194 Note: If raw=False and the object does not have a HTML
193 Note: If raw=False and the object does not have a HTML
195 representation, no HTML will be shown.
194 representation, no HTML will be shown.
196
195
197 Parameters
196 Parameters
198 ----------
197 ----------
199 objs : tuple of objects
198 objs : tuple of objects
200 The Python objects to display, or if raw=True raw HTML data to
199 The Python objects to display, or if raw=True raw HTML data to
201 display.
200 display.
202 raw : bool
201 raw : bool
203 Are the data objects raw data or Python objects that need to be
202 Are the data objects raw data or Python objects that need to be
204 formatted before display? [default: False]
203 formatted before display? [default: False]
205 metadata : dict (optional)
204 metadata : dict (optional)
206 Metadata to be associated with the specific mimetype output.
205 Metadata to be associated with the specific mimetype output.
207 """
206 """
208 _display_mimetype('text/html', objs, **kwargs)
207 _display_mimetype('text/html', objs, **kwargs)
209
208
210
209
211 def display_markdown(*objs, **kwargs):
210 def display_markdown(*objs, **kwargs):
212 """Displays the Markdown representation of an object.
211 """Displays the Markdown representation of an object.
213
212
214 Parameters
213 Parameters
215 ----------
214 ----------
216 objs : tuple of objects
215 objs : tuple of objects
217 The Python objects to display, or if raw=True raw markdown data to
216 The Python objects to display, or if raw=True raw markdown data to
218 display.
217 display.
219 raw : bool
218 raw : bool
220 Are the data objects raw data or Python objects that need to be
219 Are the data objects raw data or Python objects that need to be
221 formatted before display? [default: False]
220 formatted before display? [default: False]
222 metadata : dict (optional)
221 metadata : dict (optional)
223 Metadata to be associated with the specific mimetype output.
222 Metadata to be associated with the specific mimetype output.
224 """
223 """
225
224
226 _display_mimetype('text/markdown', objs, **kwargs)
225 _display_mimetype('text/markdown', objs, **kwargs)
227
226
228
227
229 def display_svg(*objs, **kwargs):
228 def display_svg(*objs, **kwargs):
230 """Display the SVG representation of an object.
229 """Display the SVG representation of an object.
231
230
232 Parameters
231 Parameters
233 ----------
232 ----------
234 objs : tuple of objects
233 objs : tuple of objects
235 The Python objects to display, or if raw=True raw svg data to
234 The Python objects to display, or if raw=True raw svg data to
236 display.
235 display.
237 raw : bool
236 raw : bool
238 Are the data objects raw data or Python objects that need to be
237 Are the data objects raw data or Python objects that need to be
239 formatted before display? [default: False]
238 formatted before display? [default: False]
240 metadata : dict (optional)
239 metadata : dict (optional)
241 Metadata to be associated with the specific mimetype output.
240 Metadata to be associated with the specific mimetype output.
242 """
241 """
243 _display_mimetype('image/svg+xml', objs, **kwargs)
242 _display_mimetype('image/svg+xml', objs, **kwargs)
244
243
245
244
246 def display_png(*objs, **kwargs):
245 def display_png(*objs, **kwargs):
247 """Display the PNG representation of an object.
246 """Display the PNG representation of an object.
248
247
249 Parameters
248 Parameters
250 ----------
249 ----------
251 objs : tuple of objects
250 objs : tuple of objects
252 The Python objects to display, or if raw=True raw png data to
251 The Python objects to display, or if raw=True raw png data to
253 display.
252 display.
254 raw : bool
253 raw : bool
255 Are the data objects raw data or Python objects that need to be
254 Are the data objects raw data or Python objects that need to be
256 formatted before display? [default: False]
255 formatted before display? [default: False]
257 metadata : dict (optional)
256 metadata : dict (optional)
258 Metadata to be associated with the specific mimetype output.
257 Metadata to be associated with the specific mimetype output.
259 """
258 """
260 _display_mimetype('image/png', objs, **kwargs)
259 _display_mimetype('image/png', objs, **kwargs)
261
260
262
261
263 def display_jpeg(*objs, **kwargs):
262 def display_jpeg(*objs, **kwargs):
264 """Display the JPEG representation of an object.
263 """Display the JPEG representation of an object.
265
264
266 Parameters
265 Parameters
267 ----------
266 ----------
268 objs : tuple of objects
267 objs : tuple of objects
269 The Python objects to display, or if raw=True raw JPEG data to
268 The Python objects to display, or if raw=True raw JPEG data to
270 display.
269 display.
271 raw : bool
270 raw : bool
272 Are the data objects raw data or Python objects that need to be
271 Are the data objects raw data or Python objects that need to be
273 formatted before display? [default: False]
272 formatted before display? [default: False]
274 metadata : dict (optional)
273 metadata : dict (optional)
275 Metadata to be associated with the specific mimetype output.
274 Metadata to be associated with the specific mimetype output.
276 """
275 """
277 _display_mimetype('image/jpeg', objs, **kwargs)
276 _display_mimetype('image/jpeg', objs, **kwargs)
278
277
279
278
280 def display_latex(*objs, **kwargs):
279 def display_latex(*objs, **kwargs):
281 """Display the LaTeX representation of an object.
280 """Display the LaTeX representation of an object.
282
281
283 Parameters
282 Parameters
284 ----------
283 ----------
285 objs : tuple of objects
284 objs : tuple of objects
286 The Python objects to display, or if raw=True raw latex data to
285 The Python objects to display, or if raw=True raw latex data to
287 display.
286 display.
288 raw : bool
287 raw : bool
289 Are the data objects raw data or Python objects that need to be
288 Are the data objects raw data or Python objects that need to be
290 formatted before display? [default: False]
289 formatted before display? [default: False]
291 metadata : dict (optional)
290 metadata : dict (optional)
292 Metadata to be associated with the specific mimetype output.
291 Metadata to be associated with the specific mimetype output.
293 """
292 """
294 _display_mimetype('text/latex', objs, **kwargs)
293 _display_mimetype('text/latex', objs, **kwargs)
295
294
296
295
297 def display_json(*objs, **kwargs):
296 def display_json(*objs, **kwargs):
298 """Display the JSON representation of an object.
297 """Display the JSON representation of an object.
299
298
300 Note that not many frontends support displaying JSON.
299 Note that not many frontends support displaying JSON.
301
300
302 Parameters
301 Parameters
303 ----------
302 ----------
304 objs : tuple of objects
303 objs : tuple of objects
305 The Python objects to display, or if raw=True raw json data to
304 The Python objects to display, or if raw=True raw json data to
306 display.
305 display.
307 raw : bool
306 raw : bool
308 Are the data objects raw data or Python objects that need to be
307 Are the data objects raw data or Python objects that need to be
309 formatted before display? [default: False]
308 formatted before display? [default: False]
310 metadata : dict (optional)
309 metadata : dict (optional)
311 Metadata to be associated with the specific mimetype output.
310 Metadata to be associated with the specific mimetype output.
312 """
311 """
313 _display_mimetype('application/json', objs, **kwargs)
312 _display_mimetype('application/json', objs, **kwargs)
314
313
315
314
316 def display_javascript(*objs, **kwargs):
315 def display_javascript(*objs, **kwargs):
317 """Display the Javascript representation of an object.
316 """Display the Javascript representation of an object.
318
317
319 Parameters
318 Parameters
320 ----------
319 ----------
321 objs : tuple of objects
320 objs : tuple of objects
322 The Python objects to display, or if raw=True raw javascript data to
321 The Python objects to display, or if raw=True raw javascript data to
323 display.
322 display.
324 raw : bool
323 raw : bool
325 Are the data objects raw data or Python objects that need to be
324 Are the data objects raw data or Python objects that need to be
326 formatted before display? [default: False]
325 formatted before display? [default: False]
327 metadata : dict (optional)
326 metadata : dict (optional)
328 Metadata to be associated with the specific mimetype output.
327 Metadata to be associated with the specific mimetype output.
329 """
328 """
330 _display_mimetype('application/javascript', objs, **kwargs)
329 _display_mimetype('application/javascript', objs, **kwargs)
331
330
332
331
333 def display_pdf(*objs, **kwargs):
332 def display_pdf(*objs, **kwargs):
334 """Display the PDF representation of an object.
333 """Display the PDF representation of an object.
335
334
336 Parameters
335 Parameters
337 ----------
336 ----------
338 objs : tuple of objects
337 objs : tuple of objects
339 The Python objects to display, or if raw=True raw javascript data to
338 The Python objects to display, or if raw=True raw javascript data to
340 display.
339 display.
341 raw : bool
340 raw : bool
342 Are the data objects raw data or Python objects that need to be
341 Are the data objects raw data or Python objects that need to be
343 formatted before display? [default: False]
342 formatted before display? [default: False]
344 metadata : dict (optional)
343 metadata : dict (optional)
345 Metadata to be associated with the specific mimetype output.
344 Metadata to be associated with the specific mimetype output.
346 """
345 """
347 _display_mimetype('application/pdf', objs, **kwargs)
346 _display_mimetype('application/pdf', objs, **kwargs)
348
347
349
348
350 #-----------------------------------------------------------------------------
349 #-----------------------------------------------------------------------------
351 # Smart classes
350 # Smart classes
352 #-----------------------------------------------------------------------------
351 #-----------------------------------------------------------------------------
353
352
354
353
355 class DisplayObject(object):
354 class DisplayObject(object):
356 """An object that wraps data to be displayed."""
355 """An object that wraps data to be displayed."""
357
356
358 _read_flags = 'r'
357 _read_flags = 'r'
359 _show_mem_addr = False
358 _show_mem_addr = False
360
359
361 def __init__(self, data=None, url=None, filename=None):
360 def __init__(self, data=None, url=None, filename=None):
362 """Create a display object given raw data.
361 """Create a display object given raw data.
363
362
364 When this object is returned by an expression or passed to the
363 When this object is returned by an expression or passed to the
365 display function, it will result in the data being displayed
364 display function, it will result in the data being displayed
366 in the frontend. The MIME type of the data should match the
365 in the frontend. The MIME type of the data should match the
367 subclasses used, so the Png subclass should be used for 'image/png'
366 subclasses used, so the Png subclass should be used for 'image/png'
368 data. If the data is a URL, the data will first be downloaded
367 data. If the data is a URL, the data will first be downloaded
369 and then displayed. If
368 and then displayed. If
370
369
371 Parameters
370 Parameters
372 ----------
371 ----------
373 data : unicode, str or bytes
372 data : unicode, str or bytes
374 The raw data or a URL or file to load the data from
373 The raw data or a URL or file to load the data from
375 url : unicode
374 url : unicode
376 A URL to download the data from.
375 A URL to download the data from.
377 filename : unicode
376 filename : unicode
378 Path to a local file to load the data from.
377 Path to a local file to load the data from.
379 """
378 """
380 if data is not None and isinstance(data, string_types):
379 if data is not None and isinstance(data, string_types):
381 if data.startswith('http') and url is None:
380 if data.startswith('http') and url is None:
382 url = data
381 url = data
383 filename = None
382 filename = None
384 data = None
383 data = None
385 elif _safe_exists(data) and filename is None:
384 elif _safe_exists(data) and filename is None:
386 url = None
385 url = None
387 filename = data
386 filename = data
388 data = None
387 data = None
389
388
390 self.data = data
389 self.data = data
391 self.url = url
390 self.url = url
392 self.filename = None if filename is None else unicode_type(filename)
391 self.filename = None if filename is None else unicode_type(filename)
393
392
394 self.reload()
393 self.reload()
395 self._check_data()
394 self._check_data()
396
395
397 def __repr__(self):
396 def __repr__(self):
398 if not self._show_mem_addr:
397 if not self._show_mem_addr:
399 cls = self.__class__
398 cls = self.__class__
400 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
399 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
401 else:
400 else:
402 r = super(DisplayObject, self).__repr__()
401 r = super(DisplayObject, self).__repr__()
403 return r
402 return r
404
403
405 def _check_data(self):
404 def _check_data(self):
406 """Override in subclasses if there's something to check."""
405 """Override in subclasses if there's something to check."""
407 pass
406 pass
408
407
409 def reload(self):
408 def reload(self):
410 """Reload the raw data from file or URL."""
409 """Reload the raw data from file or URL."""
411 if self.filename is not None:
410 if self.filename is not None:
412 with open(self.filename, self._read_flags) as f:
411 with open(self.filename, self._read_flags) as f:
413 self.data = f.read()
412 self.data = f.read()
414 elif self.url is not None:
413 elif self.url is not None:
415 try:
414 try:
416 try:
415 try:
417 from urllib.request import urlopen # Py3
416 from urllib.request import urlopen # Py3
418 except ImportError:
417 except ImportError:
419 from urllib2 import urlopen
418 from urllib2 import urlopen
420 response = urlopen(self.url)
419 response = urlopen(self.url)
421 self.data = response.read()
420 self.data = response.read()
422 # extract encoding from header, if there is one:
421 # extract encoding from header, if there is one:
423 encoding = None
422 encoding = None
424 for sub in response.headers['content-type'].split(';'):
423 for sub in response.headers['content-type'].split(';'):
425 sub = sub.strip()
424 sub = sub.strip()
426 if sub.startswith('charset'):
425 if sub.startswith('charset'):
427 encoding = sub.split('=')[-1].strip()
426 encoding = sub.split('=')[-1].strip()
428 break
427 break
429 # decode data, if an encoding was specified
428 # decode data, if an encoding was specified
430 if encoding:
429 if encoding:
431 self.data = self.data.decode(encoding, 'replace')
430 self.data = self.data.decode(encoding, 'replace')
432 except:
431 except:
433 self.data = None
432 self.data = None
434
433
435 class TextDisplayObject(DisplayObject):
434 class TextDisplayObject(DisplayObject):
436 """Validate that display data is text"""
435 """Validate that display data is text"""
437 def _check_data(self):
436 def _check_data(self):
438 if self.data is not None and not isinstance(self.data, string_types):
437 if self.data is not None and not isinstance(self.data, string_types):
439 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
438 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
440
439
441 class Pretty(TextDisplayObject):
440 class Pretty(TextDisplayObject):
442
441
443 def _repr_pretty_(self):
442 def _repr_pretty_(self):
444 return self.data
443 return self.data
445
444
446
445
447 class HTML(TextDisplayObject):
446 class HTML(TextDisplayObject):
448
447
449 def _repr_html_(self):
448 def _repr_html_(self):
450 return self.data
449 return self.data
451
450
452 def __html__(self):
451 def __html__(self):
453 """
452 """
454 This method exists to inform other HTML-using modules (e.g. Markupsafe,
453 This method exists to inform other HTML-using modules (e.g. Markupsafe,
455 htmltag, etc) that this object is HTML and does not need things like
454 htmltag, etc) that this object is HTML and does not need things like
456 special characters (<>&) escaped.
455 special characters (<>&) escaped.
457 """
456 """
458 return self._repr_html_()
457 return self._repr_html_()
459
458
460
459
461 class Markdown(TextDisplayObject):
460 class Markdown(TextDisplayObject):
462
461
463 def _repr_markdown_(self):
462 def _repr_markdown_(self):
464 return self.data
463 return self.data
465
464
466
465
467 class Math(TextDisplayObject):
466 class Math(TextDisplayObject):
468
467
469 def _repr_latex_(self):
468 def _repr_latex_(self):
470 s = self.data.strip('$')
469 s = self.data.strip('$')
471 return "$$%s$$" % s
470 return "$$%s$$" % s
472
471
473
472
474 class Latex(TextDisplayObject):
473 class Latex(TextDisplayObject):
475
474
476 def _repr_latex_(self):
475 def _repr_latex_(self):
477 return self.data
476 return self.data
478
477
479
478
480 class SVG(DisplayObject):
479 class SVG(DisplayObject):
481
480
482 # wrap data in a property, which extracts the <svg> tag, discarding
481 # wrap data in a property, which extracts the <svg> tag, discarding
483 # document headers
482 # document headers
484 _data = None
483 _data = None
485
484
486 @property
485 @property
487 def data(self):
486 def data(self):
488 return self._data
487 return self._data
489
488
490 @data.setter
489 @data.setter
491 def data(self, svg):
490 def data(self, svg):
492 if svg is None:
491 if svg is None:
493 self._data = None
492 self._data = None
494 return
493 return
495 # parse into dom object
494 # parse into dom object
496 from xml.dom import minidom
495 from xml.dom import minidom
497 svg = cast_bytes_py2(svg)
496 svg = cast_bytes_py2(svg)
498 x = minidom.parseString(svg)
497 x = minidom.parseString(svg)
499 # get svg tag (should be 1)
498 # get svg tag (should be 1)
500 found_svg = x.getElementsByTagName('svg')
499 found_svg = x.getElementsByTagName('svg')
501 if found_svg:
500 if found_svg:
502 svg = found_svg[0].toxml()
501 svg = found_svg[0].toxml()
503 else:
502 else:
504 # fallback on the input, trust the user
503 # fallback on the input, trust the user
505 # but this is probably an error.
504 # but this is probably an error.
506 pass
505 pass
507 svg = cast_unicode(svg)
506 svg = cast_unicode(svg)
508 self._data = svg
507 self._data = svg
509
508
510 def _repr_svg_(self):
509 def _repr_svg_(self):
511 return self.data
510 return self.data
512
511
513
512
514 class JSON(DisplayObject):
513 class JSON(DisplayObject):
515 """JSON expects a JSON-able dict or list
514 """JSON expects a JSON-able dict or list
516
515
517 not an already-serialized JSON string.
516 not an already-serialized JSON string.
518
517
519 Scalar types (None, number, string) are not allowed, only dict or list containers.
518 Scalar types (None, number, string) are not allowed, only dict or list containers.
520 """
519 """
521 # wrap data in a property, which warns about passing already-serialized JSON
520 # wrap data in a property, which warns about passing already-serialized JSON
522 _data = None
521 _data = None
523 def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None):
522 def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None):
524 """Create a JSON display object given raw data.
523 """Create a JSON display object given raw data.
525
524
526 Parameters
525 Parameters
527 ----------
526 ----------
528 data : dict or list
527 data : dict or list
529 JSON data to display. Not an already-serialized JSON string.
528 JSON data to display. Not an already-serialized JSON string.
530 Scalar types (None, number, string) are not allowed, only dict
529 Scalar types (None, number, string) are not allowed, only dict
531 or list containers.
530 or list containers.
532 url : unicode
531 url : unicode
533 A URL to download the data from.
532 A URL to download the data from.
534 filename : unicode
533 filename : unicode
535 Path to a local file to load the data from.
534 Path to a local file to load the data from.
536 expanded : boolean
535 expanded : boolean
537 Metadata to control whether a JSON display component is expanded.
536 Metadata to control whether a JSON display component is expanded.
538 metadata: dict
537 metadata: dict
539 Specify extra metadata to attach to the json display object.
538 Specify extra metadata to attach to the json display object.
540 """
539 """
541 self.expanded = expanded
540 self.expanded = expanded
542 self.metadata = metadata
541 self.metadata = metadata
543 super(JSON, self).__init__(data=data, url=url, filename=filename)
542 super(JSON, self).__init__(data=data, url=url, filename=filename)
544
543
545 def _check_data(self):
544 def _check_data(self):
546 if self.data is not None and not isinstance(self.data, (dict, list)):
545 if self.data is not None and not isinstance(self.data, (dict, list)):
547 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
546 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
548
547
549 @property
548 @property
550 def data(self):
549 def data(self):
551 return self._data
550 return self._data
552
551
553 @data.setter
552 @data.setter
554 def data(self, data):
553 def data(self, data):
555 if isinstance(data, string_types):
554 if isinstance(data, string_types):
556 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
555 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
557 data = json.loads(data)
556 data = json.loads(data)
558 self._data = data
557 self._data = data
559
558
560 def _data_and_metadata(self):
559 def _data_and_metadata(self):
561 md = {'expanded': self.expanded}
560 md = {'expanded': self.expanded}
562 if self.metadata:
561 if self.metadata:
563 md.update(self.metadata)
562 md.update(self.metadata)
564 return self.data, md
563 return self.data, md
565
564
566 def _repr_json_(self):
565 def _repr_json_(self):
567 return self._data_and_metadata()
566 return self._data_and_metadata()
568
567
569 css_t = """$("head").append($("<link/>").attr({
568 css_t = """$("head").append($("<link/>").attr({
570 rel: "stylesheet",
569 rel: "stylesheet",
571 type: "text/css",
570 type: "text/css",
572 href: "%s"
571 href: "%s"
573 }));
572 }));
574 """
573 """
575
574
576 lib_t1 = """$.getScript("%s", function () {
575 lib_t1 = """$.getScript("%s", function () {
577 """
576 """
578 lib_t2 = """});
577 lib_t2 = """});
579 """
578 """
580
579
581 class Javascript(TextDisplayObject):
580 class Javascript(TextDisplayObject):
582
581
583 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
582 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
584 """Create a Javascript display object given raw data.
583 """Create a Javascript display object given raw data.
585
584
586 When this object is returned by an expression or passed to the
585 When this object is returned by an expression or passed to the
587 display function, it will result in the data being displayed
586 display function, it will result in the data being displayed
588 in the frontend. If the data is a URL, the data will first be
587 in the frontend. If the data is a URL, the data will first be
589 downloaded and then displayed.
588 downloaded and then displayed.
590
589
591 In the Notebook, the containing element will be available as `element`,
590 In the Notebook, the containing element will be available as `element`,
592 and jQuery will be available. Content appended to `element` will be
591 and jQuery will be available. Content appended to `element` will be
593 visible in the output area.
592 visible in the output area.
594
593
595 Parameters
594 Parameters
596 ----------
595 ----------
597 data : unicode, str or bytes
596 data : unicode, str or bytes
598 The Javascript source code or a URL to download it from.
597 The Javascript source code or a URL to download it from.
599 url : unicode
598 url : unicode
600 A URL to download the data from.
599 A URL to download the data from.
601 filename : unicode
600 filename : unicode
602 Path to a local file to load the data from.
601 Path to a local file to load the data from.
603 lib : list or str
602 lib : list or str
604 A sequence of Javascript library URLs to load asynchronously before
603 A sequence of Javascript library URLs to load asynchronously before
605 running the source code. The full URLs of the libraries should
604 running the source code. The full URLs of the libraries should
606 be given. A single Javascript library URL can also be given as a
605 be given. A single Javascript library URL can also be given as a
607 string.
606 string.
608 css: : list or str
607 css: : list or str
609 A sequence of css files to load before running the source code.
608 A sequence of css files to load before running the source code.
610 The full URLs of the css files should be given. A single css URL
609 The full URLs of the css files should be given. A single css URL
611 can also be given as a string.
610 can also be given as a string.
612 """
611 """
613 if isinstance(lib, string_types):
612 if isinstance(lib, string_types):
614 lib = [lib]
613 lib = [lib]
615 elif lib is None:
614 elif lib is None:
616 lib = []
615 lib = []
617 if isinstance(css, string_types):
616 if isinstance(css, string_types):
618 css = [css]
617 css = [css]
619 elif css is None:
618 elif css is None:
620 css = []
619 css = []
621 if not isinstance(lib, (list,tuple)):
620 if not isinstance(lib, (list,tuple)):
622 raise TypeError('expected sequence, got: %r' % lib)
621 raise TypeError('expected sequence, got: %r' % lib)
623 if not isinstance(css, (list,tuple)):
622 if not isinstance(css, (list,tuple)):
624 raise TypeError('expected sequence, got: %r' % css)
623 raise TypeError('expected sequence, got: %r' % css)
625 self.lib = lib
624 self.lib = lib
626 self.css = css
625 self.css = css
627 super(Javascript, self).__init__(data=data, url=url, filename=filename)
626 super(Javascript, self).__init__(data=data, url=url, filename=filename)
628
627
629 def _repr_javascript_(self):
628 def _repr_javascript_(self):
630 r = ''
629 r = ''
631 for c in self.css:
630 for c in self.css:
632 r += css_t % c
631 r += css_t % c
633 for l in self.lib:
632 for l in self.lib:
634 r += lib_t1 % l
633 r += lib_t1 % l
635 r += self.data
634 r += self.data
636 r += lib_t2*len(self.lib)
635 r += lib_t2*len(self.lib)
637 return r
636 return r
638
637
639 # constants for identifying png/jpeg data
638 # constants for identifying png/jpeg data
640 _PNG = b'\x89PNG\r\n\x1a\n'
639 _PNG = b'\x89PNG\r\n\x1a\n'
641 _JPEG = b'\xff\xd8'
640 _JPEG = b'\xff\xd8'
642
641
643 def _pngxy(data):
642 def _pngxy(data):
644 """read the (width, height) from a PNG header"""
643 """read the (width, height) from a PNG header"""
645 ihdr = data.index(b'IHDR')
644 ihdr = data.index(b'IHDR')
646 # next 8 bytes are width/height
645 # next 8 bytes are width/height
647 w4h4 = data[ihdr+4:ihdr+12]
646 w4h4 = data[ihdr+4:ihdr+12]
648 return struct.unpack('>ii', w4h4)
647 return struct.unpack('>ii', w4h4)
649
648
650 def _jpegxy(data):
649 def _jpegxy(data):
651 """read the (width, height) from a JPEG header"""
650 """read the (width, height) from a JPEG header"""
652 # adapted from http://www.64lines.com/jpeg-width-height
651 # adapted from http://www.64lines.com/jpeg-width-height
653
652
654 idx = 4
653 idx = 4
655 while True:
654 while True:
656 block_size = struct.unpack('>H', data[idx:idx+2])[0]
655 block_size = struct.unpack('>H', data[idx:idx+2])[0]
657 idx = idx + block_size
656 idx = idx + block_size
658 if data[idx:idx+2] == b'\xFF\xC0':
657 if data[idx:idx+2] == b'\xFF\xC0':
659 # found Start of Frame
658 # found Start of Frame
660 iSOF = idx
659 iSOF = idx
661 break
660 break
662 else:
661 else:
663 # read another block
662 # read another block
664 idx += 2
663 idx += 2
665
664
666 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
665 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
667 return w, h
666 return w, h
668
667
669 class Image(DisplayObject):
668 class Image(DisplayObject):
670
669
671 _read_flags = 'rb'
670 _read_flags = 'rb'
672 _FMT_JPEG = u'jpeg'
671 _FMT_JPEG = u'jpeg'
673 _FMT_PNG = u'png'
672 _FMT_PNG = u'png'
674 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
673 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
675
674
676 def __init__(self, data=None, url=None, filename=None, format=None,
675 def __init__(self, data=None, url=None, filename=None, format=None,
677 embed=None, width=None, height=None, retina=False,
676 embed=None, width=None, height=None, retina=False,
678 unconfined=False, metadata=None):
677 unconfined=False, metadata=None):
679 """Create a PNG/JPEG image object given raw data.
678 """Create a PNG/JPEG image object given raw data.
680
679
681 When this object is returned by an input cell or passed to the
680 When this object is returned by an input cell or passed to the
682 display function, it will result in the image being displayed
681 display function, it will result in the image being displayed
683 in the frontend.
682 in the frontend.
684
683
685 Parameters
684 Parameters
686 ----------
685 ----------
687 data : unicode, str or bytes
686 data : unicode, str or bytes
688 The raw image data or a URL or filename to load the data from.
687 The raw image data or a URL or filename to load the data from.
689 This always results in embedded image data.
688 This always results in embedded image data.
690 url : unicode
689 url : unicode
691 A URL to download the data from. If you specify `url=`,
690 A URL to download the data from. If you specify `url=`,
692 the image data will not be embedded unless you also specify `embed=True`.
691 the image data will not be embedded unless you also specify `embed=True`.
693 filename : unicode
692 filename : unicode
694 Path to a local file to load the data from.
693 Path to a local file to load the data from.
695 Images from a file are always embedded.
694 Images from a file are always embedded.
696 format : unicode
695 format : unicode
697 The format of the image data (png/jpeg/jpg). If a filename or URL is given
696 The format of the image data (png/jpeg/jpg). If a filename or URL is given
698 for format will be inferred from the filename extension.
697 for format will be inferred from the filename extension.
699 embed : bool
698 embed : bool
700 Should the image data be embedded using a data URI (True) or be
699 Should the image data be embedded using a data URI (True) or be
701 loaded using an <img> tag. Set this to True if you want the image
700 loaded using an <img> tag. Set this to True if you want the image
702 to be viewable later with no internet connection in the notebook.
701 to be viewable later with no internet connection in the notebook.
703
702
704 Default is `True`, unless the keyword argument `url` is set, then
703 Default is `True`, unless the keyword argument `url` is set, then
705 default value is `False`.
704 default value is `False`.
706
705
707 Note that QtConsole is not able to display images if `embed` is set to `False`
706 Note that QtConsole is not able to display images if `embed` is set to `False`
708 width : int
707 width : int
709 Width in pixels to which to constrain the image in html
708 Width in pixels to which to constrain the image in html
710 height : int
709 height : int
711 Height in pixels to which to constrain the image in html
710 Height in pixels to which to constrain the image in html
712 retina : bool
711 retina : bool
713 Automatically set the width and height to half of the measured
712 Automatically set the width and height to half of the measured
714 width and height.
713 width and height.
715 This only works for embedded images because it reads the width/height
714 This only works for embedded images because it reads the width/height
716 from image data.
715 from image data.
717 For non-embedded images, you can just set the desired display width
716 For non-embedded images, you can just set the desired display width
718 and height directly.
717 and height directly.
719 unconfined: bool
718 unconfined: bool
720 Set unconfined=True to disable max-width confinement of the image.
719 Set unconfined=True to disable max-width confinement of the image.
721 metadata: dict
720 metadata: dict
722 Specify extra metadata to attach to the image.
721 Specify extra metadata to attach to the image.
723
722
724 Examples
723 Examples
725 --------
724 --------
726 # embedded image data, works in qtconsole and notebook
725 # embedded image data, works in qtconsole and notebook
727 # when passed positionally, the first arg can be any of raw image data,
726 # when passed positionally, the first arg can be any of raw image data,
728 # a URL, or a filename from which to load image data.
727 # a URL, or a filename from which to load image data.
729 # The result is always embedding image data for inline images.
728 # The result is always embedding image data for inline images.
730 Image('http://www.google.fr/images/srpr/logo3w.png')
729 Image('http://www.google.fr/images/srpr/logo3w.png')
731 Image('/path/to/image.jpg')
730 Image('/path/to/image.jpg')
732 Image(b'RAW_PNG_DATA...')
731 Image(b'RAW_PNG_DATA...')
733
732
734 # Specifying Image(url=...) does not embed the image data,
733 # Specifying Image(url=...) does not embed the image data,
735 # it only generates `<img>` tag with a link to the source.
734 # it only generates `<img>` tag with a link to the source.
736 # This will not work in the qtconsole or offline.
735 # This will not work in the qtconsole or offline.
737 Image(url='http://www.google.fr/images/srpr/logo3w.png')
736 Image(url='http://www.google.fr/images/srpr/logo3w.png')
738
737
739 """
738 """
740 if filename is not None:
739 if filename is not None:
741 ext = self._find_ext(filename)
740 ext = self._find_ext(filename)
742 elif url is not None:
741 elif url is not None:
743 ext = self._find_ext(url)
742 ext = self._find_ext(url)
744 elif data is None:
743 elif data is None:
745 raise ValueError("No image data found. Expecting filename, url, or data.")
744 raise ValueError("No image data found. Expecting filename, url, or data.")
746 elif isinstance(data, string_types) and (
745 elif isinstance(data, string_types) and (
747 data.startswith('http') or _safe_exists(data)
746 data.startswith('http') or _safe_exists(data)
748 ):
747 ):
749 ext = self._find_ext(data)
748 ext = self._find_ext(data)
750 else:
749 else:
751 ext = None
750 ext = None
752
751
753 if format is None:
752 if format is None:
754 if ext is not None:
753 if ext is not None:
755 if ext == u'jpg' or ext == u'jpeg':
754 if ext == u'jpg' or ext == u'jpeg':
756 format = self._FMT_JPEG
755 format = self._FMT_JPEG
757 if ext == u'png':
756 if ext == u'png':
758 format = self._FMT_PNG
757 format = self._FMT_PNG
759 else:
758 else:
760 format = ext.lower()
759 format = ext.lower()
761 elif isinstance(data, bytes):
760 elif isinstance(data, bytes):
762 # infer image type from image data header,
761 # infer image type from image data header,
763 # only if format has not been specified.
762 # only if format has not been specified.
764 if data[:2] == _JPEG:
763 if data[:2] == _JPEG:
765 format = self._FMT_JPEG
764 format = self._FMT_JPEG
766
765
767 # failed to detect format, default png
766 # failed to detect format, default png
768 if format is None:
767 if format is None:
769 format = 'png'
768 format = 'png'
770
769
771 if format.lower() == 'jpg':
770 if format.lower() == 'jpg':
772 # jpg->jpeg
771 # jpg->jpeg
773 format = self._FMT_JPEG
772 format = self._FMT_JPEG
774
773
775 self.format = unicode_type(format).lower()
774 self.format = unicode_type(format).lower()
776 self.embed = embed if embed is not None else (url is None)
775 self.embed = embed if embed is not None else (url is None)
777
776
778 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
777 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
779 raise ValueError("Cannot embed the '%s' image format" % (self.format))
778 raise ValueError("Cannot embed the '%s' image format" % (self.format))
780 self.width = width
779 self.width = width
781 self.height = height
780 self.height = height
782 self.retina = retina
781 self.retina = retina
783 self.unconfined = unconfined
782 self.unconfined = unconfined
784 self.metadata = metadata
783 self.metadata = metadata
785 super(Image, self).__init__(data=data, url=url, filename=filename)
784 super(Image, self).__init__(data=data, url=url, filename=filename)
786
785
787 if retina:
786 if retina:
788 self._retina_shape()
787 self._retina_shape()
789
788
790 def _retina_shape(self):
789 def _retina_shape(self):
791 """load pixel-doubled width and height from image data"""
790 """load pixel-doubled width and height from image data"""
792 if not self.embed:
791 if not self.embed:
793 return
792 return
794 if self.format == 'png':
793 if self.format == 'png':
795 w, h = _pngxy(self.data)
794 w, h = _pngxy(self.data)
796 elif self.format == 'jpeg':
795 elif self.format == 'jpeg':
797 w, h = _jpegxy(self.data)
796 w, h = _jpegxy(self.data)
798 else:
797 else:
799 # retina only supports png
798 # retina only supports png
800 return
799 return
801 self.width = w // 2
800 self.width = w // 2
802 self.height = h // 2
801 self.height = h // 2
803
802
804 def reload(self):
803 def reload(self):
805 """Reload the raw data from file or URL."""
804 """Reload the raw data from file or URL."""
806 if self.embed:
805 if self.embed:
807 super(Image,self).reload()
806 super(Image,self).reload()
808 if self.retina:
807 if self.retina:
809 self._retina_shape()
808 self._retina_shape()
810
809
811 def _repr_html_(self):
810 def _repr_html_(self):
812 if not self.embed:
811 if not self.embed:
813 width = height = klass = ''
812 width = height = klass = ''
814 if self.width:
813 if self.width:
815 width = ' width="%d"' % self.width
814 width = ' width="%d"' % self.width
816 if self.height:
815 if self.height:
817 height = ' height="%d"' % self.height
816 height = ' height="%d"' % self.height
818 if self.unconfined:
817 if self.unconfined:
819 klass = ' class="unconfined"'
818 klass = ' class="unconfined"'
820 return u'<img src="{url}"{width}{height}{klass}/>'.format(
819 return u'<img src="{url}"{width}{height}{klass}/>'.format(
821 url=self.url,
820 url=self.url,
822 width=width,
821 width=width,
823 height=height,
822 height=height,
824 klass=klass,
823 klass=klass,
825 )
824 )
826
825
827 def _data_and_metadata(self):
826 def _data_and_metadata(self):
828 """shortcut for returning metadata with shape information, if defined"""
827 """shortcut for returning metadata with shape information, if defined"""
829 md = {}
828 md = {}
830 if self.width:
829 if self.width:
831 md['width'] = self.width
830 md['width'] = self.width
832 if self.height:
831 if self.height:
833 md['height'] = self.height
832 md['height'] = self.height
834 if self.unconfined:
833 if self.unconfined:
835 md['unconfined'] = self.unconfined
834 md['unconfined'] = self.unconfined
836 if self.metadata:
835 if self.metadata:
837 md.update(self.metadata)
836 md.update(self.metadata)
838 if md:
837 if md:
839 return self.data, md
838 return self.data, md
840 else:
839 else:
841 return self.data
840 return self.data
842
841
843 def _repr_png_(self):
842 def _repr_png_(self):
844 if self.embed and self.format == u'png':
843 if self.embed and self.format == u'png':
845 return self._data_and_metadata()
844 return self._data_and_metadata()
846
845
847 def _repr_jpeg_(self):
846 def _repr_jpeg_(self):
848 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
847 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
849 return self._data_and_metadata()
848 return self._data_and_metadata()
850
849
851 def _find_ext(self, s):
850 def _find_ext(self, s):
852 return unicode_type(s.split('.')[-1].lower())
851 return unicode_type(s.split('.')[-1].lower())
853
852
854 class Video(DisplayObject):
853 class Video(DisplayObject):
855
854
856 def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
855 def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
857 """Create a video object given raw data or an URL.
856 """Create a video object given raw data or an URL.
858
857
859 When this object is returned by an input cell or passed to the
858 When this object is returned by an input cell or passed to the
860 display function, it will result in the video being displayed
859 display function, it will result in the video being displayed
861 in the frontend.
860 in the frontend.
862
861
863 Parameters
862 Parameters
864 ----------
863 ----------
865 data : unicode, str or bytes
864 data : unicode, str or bytes
866 The raw video data or a URL or filename to load the data from.
865 The raw video data or a URL or filename to load the data from.
867 Raw data will require passing `embed=True`.
866 Raw data will require passing `embed=True`.
868 url : unicode
867 url : unicode
869 A URL for the video. If you specify `url=`,
868 A URL for the video. If you specify `url=`,
870 the image data will not be embedded.
869 the image data will not be embedded.
871 filename : unicode
870 filename : unicode
872 Path to a local file containing the video.
871 Path to a local file containing the video.
873 Will be interpreted as a local URL unless `embed=True`.
872 Will be interpreted as a local URL unless `embed=True`.
874 embed : bool
873 embed : bool
875 Should the video be embedded using a data URI (True) or be
874 Should the video be embedded using a data URI (True) or be
876 loaded using a <video> tag (False).
875 loaded using a <video> tag (False).
877
876
878 Since videos are large, embedding them should be avoided, if possible.
877 Since videos are large, embedding them should be avoided, if possible.
879 You must confirm embedding as your intention by passing `embed=True`.
878 You must confirm embedding as your intention by passing `embed=True`.
880
879
881 Local files can be displayed with URLs without embedding the content, via::
880 Local files can be displayed with URLs without embedding the content, via::
882
881
883 Video('./video.mp4')
882 Video('./video.mp4')
884
883
885 mimetype: unicode
884 mimetype: unicode
886 Specify the mimetype for embedded videos.
885 Specify the mimetype for embedded videos.
887 Default will be guessed from file extension, if available.
886 Default will be guessed from file extension, if available.
888
887
889 Examples
888 Examples
890 --------
889 --------
891
890
892 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
891 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
893 Video('path/to/video.mp4')
892 Video('path/to/video.mp4')
894 Video('path/to/video.mp4', embed=True)
893 Video('path/to/video.mp4', embed=True)
895 Video(b'raw-videodata', embed=True)
894 Video(b'raw-videodata', embed=True)
896 """
895 """
897 if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
896 if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
898 url = data
897 url = data
899 data = None
898 data = None
900 elif os.path.exists(data):
899 elif os.path.exists(data):
901 filename = data
900 filename = data
902 data = None
901 data = None
903
902
904 if data and not embed:
903 if data and not embed:
905 msg = ''.join([
904 msg = ''.join([
906 "To embed videos, you must pass embed=True ",
905 "To embed videos, you must pass embed=True ",
907 "(this may make your notebook files huge)\n",
906 "(this may make your notebook files huge)\n",
908 "Consider passing Video(url='...')",
907 "Consider passing Video(url='...')",
909 ])
908 ])
910 raise ValueError(msg)
909 raise ValueError(msg)
911
910
912 self.mimetype = mimetype
911 self.mimetype = mimetype
913 self.embed = embed
912 self.embed = embed
914 super(Video, self).__init__(data=data, url=url, filename=filename)
913 super(Video, self).__init__(data=data, url=url, filename=filename)
915
914
916 def _repr_html_(self):
915 def _repr_html_(self):
917 # External URLs and potentially local files are not embedded into the
916 # External URLs and potentially local files are not embedded into the
918 # notebook output.
917 # notebook output.
919 if not self.embed:
918 if not self.embed:
920 url = self.url if self.url is not None else self.filename
919 url = self.url if self.url is not None else self.filename
921 output = """<video src="{0}" controls>
920 output = """<video src="{0}" controls>
922 Your browser does not support the <code>video</code> element.
921 Your browser does not support the <code>video</code> element.
923 </video>""".format(url)
922 </video>""".format(url)
924 return output
923 return output
925
924
926 # Embedded videos are base64-encoded.
925 # Embedded videos are base64-encoded.
927 mimetype = self.mimetype
926 mimetype = self.mimetype
928 if self.filename is not None:
927 if self.filename is not None:
929 if not mimetype:
928 if not mimetype:
930 mimetype, _ = mimetypes.guess_type(self.filename)
929 mimetype, _ = mimetypes.guess_type(self.filename)
931
930
932 with open(self.filename, 'rb') as f:
931 with open(self.filename, 'rb') as f:
933 video = f.read()
932 video = f.read()
934 else:
933 else:
935 video = self.data
934 video = self.data
936 if isinstance(video, unicode_type):
935 if isinstance(video, unicode_type):
937 # unicode input is already b64-encoded
936 # unicode input is already b64-encoded
938 b64_video = video
937 b64_video = video
939 else:
938 else:
940 b64_video = base64_encode(video).decode('ascii').rstrip()
939 b64_video = base64_encode(video).decode('ascii').rstrip()
941
940
942 output = """<video controls>
941 output = """<video controls>
943 <source src="data:{0};base64,{1}" type="{0}">
942 <source src="data:{0};base64,{1}" type="{0}">
944 Your browser does not support the video tag.
943 Your browser does not support the video tag.
945 </video>""".format(mimetype, b64_video)
944 </video>""".format(mimetype, b64_video)
946 return output
945 return output
947
946
948 def reload(self):
947 def reload(self):
949 # TODO
948 # TODO
950 pass
949 pass
951
950
952 def _repr_png_(self):
951 def _repr_png_(self):
953 # TODO
952 # TODO
954 pass
953 pass
955 def _repr_jpeg_(self):
954 def _repr_jpeg_(self):
956 # TODO
955 # TODO
957 pass
956 pass
958
957
959 def clear_output(wait=False):
958 def clear_output(wait=False):
960 """Clear the output of the current cell receiving output.
959 """Clear the output of the current cell receiving output.
961
960
962 Parameters
961 Parameters
963 ----------
962 ----------
964 wait : bool [default: false]
963 wait : bool [default: false]
965 Wait to clear the output until new output is available to replace it."""
964 Wait to clear the output until new output is available to replace it."""
966 from IPython.core.interactiveshell import InteractiveShell
965 from IPython.core.interactiveshell import InteractiveShell
967 if InteractiveShell.initialized():
966 if InteractiveShell.initialized():
968 InteractiveShell.instance().display_pub.clear_output(wait)
967 InteractiveShell.instance().display_pub.clear_output(wait)
969 else:
968 else:
970 print('\033[2K\r', end='')
969 print('\033[2K\r', end='')
971 sys.stdout.flush()
970 sys.stdout.flush()
972 print('\033[2K\r', end='')
971 print('\033[2K\r', end='')
973 sys.stderr.flush()
972 sys.stderr.flush()
974
973
975
974
976 @skip_doctest
975 @skip_doctest
977 def set_matplotlib_formats(*formats, **kwargs):
976 def set_matplotlib_formats(*formats, **kwargs):
978 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
977 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
979
978
980 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
979 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
981
980
982 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
981 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
983
982
984 To set this in your config files use the following::
983 To set this in your config files use the following::
985
984
986 c.InlineBackend.figure_formats = {'png', 'jpeg'}
985 c.InlineBackend.figure_formats = {'png', 'jpeg'}
987 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
986 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
988
987
989 Parameters
988 Parameters
990 ----------
989 ----------
991 *formats : strs
990 *formats : strs
992 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
991 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
993 **kwargs :
992 **kwargs :
994 Keyword args will be relayed to ``figure.canvas.print_figure``.
993 Keyword args will be relayed to ``figure.canvas.print_figure``.
995 """
994 """
996 from IPython.core.interactiveshell import InteractiveShell
995 from IPython.core.interactiveshell import InteractiveShell
997 from IPython.core.pylabtools import select_figure_formats
996 from IPython.core.pylabtools import select_figure_formats
998 # build kwargs, starting with InlineBackend config
997 # build kwargs, starting with InlineBackend config
999 kw = {}
998 kw = {}
1000 from ipykernel.pylab.config import InlineBackend
999 from ipykernel.pylab.config import InlineBackend
1001 cfg = InlineBackend.instance()
1000 cfg = InlineBackend.instance()
1002 kw.update(cfg.print_figure_kwargs)
1001 kw.update(cfg.print_figure_kwargs)
1003 kw.update(**kwargs)
1002 kw.update(**kwargs)
1004 shell = InteractiveShell.instance()
1003 shell = InteractiveShell.instance()
1005 select_figure_formats(shell, formats, **kw)
1004 select_figure_formats(shell, formats, **kw)
1006
1005
1007 @skip_doctest
1006 @skip_doctest
1008 def set_matplotlib_close(close=True):
1007 def set_matplotlib_close(close=True):
1009 """Set whether the inline backend closes all figures automatically or not.
1008 """Set whether the inline backend closes all figures automatically or not.
1010
1009
1011 By default, the inline backend used in the IPython Notebook will close all
1010 By default, the inline backend used in the IPython Notebook will close all
1012 matplotlib figures automatically after each cell is run. This means that
1011 matplotlib figures automatically after each cell is run. This means that
1013 plots in different cells won't interfere. Sometimes, you may want to make
1012 plots in different cells won't interfere. Sometimes, you may want to make
1014 a plot in one cell and then refine it in later cells. This can be accomplished
1013 a plot in one cell and then refine it in later cells. This can be accomplished
1015 by::
1014 by::
1016
1015
1017 In [1]: set_matplotlib_close(False)
1016 In [1]: set_matplotlib_close(False)
1018
1017
1019 To set this in your config files use the following::
1018 To set this in your config files use the following::
1020
1019
1021 c.InlineBackend.close_figures = False
1020 c.InlineBackend.close_figures = False
1022
1021
1023 Parameters
1022 Parameters
1024 ----------
1023 ----------
1025 close : bool
1024 close : bool
1026 Should all matplotlib figures be automatically closed after each cell is
1025 Should all matplotlib figures be automatically closed after each cell is
1027 run?
1026 run?
1028 """
1027 """
1029 from ipykernel.pylab.config import InlineBackend
1028 from ipykernel.pylab.config import InlineBackend
1030 cfg = InlineBackend.instance()
1029 cfg = InlineBackend.instance()
1031 cfg.close_figures = close
1030 cfg.close_figures = close
@@ -1,322 +1,321 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
2 """Displayhook for IPython.
3
3
4 This defines a callable class that IPython uses for `sys.displayhook`.
4 This defines a callable class that IPython uses for `sys.displayhook`.
5 """
5 """
6
6
7 # Copyright (c) IPython Development Team.
7 # Copyright (c) IPython Development Team.
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9
9
10 from __future__ import print_function
11
10
12 import sys
11 import sys
13 import io as _io
12 import io as _io
14 import tokenize
13 import tokenize
15
14
16 from traitlets.config.configurable import Configurable
15 from traitlets.config.configurable import Configurable
17 from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
16 from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
18 from traitlets import Instance, Float
17 from traitlets import Instance, Float
19 from warnings import warn
18 from warnings import warn
20
19
21 # TODO: Move the various attributes (cache_size, [others now moved]). Some
20 # TODO: Move the various attributes (cache_size, [others now moved]). Some
22 # of these are also attributes of InteractiveShell. They should be on ONE object
21 # of these are also attributes of InteractiveShell. They should be on ONE object
23 # only and the other objects should ask that one object for their values.
22 # only and the other objects should ask that one object for their values.
24
23
25 class DisplayHook(Configurable):
24 class DisplayHook(Configurable):
26 """The custom IPython displayhook to replace sys.displayhook.
25 """The custom IPython displayhook to replace sys.displayhook.
27
26
28 This class does many things, but the basic idea is that it is a callable
27 This class does many things, but the basic idea is that it is a callable
29 that gets called anytime user code returns a value.
28 that gets called anytime user code returns a value.
30 """
29 """
31
30
32 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
31 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
33 allow_none=True)
32 allow_none=True)
34 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
33 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
35 allow_none=True)
34 allow_none=True)
36 cull_fraction = Float(0.2)
35 cull_fraction = Float(0.2)
37
36
38 def __init__(self, shell=None, cache_size=1000, **kwargs):
37 def __init__(self, shell=None, cache_size=1000, **kwargs):
39 super(DisplayHook, self).__init__(shell=shell, **kwargs)
38 super(DisplayHook, self).__init__(shell=shell, **kwargs)
40 cache_size_min = 3
39 cache_size_min = 3
41 if cache_size <= 0:
40 if cache_size <= 0:
42 self.do_full_cache = 0
41 self.do_full_cache = 0
43 cache_size = 0
42 cache_size = 0
44 elif cache_size < cache_size_min:
43 elif cache_size < cache_size_min:
45 self.do_full_cache = 0
44 self.do_full_cache = 0
46 cache_size = 0
45 cache_size = 0
47 warn('caching was disabled (min value for cache size is %s).' %
46 warn('caching was disabled (min value for cache size is %s).' %
48 cache_size_min,level=3)
47 cache_size_min,level=3)
49 else:
48 else:
50 self.do_full_cache = 1
49 self.do_full_cache = 1
51
50
52 self.cache_size = cache_size
51 self.cache_size = cache_size
53
52
54 # we need a reference to the user-level namespace
53 # we need a reference to the user-level namespace
55 self.shell = shell
54 self.shell = shell
56
55
57 self._,self.__,self.___ = '','',''
56 self._,self.__,self.___ = '','',''
58
57
59 # these are deliberately global:
58 # these are deliberately global:
60 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
59 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
61 self.shell.user_ns.update(to_user_ns)
60 self.shell.user_ns.update(to_user_ns)
62
61
63 @property
62 @property
64 def prompt_count(self):
63 def prompt_count(self):
65 return self.shell.execution_count
64 return self.shell.execution_count
66
65
67 #-------------------------------------------------------------------------
66 #-------------------------------------------------------------------------
68 # Methods used in __call__. Override these methods to modify the behavior
67 # Methods used in __call__. Override these methods to modify the behavior
69 # of the displayhook.
68 # of the displayhook.
70 #-------------------------------------------------------------------------
69 #-------------------------------------------------------------------------
71
70
72 def check_for_underscore(self):
71 def check_for_underscore(self):
73 """Check if the user has set the '_' variable by hand."""
72 """Check if the user has set the '_' variable by hand."""
74 # If something injected a '_' variable in __builtin__, delete
73 # If something injected a '_' variable in __builtin__, delete
75 # ipython's automatic one so we don't clobber that. gettext() in
74 # ipython's automatic one so we don't clobber that. gettext() in
76 # particular uses _, so we need to stay away from it.
75 # particular uses _, so we need to stay away from it.
77 if '_' in builtin_mod.__dict__:
76 if '_' in builtin_mod.__dict__:
78 try:
77 try:
79 user_value = self.shell.user_ns['_']
78 user_value = self.shell.user_ns['_']
80 if user_value is not self._:
79 if user_value is not self._:
81 return
80 return
82 del self.shell.user_ns['_']
81 del self.shell.user_ns['_']
83 except KeyError:
82 except KeyError:
84 pass
83 pass
85
84
86 def quiet(self):
85 def quiet(self):
87 """Should we silence the display hook because of ';'?"""
86 """Should we silence the display hook because of ';'?"""
88 # do not print output if input ends in ';'
87 # do not print output if input ends in ';'
89
88
90 try:
89 try:
91 cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
90 cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
92 except IndexError:
91 except IndexError:
93 # some uses of ipshellembed may fail here
92 # some uses of ipshellembed may fail here
94 return False
93 return False
95
94
96 sio = _io.StringIO(cell)
95 sio = _io.StringIO(cell)
97 tokens = list(tokenize.generate_tokens(sio.readline))
96 tokens = list(tokenize.generate_tokens(sio.readline))
98
97
99 for token in reversed(tokens):
98 for token in reversed(tokens):
100 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
99 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
101 continue
100 continue
102 if (token[0] == tokenize.OP) and (token[1] == ';'):
101 if (token[0] == tokenize.OP) and (token[1] == ';'):
103 return True
102 return True
104 else:
103 else:
105 return False
104 return False
106
105
107 def start_displayhook(self):
106 def start_displayhook(self):
108 """Start the displayhook, initializing resources."""
107 """Start the displayhook, initializing resources."""
109 pass
108 pass
110
109
111 def write_output_prompt(self):
110 def write_output_prompt(self):
112 """Write the output prompt.
111 """Write the output prompt.
113
112
114 The default implementation simply writes the prompt to
113 The default implementation simply writes the prompt to
115 ``sys.stdout``.
114 ``sys.stdout``.
116 """
115 """
117 # Use write, not print which adds an extra space.
116 # Use write, not print which adds an extra space.
118 sys.stdout.write(self.shell.separate_out)
117 sys.stdout.write(self.shell.separate_out)
119 outprompt = 'Out[{}]: '.format(self.shell.execution_count)
118 outprompt = 'Out[{}]: '.format(self.shell.execution_count)
120 if self.do_full_cache:
119 if self.do_full_cache:
121 sys.stdout.write(outprompt)
120 sys.stdout.write(outprompt)
122
121
123 def compute_format_data(self, result):
122 def compute_format_data(self, result):
124 """Compute format data of the object to be displayed.
123 """Compute format data of the object to be displayed.
125
124
126 The format data is a generalization of the :func:`repr` of an object.
125 The format data is a generalization of the :func:`repr` of an object.
127 In the default implementation the format data is a :class:`dict` of
126 In the default implementation the format data is a :class:`dict` of
128 key value pair where the keys are valid MIME types and the values
127 key value pair where the keys are valid MIME types and the values
129 are JSON'able data structure containing the raw data for that MIME
128 are JSON'able data structure containing the raw data for that MIME
130 type. It is up to frontends to determine pick a MIME to to use and
129 type. It is up to frontends to determine pick a MIME to to use and
131 display that data in an appropriate manner.
130 display that data in an appropriate manner.
132
131
133 This method only computes the format data for the object and should
132 This method only computes the format data for the object and should
134 NOT actually print or write that to a stream.
133 NOT actually print or write that to a stream.
135
134
136 Parameters
135 Parameters
137 ----------
136 ----------
138 result : object
137 result : object
139 The Python object passed to the display hook, whose format will be
138 The Python object passed to the display hook, whose format will be
140 computed.
139 computed.
141
140
142 Returns
141 Returns
143 -------
142 -------
144 (format_dict, md_dict) : dict
143 (format_dict, md_dict) : dict
145 format_dict is a :class:`dict` whose keys are valid MIME types and values are
144 format_dict is a :class:`dict` whose keys are valid MIME types and values are
146 JSON'able raw data for that MIME type. It is recommended that
145 JSON'able raw data for that MIME type. It is recommended that
147 all return values of this should always include the "text/plain"
146 all return values of this should always include the "text/plain"
148 MIME type representation of the object.
147 MIME type representation of the object.
149 md_dict is a :class:`dict` with the same MIME type keys
148 md_dict is a :class:`dict` with the same MIME type keys
150 of metadata associated with each output.
149 of metadata associated with each output.
151
150
152 """
151 """
153 return self.shell.display_formatter.format(result)
152 return self.shell.display_formatter.format(result)
154
153
155 # This can be set to True by the write_output_prompt method in a subclass
154 # This can be set to True by the write_output_prompt method in a subclass
156 prompt_end_newline = False
155 prompt_end_newline = False
157
156
158 def write_format_data(self, format_dict, md_dict=None):
157 def write_format_data(self, format_dict, md_dict=None):
159 """Write the format data dict to the frontend.
158 """Write the format data dict to the frontend.
160
159
161 This default version of this method simply writes the plain text
160 This default version of this method simply writes the plain text
162 representation of the object to ``sys.stdout``. Subclasses should
161 representation of the object to ``sys.stdout``. Subclasses should
163 override this method to send the entire `format_dict` to the
162 override this method to send the entire `format_dict` to the
164 frontends.
163 frontends.
165
164
166 Parameters
165 Parameters
167 ----------
166 ----------
168 format_dict : dict
167 format_dict : dict
169 The format dict for the object passed to `sys.displayhook`.
168 The format dict for the object passed to `sys.displayhook`.
170 md_dict : dict (optional)
169 md_dict : dict (optional)
171 The metadata dict to be associated with the display data.
170 The metadata dict to be associated with the display data.
172 """
171 """
173 if 'text/plain' not in format_dict:
172 if 'text/plain' not in format_dict:
174 # nothing to do
173 # nothing to do
175 return
174 return
176 # We want to print because we want to always make sure we have a
175 # We want to print because we want to always make sure we have a
177 # newline, even if all the prompt separators are ''. This is the
176 # newline, even if all the prompt separators are ''. This is the
178 # standard IPython behavior.
177 # standard IPython behavior.
179 result_repr = format_dict['text/plain']
178 result_repr = format_dict['text/plain']
180 if '\n' in result_repr:
179 if '\n' in result_repr:
181 # So that multi-line strings line up with the left column of
180 # So that multi-line strings line up with the left column of
182 # the screen, instead of having the output prompt mess up
181 # the screen, instead of having the output prompt mess up
183 # their first line.
182 # their first line.
184 # We use the prompt template instead of the expanded prompt
183 # We use the prompt template instead of the expanded prompt
185 # because the expansion may add ANSI escapes that will interfere
184 # because the expansion may add ANSI escapes that will interfere
186 # with our ability to determine whether or not we should add
185 # with our ability to determine whether or not we should add
187 # a newline.
186 # a newline.
188 if not self.prompt_end_newline:
187 if not self.prompt_end_newline:
189 # But avoid extraneous empty lines.
188 # But avoid extraneous empty lines.
190 result_repr = '\n' + result_repr
189 result_repr = '\n' + result_repr
191
190
192 print(result_repr)
191 print(result_repr)
193
192
194 def update_user_ns(self, result):
193 def update_user_ns(self, result):
195 """Update user_ns with various things like _, __, _1, etc."""
194 """Update user_ns with various things like _, __, _1, etc."""
196
195
197 # Avoid recursive reference when displaying _oh/Out
196 # Avoid recursive reference when displaying _oh/Out
198 if result is not self.shell.user_ns['_oh']:
197 if result is not self.shell.user_ns['_oh']:
199 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
198 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
200 self.cull_cache()
199 self.cull_cache()
201
200
202 # Don't overwrite '_' and friends if '_' is in __builtin__
201 # Don't overwrite '_' and friends if '_' is in __builtin__
203 # (otherwise we cause buggy behavior for things like gettext). and
202 # (otherwise we cause buggy behavior for things like gettext). and
204 # do not overwrite _, __ or ___ if one of these has been assigned
203 # do not overwrite _, __ or ___ if one of these has been assigned
205 # by the user.
204 # by the user.
206 update_unders = True
205 update_unders = True
207 for unders in ['_'*i for i in range(1,4)]:
206 for unders in ['_'*i for i in range(1,4)]:
208 if not unders in self.shell.user_ns:
207 if not unders in self.shell.user_ns:
209 continue
208 continue
210 if getattr(self, unders) is not self.shell.user_ns.get(unders):
209 if getattr(self, unders) is not self.shell.user_ns.get(unders):
211 update_unders = False
210 update_unders = False
212
211
213 self.___ = self.__
212 self.___ = self.__
214 self.__ = self._
213 self.__ = self._
215 self._ = result
214 self._ = result
216
215
217 if ('_' not in builtin_mod.__dict__) and (update_unders):
216 if ('_' not in builtin_mod.__dict__) and (update_unders):
218 self.shell.push({'_':self._,
217 self.shell.push({'_':self._,
219 '__':self.__,
218 '__':self.__,
220 '___':self.___}, interactive=False)
219 '___':self.___}, interactive=False)
221
220
222 # hackish access to top-level namespace to create _1,_2... dynamically
221 # hackish access to top-level namespace to create _1,_2... dynamically
223 to_main = {}
222 to_main = {}
224 if self.do_full_cache:
223 if self.do_full_cache:
225 new_result = '_%s' % self.prompt_count
224 new_result = '_%s' % self.prompt_count
226 to_main[new_result] = result
225 to_main[new_result] = result
227 self.shell.push(to_main, interactive=False)
226 self.shell.push(to_main, interactive=False)
228 self.shell.user_ns['_oh'][self.prompt_count] = result
227 self.shell.user_ns['_oh'][self.prompt_count] = result
229
228
230 def fill_exec_result(self, result):
229 def fill_exec_result(self, result):
231 if self.exec_result is not None:
230 if self.exec_result is not None:
232 self.exec_result.result = result
231 self.exec_result.result = result
233
232
234 def log_output(self, format_dict):
233 def log_output(self, format_dict):
235 """Log the output."""
234 """Log the output."""
236 if 'text/plain' not in format_dict:
235 if 'text/plain' not in format_dict:
237 # nothing to do
236 # nothing to do
238 return
237 return
239 if self.shell.logger.log_output:
238 if self.shell.logger.log_output:
240 self.shell.logger.log_write(format_dict['text/plain'], 'output')
239 self.shell.logger.log_write(format_dict['text/plain'], 'output')
241 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
240 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
242 format_dict['text/plain']
241 format_dict['text/plain']
243
242
244 def finish_displayhook(self):
243 def finish_displayhook(self):
245 """Finish up all displayhook activities."""
244 """Finish up all displayhook activities."""
246 sys.stdout.write(self.shell.separate_out2)
245 sys.stdout.write(self.shell.separate_out2)
247 sys.stdout.flush()
246 sys.stdout.flush()
248
247
249 def __call__(self, result=None):
248 def __call__(self, result=None):
250 """Printing with history cache management.
249 """Printing with history cache management.
251
250
252 This is invoked everytime the interpreter needs to print, and is
251 This is invoked everytime the interpreter needs to print, and is
253 activated by setting the variable sys.displayhook to it.
252 activated by setting the variable sys.displayhook to it.
254 """
253 """
255 self.check_for_underscore()
254 self.check_for_underscore()
256 if result is not None and not self.quiet():
255 if result is not None and not self.quiet():
257 self.start_displayhook()
256 self.start_displayhook()
258 self.write_output_prompt()
257 self.write_output_prompt()
259 format_dict, md_dict = self.compute_format_data(result)
258 format_dict, md_dict = self.compute_format_data(result)
260 self.update_user_ns(result)
259 self.update_user_ns(result)
261 self.fill_exec_result(result)
260 self.fill_exec_result(result)
262 if format_dict:
261 if format_dict:
263 self.write_format_data(format_dict, md_dict)
262 self.write_format_data(format_dict, md_dict)
264 self.log_output(format_dict)
263 self.log_output(format_dict)
265 self.finish_displayhook()
264 self.finish_displayhook()
266
265
267 def cull_cache(self):
266 def cull_cache(self):
268 """Output cache is full, cull the oldest entries"""
267 """Output cache is full, cull the oldest entries"""
269 oh = self.shell.user_ns.get('_oh', {})
268 oh = self.shell.user_ns.get('_oh', {})
270 sz = len(oh)
269 sz = len(oh)
271 cull_count = max(int(sz * self.cull_fraction), 2)
270 cull_count = max(int(sz * self.cull_fraction), 2)
272 warn('Output cache limit (currently {sz} entries) hit.\n'
271 warn('Output cache limit (currently {sz} entries) hit.\n'
273 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
272 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
274
273
275 for i, n in enumerate(sorted(oh)):
274 for i, n in enumerate(sorted(oh)):
276 if i >= cull_count:
275 if i >= cull_count:
277 break
276 break
278 self.shell.user_ns.pop('_%i' % n, None)
277 self.shell.user_ns.pop('_%i' % n, None)
279 oh.pop(n, None)
278 oh.pop(n, None)
280
279
281
280
282 def flush(self):
281 def flush(self):
283 if not self.do_full_cache:
282 if not self.do_full_cache:
284 raise ValueError("You shouldn't have reached the cache flush "
283 raise ValueError("You shouldn't have reached the cache flush "
285 "if full caching is not enabled!")
284 "if full caching is not enabled!")
286 # delete auto-generated vars from global namespace
285 # delete auto-generated vars from global namespace
287
286
288 for n in range(1,self.prompt_count + 1):
287 for n in range(1,self.prompt_count + 1):
289 key = '_'+repr(n)
288 key = '_'+repr(n)
290 try:
289 try:
291 del self.shell.user_ns[key]
290 del self.shell.user_ns[key]
292 except: pass
291 except: pass
293 # In some embedded circumstances, the user_ns doesn't have the
292 # In some embedded circumstances, the user_ns doesn't have the
294 # '_oh' key set up.
293 # '_oh' key set up.
295 oh = self.shell.user_ns.get('_oh', None)
294 oh = self.shell.user_ns.get('_oh', None)
296 if oh is not None:
295 if oh is not None:
297 oh.clear()
296 oh.clear()
298
297
299 # Release our own references to objects:
298 # Release our own references to objects:
300 self._, self.__, self.___ = '', '', ''
299 self._, self.__, self.___ = '', '', ''
301
300
302 if '_' not in builtin_mod.__dict__:
301 if '_' not in builtin_mod.__dict__:
303 self.shell.user_ns.update({'_':None,'__':None, '___':None})
302 self.shell.user_ns.update({'_':None,'__':None, '___':None})
304 import gc
303 import gc
305 # TODO: Is this really needed?
304 # TODO: Is this really needed?
306 # IronPython blocks here forever
305 # IronPython blocks here forever
307 if sys.platform != "cli":
306 if sys.platform != "cli":
308 gc.collect()
307 gc.collect()
309
308
310
309
311 class CapturingDisplayHook(object):
310 class CapturingDisplayHook(object):
312 def __init__(self, shell, outputs=None):
311 def __init__(self, shell, outputs=None):
313 self.shell = shell
312 self.shell = shell
314 if outputs is None:
313 if outputs is None:
315 outputs = []
314 outputs = []
316 self.outputs = outputs
315 self.outputs = outputs
317
316
318 def __call__(self, result=None):
317 def __call__(self, result=None):
319 if result is None:
318 if result is None:
320 return
319 return
321 format_dict, md_dict = self.shell.display_formatter.format(result)
320 format_dict, md_dict = self.shell.display_formatter.format(result)
322 self.outputs.append((format_dict, md_dict))
321 self.outputs.append((format_dict, md_dict))
@@ -1,117 +1,116 b''
1 """An interface for publishing rich data to frontends.
1 """An interface for publishing rich data to frontends.
2
2
3 There are two components of the display system:
3 There are two components of the display system:
4
4
5 * Display formatters, which take a Python object and compute the
5 * Display formatters, which take a Python object and compute the
6 representation of the object in various formats (text, HTML, SVG, etc.).
6 representation of the object in various formats (text, HTML, SVG, etc.).
7 * The display publisher that is used to send the representation data to the
7 * The display publisher that is used to send the representation data to the
8 various frontends.
8 various frontends.
9
9
10 This module defines the logic display publishing. The display publisher uses
10 This module defines the logic display publishing. The display publisher uses
11 the ``display_data`` message type that is defined in the IPython messaging
11 the ``display_data`` message type that is defined in the IPython messaging
12 spec.
12 spec.
13 """
13 """
14
14
15 # Copyright (c) IPython Development Team.
15 # Copyright (c) IPython Development Team.
16 # Distributed under the terms of the Modified BSD License.
16 # Distributed under the terms of the Modified BSD License.
17
17
18 from __future__ import print_function
19
18
20 import sys
19 import sys
21
20
22 from traitlets.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
23 from traitlets import List
22 from traitlets import List
24
23
25 # This used to be defined here - it is imported for backwards compatibility
24 # This used to be defined here - it is imported for backwards compatibility
26 from .display import publish_display_data
25 from .display import publish_display_data
27
26
28 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
29 # Main payload class
28 # Main payload class
30 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
31
30
32 class DisplayPublisher(Configurable):
31 class DisplayPublisher(Configurable):
33 """A traited class that publishes display data to frontends.
32 """A traited class that publishes display data to frontends.
34
33
35 Instances of this class are created by the main IPython object and should
34 Instances of this class are created by the main IPython object and should
36 be accessed there.
35 be accessed there.
37 """
36 """
38
37
39 def _validate_data(self, data, metadata=None):
38 def _validate_data(self, data, metadata=None):
40 """Validate the display data.
39 """Validate the display data.
41
40
42 Parameters
41 Parameters
43 ----------
42 ----------
44 data : dict
43 data : dict
45 The formata data dictionary.
44 The formata data dictionary.
46 metadata : dict
45 metadata : dict
47 Any metadata for the data.
46 Any metadata for the data.
48 """
47 """
49
48
50 if not isinstance(data, dict):
49 if not isinstance(data, dict):
51 raise TypeError('data must be a dict, got: %r' % data)
50 raise TypeError('data must be a dict, got: %r' % data)
52 if metadata is not None:
51 if metadata is not None:
53 if not isinstance(metadata, dict):
52 if not isinstance(metadata, dict):
54 raise TypeError('metadata must be a dict, got: %r' % data)
53 raise TypeError('metadata must be a dict, got: %r' % data)
55
54
56 def publish(self, data, metadata=None, source=None):
55 def publish(self, data, metadata=None, source=None):
57 """Publish data and metadata to all frontends.
56 """Publish data and metadata to all frontends.
58
57
59 See the ``display_data`` message in the messaging documentation for
58 See the ``display_data`` message in the messaging documentation for
60 more details about this message type.
59 more details about this message type.
61
60
62 The following MIME types are currently implemented:
61 The following MIME types are currently implemented:
63
62
64 * text/plain
63 * text/plain
65 * text/html
64 * text/html
66 * text/markdown
65 * text/markdown
67 * text/latex
66 * text/latex
68 * application/json
67 * application/json
69 * application/javascript
68 * application/javascript
70 * image/png
69 * image/png
71 * image/jpeg
70 * image/jpeg
72 * image/svg+xml
71 * image/svg+xml
73
72
74 Parameters
73 Parameters
75 ----------
74 ----------
76 data : dict
75 data : dict
77 A dictionary having keys that are valid MIME types (like
76 A dictionary having keys that are valid MIME types (like
78 'text/plain' or 'image/svg+xml') and values that are the data for
77 'text/plain' or 'image/svg+xml') and values that are the data for
79 that MIME type. The data itself must be a JSON'able data
78 that MIME type. The data itself must be a JSON'able data
80 structure. Minimally all data should have the 'text/plain' data,
79 structure. Minimally all data should have the 'text/plain' data,
81 which can be displayed by all frontends. If more than the plain
80 which can be displayed by all frontends. If more than the plain
82 text is given, it is up to the frontend to decide which
81 text is given, it is up to the frontend to decide which
83 representation to use.
82 representation to use.
84 metadata : dict
83 metadata : dict
85 A dictionary for metadata related to the data. This can contain
84 A dictionary for metadata related to the data. This can contain
86 arbitrary key, value pairs that frontends can use to interpret
85 arbitrary key, value pairs that frontends can use to interpret
87 the data. Metadata specific to each mime-type can be specified
86 the data. Metadata specific to each mime-type can be specified
88 in the metadata dict with the same mime-type keys as
87 in the metadata dict with the same mime-type keys as
89 the data itself.
88 the data itself.
90 source : str, deprecated
89 source : str, deprecated
91 Unused.
90 Unused.
92 """
91 """
93
92
94 # The default is to simply write the plain text data using sys.stdout.
93 # The default is to simply write the plain text data using sys.stdout.
95 if 'text/plain' in data:
94 if 'text/plain' in data:
96 print(data['text/plain'])
95 print(data['text/plain'])
97
96
98 def clear_output(self, wait=False):
97 def clear_output(self, wait=False):
99 """Clear the output of the cell receiving output."""
98 """Clear the output of the cell receiving output."""
100 print('\033[2K\r', end='')
99 print('\033[2K\r', end='')
101 sys.stdout.flush()
100 sys.stdout.flush()
102 print('\033[2K\r', end='')
101 print('\033[2K\r', end='')
103 sys.stderr.flush()
102 sys.stderr.flush()
104
103
105
104
106 class CapturingDisplayPublisher(DisplayPublisher):
105 class CapturingDisplayPublisher(DisplayPublisher):
107 """A DisplayPublisher that stores"""
106 """A DisplayPublisher that stores"""
108 outputs = List()
107 outputs = List()
109
108
110 def publish(self, data, metadata=None, source=None):
109 def publish(self, data, metadata=None, source=None):
111 self.outputs.append((data, metadata))
110 self.outputs.append((data, metadata))
112
111
113 def clear_output(self, wait=False):
112 def clear_output(self, wait=False):
114 super(CapturingDisplayPublisher, self).clear_output(wait)
113 super(CapturingDisplayPublisher, self).clear_output(wait)
115
114
116 # empty the list, *do not* reassign a new list
115 # empty the list, *do not* reassign a new list
117 del self.outputs[:]
116 del self.outputs[:]
@@ -1,131 +1,130 b''
1 """Infrastructure for registering and firing callbacks on application events.
1 """Infrastructure for registering and firing callbacks on application events.
2
2
3 Unlike :mod:`IPython.core.hooks`, which lets end users set single functions to
3 Unlike :mod:`IPython.core.hooks`, which lets end users set single functions to
4 be called at specific times, or a collection of alternative methods to try,
4 be called at specific times, or a collection of alternative methods to try,
5 callbacks are designed to be used by extension authors. A number of callbacks
5 callbacks are designed to be used by extension authors. A number of callbacks
6 can be registered for the same event without needing to be aware of one another.
6 can be registered for the same event without needing to be aware of one another.
7
7
8 The functions defined in this module are no-ops indicating the names of available
8 The functions defined in this module are no-ops indicating the names of available
9 events and the arguments which will be passed to them.
9 events and the arguments which will be passed to them.
10
10
11 .. note::
11 .. note::
12
12
13 This API is experimental in IPython 2.0, and may be revised in future versions.
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 class EventManager(object):
16 class EventManager(object):
18 """Manage a collection of events and a sequence of callbacks for each.
17 """Manage a collection of events and a sequence of callbacks for each.
19
18
20 This is attached to :class:`~IPython.core.interactiveshell.InteractiveShell`
19 This is attached to :class:`~IPython.core.interactiveshell.InteractiveShell`
21 instances as an ``events`` attribute.
20 instances as an ``events`` attribute.
22
21
23 .. note::
22 .. note::
24
23
25 This API is experimental in IPython 2.0, and may be revised in future versions.
24 This API is experimental in IPython 2.0, and may be revised in future versions.
26 """
25 """
27 def __init__(self, shell, available_events):
26 def __init__(self, shell, available_events):
28 """Initialise the :class:`CallbackManager`.
27 """Initialise the :class:`CallbackManager`.
29
28
30 Parameters
29 Parameters
31 ----------
30 ----------
32 shell
31 shell
33 The :class:`~IPython.core.interactiveshell.InteractiveShell` instance
32 The :class:`~IPython.core.interactiveshell.InteractiveShell` instance
34 available_callbacks
33 available_callbacks
35 An iterable of names for callback events.
34 An iterable of names for callback events.
36 """
35 """
37 self.shell = shell
36 self.shell = shell
38 self.callbacks = {n:[] for n in available_events}
37 self.callbacks = {n:[] for n in available_events}
39
38
40 def register(self, event, function):
39 def register(self, event, function):
41 """Register a new event callback
40 """Register a new event callback
42
41
43 Parameters
42 Parameters
44 ----------
43 ----------
45 event : str
44 event : str
46 The event for which to register this callback.
45 The event for which to register this callback.
47 function : callable
46 function : callable
48 A function to be called on the given event. It should take the same
47 A function to be called on the given event. It should take the same
49 parameters as the appropriate callback prototype.
48 parameters as the appropriate callback prototype.
50
49
51 Raises
50 Raises
52 ------
51 ------
53 TypeError
52 TypeError
54 If ``function`` is not callable.
53 If ``function`` is not callable.
55 KeyError
54 KeyError
56 If ``event`` is not one of the known events.
55 If ``event`` is not one of the known events.
57 """
56 """
58 if not callable(function):
57 if not callable(function):
59 raise TypeError('Need a callable, got %r' % function)
58 raise TypeError('Need a callable, got %r' % function)
60 self.callbacks[event].append(function)
59 self.callbacks[event].append(function)
61
60
62 def unregister(self, event, function):
61 def unregister(self, event, function):
63 """Remove a callback from the given event."""
62 """Remove a callback from the given event."""
64 self.callbacks[event].remove(function)
63 self.callbacks[event].remove(function)
65
64
66 def trigger(self, event, *args, **kwargs):
65 def trigger(self, event, *args, **kwargs):
67 """Call callbacks for ``event``.
66 """Call callbacks for ``event``.
68
67
69 Any additional arguments are passed to all callbacks registered for this
68 Any additional arguments are passed to all callbacks registered for this
70 event. Exceptions raised by callbacks are caught, and a message printed.
69 event. Exceptions raised by callbacks are caught, and a message printed.
71 """
70 """
72 for func in self.callbacks[event][:]:
71 for func in self.callbacks[event][:]:
73 try:
72 try:
74 func(*args, **kwargs)
73 func(*args, **kwargs)
75 except Exception:
74 except Exception:
76 print("Error in callback {} (for {}):".format(func, event))
75 print("Error in callback {} (for {}):".format(func, event))
77 self.shell.showtraceback()
76 self.shell.showtraceback()
78
77
79 # event_name -> prototype mapping
78 # event_name -> prototype mapping
80 available_events = {}
79 available_events = {}
81
80
82 def _define_event(callback_proto):
81 def _define_event(callback_proto):
83 available_events[callback_proto.__name__] = callback_proto
82 available_events[callback_proto.__name__] = callback_proto
84 return callback_proto
83 return callback_proto
85
84
86 # ------------------------------------------------------------------------------
85 # ------------------------------------------------------------------------------
87 # Callback prototypes
86 # Callback prototypes
88 #
87 #
89 # No-op functions which describe the names of available events and the
88 # No-op functions which describe the names of available events and the
90 # signatures of callbacks for those events.
89 # signatures of callbacks for those events.
91 # ------------------------------------------------------------------------------
90 # ------------------------------------------------------------------------------
92
91
93 @_define_event
92 @_define_event
94 def pre_execute():
93 def pre_execute():
95 """Fires before code is executed in response to user/frontend action.
94 """Fires before code is executed in response to user/frontend action.
96
95
97 This includes comm and widget messages and silent execution, as well as user
96 This includes comm and widget messages and silent execution, as well as user
98 code cells."""
97 code cells."""
99 pass
98 pass
100
99
101 @_define_event
100 @_define_event
102 def pre_run_cell():
101 def pre_run_cell():
103 """Fires before user-entered code runs."""
102 """Fires before user-entered code runs."""
104 pass
103 pass
105
104
106 @_define_event
105 @_define_event
107 def post_execute():
106 def post_execute():
108 """Fires after code is executed in response to user/frontend action.
107 """Fires after code is executed in response to user/frontend action.
109
108
110 This includes comm and widget messages and silent execution, as well as user
109 This includes comm and widget messages and silent execution, as well as user
111 code cells."""
110 code cells."""
112 pass
111 pass
113
112
114 @_define_event
113 @_define_event
115 def post_run_cell():
114 def post_run_cell():
116 """Fires after user-entered code runs."""
115 """Fires after user-entered code runs."""
117 pass
116 pass
118
117
119 @_define_event
118 @_define_event
120 def shell_initialized(ip):
119 def shell_initialized(ip):
121 """Fires after initialisation of :class:`~IPython.core.interactiveshell.InteractiveShell`.
120 """Fires after initialisation of :class:`~IPython.core.interactiveshell.InteractiveShell`.
122
121
123 This is before extensions and startup scripts are loaded, so it can only be
122 This is before extensions and startup scripts are loaded, so it can only be
124 set by subclassing.
123 set by subclassing.
125
124
126 Parameters
125 Parameters
127 ----------
126 ----------
128 ip : :class:`~IPython.core.interactiveshell.InteractiveShell`
127 ip : :class:`~IPython.core.interactiveshell.InteractiveShell`
129 The newly initialised shell.
128 The newly initialised shell.
130 """
129 """
131 pass
130 pass
@@ -1,911 +1,910 b''
1 """ History related magics and functionality """
1 """ History related magics and functionality """
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 from __future__ import print_function
7
6
8 import atexit
7 import atexit
9 import datetime
8 import datetime
10 import os
9 import os
11 import re
10 import re
12 try:
11 try:
13 import sqlite3
12 import sqlite3
14 except ImportError:
13 except ImportError:
15 try:
14 try:
16 from pysqlite2 import dbapi2 as sqlite3
15 from pysqlite2 import dbapi2 as sqlite3
17 except ImportError:
16 except ImportError:
18 sqlite3 = None
17 sqlite3 = None
19 import threading
18 import threading
20
19
21 from traitlets.config.configurable import LoggingConfigurable
20 from traitlets.config.configurable import LoggingConfigurable
22 from decorator import decorator
21 from decorator import decorator
23 from IPython.utils.decorators import undoc
22 from IPython.utils.decorators import undoc
24 from IPython.utils.path import locate_profile
23 from IPython.utils.path import locate_profile
25 from IPython.utils import py3compat
24 from IPython.utils import py3compat
26 from traitlets import (
25 from traitlets import (
27 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
26 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
28 default, observe,
27 default, observe,
29 )
28 )
30 from warnings import warn
29 from warnings import warn
31
30
32 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
33 # Classes and functions
32 # Classes and functions
34 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
35
34
36 @undoc
35 @undoc
37 class DummyDB(object):
36 class DummyDB(object):
38 """Dummy DB that will act as a black hole for history.
37 """Dummy DB that will act as a black hole for history.
39
38
40 Only used in the absence of sqlite"""
39 Only used in the absence of sqlite"""
41 def execute(*args, **kwargs):
40 def execute(*args, **kwargs):
42 return []
41 return []
43
42
44 def commit(self, *args, **kwargs):
43 def commit(self, *args, **kwargs):
45 pass
44 pass
46
45
47 def __enter__(self, *args, **kwargs):
46 def __enter__(self, *args, **kwargs):
48 pass
47 pass
49
48
50 def __exit__(self, *args, **kwargs):
49 def __exit__(self, *args, **kwargs):
51 pass
50 pass
52
51
53
52
54 @decorator
53 @decorator
55 def needs_sqlite(f, self, *a, **kw):
54 def needs_sqlite(f, self, *a, **kw):
56 """Decorator: return an empty list in the absence of sqlite."""
55 """Decorator: return an empty list in the absence of sqlite."""
57 if sqlite3 is None or not self.enabled:
56 if sqlite3 is None or not self.enabled:
58 return []
57 return []
59 else:
58 else:
60 return f(self, *a, **kw)
59 return f(self, *a, **kw)
61
60
62
61
63 if sqlite3 is not None:
62 if sqlite3 is not None:
64 DatabaseError = sqlite3.DatabaseError
63 DatabaseError = sqlite3.DatabaseError
65 OperationalError = sqlite3.OperationalError
64 OperationalError = sqlite3.OperationalError
66 else:
65 else:
67 @undoc
66 @undoc
68 class DatabaseError(Exception):
67 class DatabaseError(Exception):
69 "Dummy exception when sqlite could not be imported. Should never occur."
68 "Dummy exception when sqlite could not be imported. Should never occur."
70
69
71 @undoc
70 @undoc
72 class OperationalError(Exception):
71 class OperationalError(Exception):
73 "Dummy exception when sqlite could not be imported. Should never occur."
72 "Dummy exception when sqlite could not be imported. Should never occur."
74
73
75 # use 16kB as threshold for whether a corrupt history db should be saved
74 # use 16kB as threshold for whether a corrupt history db should be saved
76 # that should be at least 100 entries or so
75 # that should be at least 100 entries or so
77 _SAVE_DB_SIZE = 16384
76 _SAVE_DB_SIZE = 16384
78
77
79 @decorator
78 @decorator
80 def catch_corrupt_db(f, self, *a, **kw):
79 def catch_corrupt_db(f, self, *a, **kw):
81 """A decorator which wraps HistoryAccessor method calls to catch errors from
80 """A decorator which wraps HistoryAccessor method calls to catch errors from
82 a corrupt SQLite database, move the old database out of the way, and create
81 a corrupt SQLite database, move the old database out of the way, and create
83 a new one.
82 a new one.
84
83
85 We avoid clobbering larger databases because this may be triggered due to filesystem issues,
84 We avoid clobbering larger databases because this may be triggered due to filesystem issues,
86 not just a corrupt file.
85 not just a corrupt file.
87 """
86 """
88 try:
87 try:
89 return f(self, *a, **kw)
88 return f(self, *a, **kw)
90 except (DatabaseError, OperationalError) as e:
89 except (DatabaseError, OperationalError) as e:
91 self._corrupt_db_counter += 1
90 self._corrupt_db_counter += 1
92 self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
91 self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
93 if self.hist_file != ':memory:':
92 if self.hist_file != ':memory:':
94 if self._corrupt_db_counter > self._corrupt_db_limit:
93 if self._corrupt_db_counter > self._corrupt_db_limit:
95 self.hist_file = ':memory:'
94 self.hist_file = ':memory:'
96 self.log.error("Failed to load history too many times, history will not be saved.")
95 self.log.error("Failed to load history too many times, history will not be saved.")
97 elif os.path.isfile(self.hist_file):
96 elif os.path.isfile(self.hist_file):
98 # move the file out of the way
97 # move the file out of the way
99 base, ext = os.path.splitext(self.hist_file)
98 base, ext = os.path.splitext(self.hist_file)
100 size = os.stat(self.hist_file).st_size
99 size = os.stat(self.hist_file).st_size
101 if size >= _SAVE_DB_SIZE:
100 if size >= _SAVE_DB_SIZE:
102 # if there's significant content, avoid clobbering
101 # if there's significant content, avoid clobbering
103 now = datetime.datetime.now().isoformat().replace(':', '.')
102 now = datetime.datetime.now().isoformat().replace(':', '.')
104 newpath = base + '-corrupt-' + now + ext
103 newpath = base + '-corrupt-' + now + ext
105 # don't clobber previous corrupt backups
104 # don't clobber previous corrupt backups
106 for i in range(100):
105 for i in range(100):
107 if not os.path.isfile(newpath):
106 if not os.path.isfile(newpath):
108 break
107 break
109 else:
108 else:
110 newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
109 newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
111 else:
110 else:
112 # not much content, possibly empty; don't worry about clobbering
111 # not much content, possibly empty; don't worry about clobbering
113 # maybe we should just delete it?
112 # maybe we should just delete it?
114 newpath = base + '-corrupt' + ext
113 newpath = base + '-corrupt' + ext
115 os.rename(self.hist_file, newpath)
114 os.rename(self.hist_file, newpath)
116 self.log.error("History file was moved to %s and a new file created.", newpath)
115 self.log.error("History file was moved to %s and a new file created.", newpath)
117 self.init_db()
116 self.init_db()
118 return []
117 return []
119 else:
118 else:
120 # Failed with :memory:, something serious is wrong
119 # Failed with :memory:, something serious is wrong
121 raise
120 raise
122
121
123 class HistoryAccessorBase(LoggingConfigurable):
122 class HistoryAccessorBase(LoggingConfigurable):
124 """An abstract class for History Accessors """
123 """An abstract class for History Accessors """
125
124
126 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
125 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
127 raise NotImplementedError
126 raise NotImplementedError
128
127
129 def search(self, pattern="*", raw=True, search_raw=True,
128 def search(self, pattern="*", raw=True, search_raw=True,
130 output=False, n=None, unique=False):
129 output=False, n=None, unique=False):
131 raise NotImplementedError
130 raise NotImplementedError
132
131
133 def get_range(self, session, start=1, stop=None, raw=True,output=False):
132 def get_range(self, session, start=1, stop=None, raw=True,output=False):
134 raise NotImplementedError
133 raise NotImplementedError
135
134
136 def get_range_by_str(self, rangestr, raw=True, output=False):
135 def get_range_by_str(self, rangestr, raw=True, output=False):
137 raise NotImplementedError
136 raise NotImplementedError
138
137
139
138
140 class HistoryAccessor(HistoryAccessorBase):
139 class HistoryAccessor(HistoryAccessorBase):
141 """Access the history database without adding to it.
140 """Access the history database without adding to it.
142
141
143 This is intended for use by standalone history tools. IPython shells use
142 This is intended for use by standalone history tools. IPython shells use
144 HistoryManager, below, which is a subclass of this."""
143 HistoryManager, below, which is a subclass of this."""
145
144
146 # counter for init_db retries, so we don't keep trying over and over
145 # counter for init_db retries, so we don't keep trying over and over
147 _corrupt_db_counter = 0
146 _corrupt_db_counter = 0
148 # after two failures, fallback on :memory:
147 # after two failures, fallback on :memory:
149 _corrupt_db_limit = 2
148 _corrupt_db_limit = 2
150
149
151 # String holding the path to the history file
150 # String holding the path to the history file
152 hist_file = Unicode(
151 hist_file = Unicode(
153 help="""Path to file to use for SQLite history database.
152 help="""Path to file to use for SQLite history database.
154
153
155 By default, IPython will put the history database in the IPython
154 By default, IPython will put the history database in the IPython
156 profile directory. If you would rather share one history among
155 profile directory. If you would rather share one history among
157 profiles, you can set this value in each, so that they are consistent.
156 profiles, you can set this value in each, so that they are consistent.
158
157
159 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
158 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
160 mounts. If you see IPython hanging, try setting this to something on a
159 mounts. If you see IPython hanging, try setting this to something on a
161 local disk, e.g::
160 local disk, e.g::
162
161
163 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
162 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
164
163
165 you can also use the specific value `:memory:` (including the colon
164 you can also use the specific value `:memory:` (including the colon
166 at both end but not the back ticks), to avoid creating an history file.
165 at both end but not the back ticks), to avoid creating an history file.
167
166
168 """).tag(config=True)
167 """).tag(config=True)
169
168
170 enabled = Bool(True,
169 enabled = Bool(True,
171 help="""enable the SQLite history
170 help="""enable the SQLite history
172
171
173 set enabled=False to disable the SQLite history,
172 set enabled=False to disable the SQLite history,
174 in which case there will be no stored history, no SQLite connection,
173 in which case there will be no stored history, no SQLite connection,
175 and no background saving thread. This may be necessary in some
174 and no background saving thread. This may be necessary in some
176 threaded environments where IPython is embedded.
175 threaded environments where IPython is embedded.
177 """
176 """
178 ).tag(config=True)
177 ).tag(config=True)
179
178
180 connection_options = Dict(
179 connection_options = Dict(
181 help="""Options for configuring the SQLite connection
180 help="""Options for configuring the SQLite connection
182
181
183 These options are passed as keyword args to sqlite3.connect
182 These options are passed as keyword args to sqlite3.connect
184 when establishing database conenctions.
183 when establishing database conenctions.
185 """
184 """
186 ).tag(config=True)
185 ).tag(config=True)
187
186
188 # The SQLite database
187 # The SQLite database
189 db = Any()
188 db = Any()
190 @observe('db')
189 @observe('db')
191 def _db_changed(self, change):
190 def _db_changed(self, change):
192 """validate the db, since it can be an Instance of two different types"""
191 """validate the db, since it can be an Instance of two different types"""
193 new = change['new']
192 new = change['new']
194 connection_types = (DummyDB,)
193 connection_types = (DummyDB,)
195 if sqlite3 is not None:
194 if sqlite3 is not None:
196 connection_types = (DummyDB, sqlite3.Connection)
195 connection_types = (DummyDB, sqlite3.Connection)
197 if not isinstance(new, connection_types):
196 if not isinstance(new, connection_types):
198 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
197 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
199 (self.__class__.__name__, new)
198 (self.__class__.__name__, new)
200 raise TraitError(msg)
199 raise TraitError(msg)
201
200
202 def __init__(self, profile='default', hist_file=u'', **traits):
201 def __init__(self, profile='default', hist_file=u'', **traits):
203 """Create a new history accessor.
202 """Create a new history accessor.
204
203
205 Parameters
204 Parameters
206 ----------
205 ----------
207 profile : str
206 profile : str
208 The name of the profile from which to open history.
207 The name of the profile from which to open history.
209 hist_file : str
208 hist_file : str
210 Path to an SQLite history database stored by IPython. If specified,
209 Path to an SQLite history database stored by IPython. If specified,
211 hist_file overrides profile.
210 hist_file overrides profile.
212 config : :class:`~traitlets.config.loader.Config`
211 config : :class:`~traitlets.config.loader.Config`
213 Config object. hist_file can also be set through this.
212 Config object. hist_file can also be set through this.
214 """
213 """
215 # We need a pointer back to the shell for various tasks.
214 # We need a pointer back to the shell for various tasks.
216 super(HistoryAccessor, self).__init__(**traits)
215 super(HistoryAccessor, self).__init__(**traits)
217 # defer setting hist_file from kwarg until after init,
216 # defer setting hist_file from kwarg until after init,
218 # otherwise the default kwarg value would clobber any value
217 # otherwise the default kwarg value would clobber any value
219 # set by config
218 # set by config
220 if hist_file:
219 if hist_file:
221 self.hist_file = hist_file
220 self.hist_file = hist_file
222
221
223 if self.hist_file == u'':
222 if self.hist_file == u'':
224 # No one has set the hist_file, yet.
223 # No one has set the hist_file, yet.
225 self.hist_file = self._get_hist_file_name(profile)
224 self.hist_file = self._get_hist_file_name(profile)
226
225
227 if sqlite3 is None and self.enabled:
226 if sqlite3 is None and self.enabled:
228 warn("IPython History requires SQLite, your history will not be saved")
227 warn("IPython History requires SQLite, your history will not be saved")
229 self.enabled = False
228 self.enabled = False
230
229
231 self.init_db()
230 self.init_db()
232
231
233 def _get_hist_file_name(self, profile='default'):
232 def _get_hist_file_name(self, profile='default'):
234 """Find the history file for the given profile name.
233 """Find the history file for the given profile name.
235
234
236 This is overridden by the HistoryManager subclass, to use the shell's
235 This is overridden by the HistoryManager subclass, to use the shell's
237 active profile.
236 active profile.
238
237
239 Parameters
238 Parameters
240 ----------
239 ----------
241 profile : str
240 profile : str
242 The name of a profile which has a history file.
241 The name of a profile which has a history file.
243 """
242 """
244 return os.path.join(locate_profile(profile), 'history.sqlite')
243 return os.path.join(locate_profile(profile), 'history.sqlite')
245
244
246 @catch_corrupt_db
245 @catch_corrupt_db
247 def init_db(self):
246 def init_db(self):
248 """Connect to the database, and create tables if necessary."""
247 """Connect to the database, and create tables if necessary."""
249 if not self.enabled:
248 if not self.enabled:
250 self.db = DummyDB()
249 self.db = DummyDB()
251 return
250 return
252
251
253 # use detect_types so that timestamps return datetime objects
252 # use detect_types so that timestamps return datetime objects
254 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
253 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
255 kwargs.update(self.connection_options)
254 kwargs.update(self.connection_options)
256 self.db = sqlite3.connect(self.hist_file, **kwargs)
255 self.db = sqlite3.connect(self.hist_file, **kwargs)
257 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
256 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
258 primary key autoincrement, start timestamp,
257 primary key autoincrement, start timestamp,
259 end timestamp, num_cmds integer, remark text)""")
258 end timestamp, num_cmds integer, remark text)""")
260 self.db.execute("""CREATE TABLE IF NOT EXISTS history
259 self.db.execute("""CREATE TABLE IF NOT EXISTS history
261 (session integer, line integer, source text, source_raw text,
260 (session integer, line integer, source text, source_raw text,
262 PRIMARY KEY (session, line))""")
261 PRIMARY KEY (session, line))""")
263 # Output history is optional, but ensure the table's there so it can be
262 # Output history is optional, but ensure the table's there so it can be
264 # enabled later.
263 # enabled later.
265 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
264 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
266 (session integer, line integer, output text,
265 (session integer, line integer, output text,
267 PRIMARY KEY (session, line))""")
266 PRIMARY KEY (session, line))""")
268 self.db.commit()
267 self.db.commit()
269 # success! reset corrupt db count
268 # success! reset corrupt db count
270 self._corrupt_db_counter = 0
269 self._corrupt_db_counter = 0
271
270
272 def writeout_cache(self):
271 def writeout_cache(self):
273 """Overridden by HistoryManager to dump the cache before certain
272 """Overridden by HistoryManager to dump the cache before certain
274 database lookups."""
273 database lookups."""
275 pass
274 pass
276
275
277 ## -------------------------------
276 ## -------------------------------
278 ## Methods for retrieving history:
277 ## Methods for retrieving history:
279 ## -------------------------------
278 ## -------------------------------
280 def _run_sql(self, sql, params, raw=True, output=False):
279 def _run_sql(self, sql, params, raw=True, output=False):
281 """Prepares and runs an SQL query for the history database.
280 """Prepares and runs an SQL query for the history database.
282
281
283 Parameters
282 Parameters
284 ----------
283 ----------
285 sql : str
284 sql : str
286 Any filtering expressions to go after SELECT ... FROM ...
285 Any filtering expressions to go after SELECT ... FROM ...
287 params : tuple
286 params : tuple
288 Parameters passed to the SQL query (to replace "?")
287 Parameters passed to the SQL query (to replace "?")
289 raw, output : bool
288 raw, output : bool
290 See :meth:`get_range`
289 See :meth:`get_range`
291
290
292 Returns
291 Returns
293 -------
292 -------
294 Tuples as :meth:`get_range`
293 Tuples as :meth:`get_range`
295 """
294 """
296 toget = 'source_raw' if raw else 'source'
295 toget = 'source_raw' if raw else 'source'
297 sqlfrom = "history"
296 sqlfrom = "history"
298 if output:
297 if output:
299 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
298 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
300 toget = "history.%s, output_history.output" % toget
299 toget = "history.%s, output_history.output" % toget
301 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
300 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
302 (toget, sqlfrom) + sql, params)
301 (toget, sqlfrom) + sql, params)
303 if output: # Regroup into 3-tuples, and parse JSON
302 if output: # Regroup into 3-tuples, and parse JSON
304 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
303 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
305 return cur
304 return cur
306
305
307 @needs_sqlite
306 @needs_sqlite
308 @catch_corrupt_db
307 @catch_corrupt_db
309 def get_session_info(self, session):
308 def get_session_info(self, session):
310 """Get info about a session.
309 """Get info about a session.
311
310
312 Parameters
311 Parameters
313 ----------
312 ----------
314
313
315 session : int
314 session : int
316 Session number to retrieve.
315 Session number to retrieve.
317
316
318 Returns
317 Returns
319 -------
318 -------
320
319
321 session_id : int
320 session_id : int
322 Session ID number
321 Session ID number
323 start : datetime
322 start : datetime
324 Timestamp for the start of the session.
323 Timestamp for the start of the session.
325 end : datetime
324 end : datetime
326 Timestamp for the end of the session, or None if IPython crashed.
325 Timestamp for the end of the session, or None if IPython crashed.
327 num_cmds : int
326 num_cmds : int
328 Number of commands run, or None if IPython crashed.
327 Number of commands run, or None if IPython crashed.
329 remark : unicode
328 remark : unicode
330 A manually set description.
329 A manually set description.
331 """
330 """
332 query = "SELECT * from sessions where session == ?"
331 query = "SELECT * from sessions where session == ?"
333 return self.db.execute(query, (session,)).fetchone()
332 return self.db.execute(query, (session,)).fetchone()
334
333
335 @catch_corrupt_db
334 @catch_corrupt_db
336 def get_last_session_id(self):
335 def get_last_session_id(self):
337 """Get the last session ID currently in the database.
336 """Get the last session ID currently in the database.
338
337
339 Within IPython, this should be the same as the value stored in
338 Within IPython, this should be the same as the value stored in
340 :attr:`HistoryManager.session_number`.
339 :attr:`HistoryManager.session_number`.
341 """
340 """
342 for record in self.get_tail(n=1, include_latest=True):
341 for record in self.get_tail(n=1, include_latest=True):
343 return record[0]
342 return record[0]
344
343
345 @catch_corrupt_db
344 @catch_corrupt_db
346 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
345 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
347 """Get the last n lines from the history database.
346 """Get the last n lines from the history database.
348
347
349 Parameters
348 Parameters
350 ----------
349 ----------
351 n : int
350 n : int
352 The number of lines to get
351 The number of lines to get
353 raw, output : bool
352 raw, output : bool
354 See :meth:`get_range`
353 See :meth:`get_range`
355 include_latest : bool
354 include_latest : bool
356 If False (default), n+1 lines are fetched, and the latest one
355 If False (default), n+1 lines are fetched, and the latest one
357 is discarded. This is intended to be used where the function
356 is discarded. This is intended to be used where the function
358 is called by a user command, which it should not return.
357 is called by a user command, which it should not return.
359
358
360 Returns
359 Returns
361 -------
360 -------
362 Tuples as :meth:`get_range`
361 Tuples as :meth:`get_range`
363 """
362 """
364 self.writeout_cache()
363 self.writeout_cache()
365 if not include_latest:
364 if not include_latest:
366 n += 1
365 n += 1
367 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
366 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
368 (n,), raw=raw, output=output)
367 (n,), raw=raw, output=output)
369 if not include_latest:
368 if not include_latest:
370 return reversed(list(cur)[1:])
369 return reversed(list(cur)[1:])
371 return reversed(list(cur))
370 return reversed(list(cur))
372
371
373 @catch_corrupt_db
372 @catch_corrupt_db
374 def search(self, pattern="*", raw=True, search_raw=True,
373 def search(self, pattern="*", raw=True, search_raw=True,
375 output=False, n=None, unique=False):
374 output=False, n=None, unique=False):
376 """Search the database using unix glob-style matching (wildcards
375 """Search the database using unix glob-style matching (wildcards
377 * and ?).
376 * and ?).
378
377
379 Parameters
378 Parameters
380 ----------
379 ----------
381 pattern : str
380 pattern : str
382 The wildcarded pattern to match when searching
381 The wildcarded pattern to match when searching
383 search_raw : bool
382 search_raw : bool
384 If True, search the raw input, otherwise, the parsed input
383 If True, search the raw input, otherwise, the parsed input
385 raw, output : bool
384 raw, output : bool
386 See :meth:`get_range`
385 See :meth:`get_range`
387 n : None or int
386 n : None or int
388 If an integer is given, it defines the limit of
387 If an integer is given, it defines the limit of
389 returned entries.
388 returned entries.
390 unique : bool
389 unique : bool
391 When it is true, return only unique entries.
390 When it is true, return only unique entries.
392
391
393 Returns
392 Returns
394 -------
393 -------
395 Tuples as :meth:`get_range`
394 Tuples as :meth:`get_range`
396 """
395 """
397 tosearch = "source_raw" if search_raw else "source"
396 tosearch = "source_raw" if search_raw else "source"
398 if output:
397 if output:
399 tosearch = "history." + tosearch
398 tosearch = "history." + tosearch
400 self.writeout_cache()
399 self.writeout_cache()
401 sqlform = "WHERE %s GLOB ?" % tosearch
400 sqlform = "WHERE %s GLOB ?" % tosearch
402 params = (pattern,)
401 params = (pattern,)
403 if unique:
402 if unique:
404 sqlform += ' GROUP BY {0}'.format(tosearch)
403 sqlform += ' GROUP BY {0}'.format(tosearch)
405 if n is not None:
404 if n is not None:
406 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
405 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
407 params += (n,)
406 params += (n,)
408 elif unique:
407 elif unique:
409 sqlform += " ORDER BY session, line"
408 sqlform += " ORDER BY session, line"
410 cur = self._run_sql(sqlform, params, raw=raw, output=output)
409 cur = self._run_sql(sqlform, params, raw=raw, output=output)
411 if n is not None:
410 if n is not None:
412 return reversed(list(cur))
411 return reversed(list(cur))
413 return cur
412 return cur
414
413
415 @catch_corrupt_db
414 @catch_corrupt_db
416 def get_range(self, session, start=1, stop=None, raw=True,output=False):
415 def get_range(self, session, start=1, stop=None, raw=True,output=False):
417 """Retrieve input by session.
416 """Retrieve input by session.
418
417
419 Parameters
418 Parameters
420 ----------
419 ----------
421 session : int
420 session : int
422 Session number to retrieve.
421 Session number to retrieve.
423 start : int
422 start : int
424 First line to retrieve.
423 First line to retrieve.
425 stop : int
424 stop : int
426 End of line range (excluded from output itself). If None, retrieve
425 End of line range (excluded from output itself). If None, retrieve
427 to the end of the session.
426 to the end of the session.
428 raw : bool
427 raw : bool
429 If True, return untranslated input
428 If True, return untranslated input
430 output : bool
429 output : bool
431 If True, attempt to include output. This will be 'real' Python
430 If True, attempt to include output. This will be 'real' Python
432 objects for the current session, or text reprs from previous
431 objects for the current session, or text reprs from previous
433 sessions if db_log_output was enabled at the time. Where no output
432 sessions if db_log_output was enabled at the time. Where no output
434 is found, None is used.
433 is found, None is used.
435
434
436 Returns
435 Returns
437 -------
436 -------
438 entries
437 entries
439 An iterator over the desired lines. Each line is a 3-tuple, either
438 An iterator over the desired lines. Each line is a 3-tuple, either
440 (session, line, input) if output is False, or
439 (session, line, input) if output is False, or
441 (session, line, (input, output)) if output is True.
440 (session, line, (input, output)) if output is True.
442 """
441 """
443 if stop:
442 if stop:
444 lineclause = "line >= ? AND line < ?"
443 lineclause = "line >= ? AND line < ?"
445 params = (session, start, stop)
444 params = (session, start, stop)
446 else:
445 else:
447 lineclause = "line>=?"
446 lineclause = "line>=?"
448 params = (session, start)
447 params = (session, start)
449
448
450 return self._run_sql("WHERE session==? AND %s" % lineclause,
449 return self._run_sql("WHERE session==? AND %s" % lineclause,
451 params, raw=raw, output=output)
450 params, raw=raw, output=output)
452
451
453 def get_range_by_str(self, rangestr, raw=True, output=False):
452 def get_range_by_str(self, rangestr, raw=True, output=False):
454 """Get lines of history from a string of ranges, as used by magic
453 """Get lines of history from a string of ranges, as used by magic
455 commands %hist, %save, %macro, etc.
454 commands %hist, %save, %macro, etc.
456
455
457 Parameters
456 Parameters
458 ----------
457 ----------
459 rangestr : str
458 rangestr : str
460 A string specifying ranges, e.g. "5 ~2/1-4". See
459 A string specifying ranges, e.g. "5 ~2/1-4". See
461 :func:`magic_history` for full details.
460 :func:`magic_history` for full details.
462 raw, output : bool
461 raw, output : bool
463 As :meth:`get_range`
462 As :meth:`get_range`
464
463
465 Returns
464 Returns
466 -------
465 -------
467 Tuples as :meth:`get_range`
466 Tuples as :meth:`get_range`
468 """
467 """
469 for sess, s, e in extract_hist_ranges(rangestr):
468 for sess, s, e in extract_hist_ranges(rangestr):
470 for line in self.get_range(sess, s, e, raw=raw, output=output):
469 for line in self.get_range(sess, s, e, raw=raw, output=output):
471 yield line
470 yield line
472
471
473
472
474 class HistoryManager(HistoryAccessor):
473 class HistoryManager(HistoryAccessor):
475 """A class to organize all history-related functionality in one place.
474 """A class to organize all history-related functionality in one place.
476 """
475 """
477 # Public interface
476 # Public interface
478
477
479 # An instance of the IPython shell we are attached to
478 # An instance of the IPython shell we are attached to
480 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
479 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
481 allow_none=True)
480 allow_none=True)
482 # Lists to hold processed and raw history. These start with a blank entry
481 # Lists to hold processed and raw history. These start with a blank entry
483 # so that we can index them starting from 1
482 # so that we can index them starting from 1
484 input_hist_parsed = List([""])
483 input_hist_parsed = List([""])
485 input_hist_raw = List([""])
484 input_hist_raw = List([""])
486 # A list of directories visited during session
485 # A list of directories visited during session
487 dir_hist = List()
486 dir_hist = List()
488 @default('dir_hist')
487 @default('dir_hist')
489 def _dir_hist_default(self):
488 def _dir_hist_default(self):
490 try:
489 try:
491 return [py3compat.getcwd()]
490 return [py3compat.getcwd()]
492 except OSError:
491 except OSError:
493 return []
492 return []
494
493
495 # A dict of output history, keyed with ints from the shell's
494 # A dict of output history, keyed with ints from the shell's
496 # execution count.
495 # execution count.
497 output_hist = Dict()
496 output_hist = Dict()
498 # The text/plain repr of outputs.
497 # The text/plain repr of outputs.
499 output_hist_reprs = Dict()
498 output_hist_reprs = Dict()
500
499
501 # The number of the current session in the history database
500 # The number of the current session in the history database
502 session_number = Integer()
501 session_number = Integer()
503
502
504 db_log_output = Bool(False,
503 db_log_output = Bool(False,
505 help="Should the history database include output? (default: no)"
504 help="Should the history database include output? (default: no)"
506 ).tag(config=True)
505 ).tag(config=True)
507 db_cache_size = Integer(0,
506 db_cache_size = Integer(0,
508 help="Write to database every x commands (higher values save disk access & power).\n"
507 help="Write to database every x commands (higher values save disk access & power).\n"
509 "Values of 1 or less effectively disable caching."
508 "Values of 1 or less effectively disable caching."
510 ).tag(config=True)
509 ).tag(config=True)
511 # The input and output caches
510 # The input and output caches
512 db_input_cache = List()
511 db_input_cache = List()
513 db_output_cache = List()
512 db_output_cache = List()
514
513
515 # History saving in separate thread
514 # History saving in separate thread
516 save_thread = Instance('IPython.core.history.HistorySavingThread',
515 save_thread = Instance('IPython.core.history.HistorySavingThread',
517 allow_none=True)
516 allow_none=True)
518 try: # Event is a function returning an instance of _Event...
517 try: # Event is a function returning an instance of _Event...
519 save_flag = Instance(threading._Event, allow_none=True)
518 save_flag = Instance(threading._Event, allow_none=True)
520 except AttributeError: # ...until Python 3.3, when it's a class.
519 except AttributeError: # ...until Python 3.3, when it's a class.
521 save_flag = Instance(threading.Event, allow_none=True)
520 save_flag = Instance(threading.Event, allow_none=True)
522
521
523 # Private interface
522 # Private interface
524 # Variables used to store the three last inputs from the user. On each new
523 # Variables used to store the three last inputs from the user. On each new
525 # history update, we populate the user's namespace with these, shifted as
524 # history update, we populate the user's namespace with these, shifted as
526 # necessary.
525 # necessary.
527 _i00 = Unicode(u'')
526 _i00 = Unicode(u'')
528 _i = Unicode(u'')
527 _i = Unicode(u'')
529 _ii = Unicode(u'')
528 _ii = Unicode(u'')
530 _iii = Unicode(u'')
529 _iii = Unicode(u'')
531
530
532 # A regex matching all forms of the exit command, so that we don't store
531 # A regex matching all forms of the exit command, so that we don't store
533 # them in the history (it's annoying to rewind the first entry and land on
532 # them in the history (it's annoying to rewind the first entry and land on
534 # an exit call).
533 # an exit call).
535 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
534 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
536
535
537 def __init__(self, shell=None, config=None, **traits):
536 def __init__(self, shell=None, config=None, **traits):
538 """Create a new history manager associated with a shell instance.
537 """Create a new history manager associated with a shell instance.
539 """
538 """
540 # We need a pointer back to the shell for various tasks.
539 # We need a pointer back to the shell for various tasks.
541 super(HistoryManager, self).__init__(shell=shell, config=config,
540 super(HistoryManager, self).__init__(shell=shell, config=config,
542 **traits)
541 **traits)
543 self.save_flag = threading.Event()
542 self.save_flag = threading.Event()
544 self.db_input_cache_lock = threading.Lock()
543 self.db_input_cache_lock = threading.Lock()
545 self.db_output_cache_lock = threading.Lock()
544 self.db_output_cache_lock = threading.Lock()
546
545
547 try:
546 try:
548 self.new_session()
547 self.new_session()
549 except OperationalError:
548 except OperationalError:
550 self.log.error("Failed to create history session in %s. History will not be saved.",
549 self.log.error("Failed to create history session in %s. History will not be saved.",
551 self.hist_file, exc_info=True)
550 self.hist_file, exc_info=True)
552 self.hist_file = ':memory:'
551 self.hist_file = ':memory:'
553
552
554 if self.enabled and self.hist_file != ':memory:':
553 if self.enabled and self.hist_file != ':memory:':
555 self.save_thread = HistorySavingThread(self)
554 self.save_thread = HistorySavingThread(self)
556 self.save_thread.start()
555 self.save_thread.start()
557
556
558 def _get_hist_file_name(self, profile=None):
557 def _get_hist_file_name(self, profile=None):
559 """Get default history file name based on the Shell's profile.
558 """Get default history file name based on the Shell's profile.
560
559
561 The profile parameter is ignored, but must exist for compatibility with
560 The profile parameter is ignored, but must exist for compatibility with
562 the parent class."""
561 the parent class."""
563 profile_dir = self.shell.profile_dir.location
562 profile_dir = self.shell.profile_dir.location
564 return os.path.join(profile_dir, 'history.sqlite')
563 return os.path.join(profile_dir, 'history.sqlite')
565
564
566 @needs_sqlite
565 @needs_sqlite
567 def new_session(self, conn=None):
566 def new_session(self, conn=None):
568 """Get a new session number."""
567 """Get a new session number."""
569 if conn is None:
568 if conn is None:
570 conn = self.db
569 conn = self.db
571
570
572 with conn:
571 with conn:
573 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
572 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
574 NULL, "") """, (datetime.datetime.now(),))
573 NULL, "") """, (datetime.datetime.now(),))
575 self.session_number = cur.lastrowid
574 self.session_number = cur.lastrowid
576
575
577 def end_session(self):
576 def end_session(self):
578 """Close the database session, filling in the end time and line count."""
577 """Close the database session, filling in the end time and line count."""
579 self.writeout_cache()
578 self.writeout_cache()
580 with self.db:
579 with self.db:
581 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
580 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
582 session==?""", (datetime.datetime.now(),
581 session==?""", (datetime.datetime.now(),
583 len(self.input_hist_parsed)-1, self.session_number))
582 len(self.input_hist_parsed)-1, self.session_number))
584 self.session_number = 0
583 self.session_number = 0
585
584
586 def name_session(self, name):
585 def name_session(self, name):
587 """Give the current session a name in the history database."""
586 """Give the current session a name in the history database."""
588 with self.db:
587 with self.db:
589 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
588 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
590 (name, self.session_number))
589 (name, self.session_number))
591
590
592 def reset(self, new_session=True):
591 def reset(self, new_session=True):
593 """Clear the session history, releasing all object references, and
592 """Clear the session history, releasing all object references, and
594 optionally open a new session."""
593 optionally open a new session."""
595 self.output_hist.clear()
594 self.output_hist.clear()
596 # The directory history can't be completely empty
595 # The directory history can't be completely empty
597 self.dir_hist[:] = [py3compat.getcwd()]
596 self.dir_hist[:] = [py3compat.getcwd()]
598
597
599 if new_session:
598 if new_session:
600 if self.session_number:
599 if self.session_number:
601 self.end_session()
600 self.end_session()
602 self.input_hist_parsed[:] = [""]
601 self.input_hist_parsed[:] = [""]
603 self.input_hist_raw[:] = [""]
602 self.input_hist_raw[:] = [""]
604 self.new_session()
603 self.new_session()
605
604
606 # ------------------------------
605 # ------------------------------
607 # Methods for retrieving history
606 # Methods for retrieving history
608 # ------------------------------
607 # ------------------------------
609 def get_session_info(self, session=0):
608 def get_session_info(self, session=0):
610 """Get info about a session.
609 """Get info about a session.
611
610
612 Parameters
611 Parameters
613 ----------
612 ----------
614
613
615 session : int
614 session : int
616 Session number to retrieve. The current session is 0, and negative
615 Session number to retrieve. The current session is 0, and negative
617 numbers count back from current session, so -1 is the previous session.
616 numbers count back from current session, so -1 is the previous session.
618
617
619 Returns
618 Returns
620 -------
619 -------
621
620
622 session_id : int
621 session_id : int
623 Session ID number
622 Session ID number
624 start : datetime
623 start : datetime
625 Timestamp for the start of the session.
624 Timestamp for the start of the session.
626 end : datetime
625 end : datetime
627 Timestamp for the end of the session, or None if IPython crashed.
626 Timestamp for the end of the session, or None if IPython crashed.
628 num_cmds : int
627 num_cmds : int
629 Number of commands run, or None if IPython crashed.
628 Number of commands run, or None if IPython crashed.
630 remark : unicode
629 remark : unicode
631 A manually set description.
630 A manually set description.
632 """
631 """
633 if session <= 0:
632 if session <= 0:
634 session += self.session_number
633 session += self.session_number
635
634
636 return super(HistoryManager, self).get_session_info(session=session)
635 return super(HistoryManager, self).get_session_info(session=session)
637
636
638 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
637 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
639 """Get input and output history from the current session. Called by
638 """Get input and output history from the current session. Called by
640 get_range, and takes similar parameters."""
639 get_range, and takes similar parameters."""
641 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
640 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
642
641
643 n = len(input_hist)
642 n = len(input_hist)
644 if start < 0:
643 if start < 0:
645 start += n
644 start += n
646 if not stop or (stop > n):
645 if not stop or (stop > n):
647 stop = n
646 stop = n
648 elif stop < 0:
647 elif stop < 0:
649 stop += n
648 stop += n
650
649
651 for i in range(start, stop):
650 for i in range(start, stop):
652 if output:
651 if output:
653 line = (input_hist[i], self.output_hist_reprs.get(i))
652 line = (input_hist[i], self.output_hist_reprs.get(i))
654 else:
653 else:
655 line = input_hist[i]
654 line = input_hist[i]
656 yield (0, i, line)
655 yield (0, i, line)
657
656
658 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
657 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
659 """Retrieve input by session.
658 """Retrieve input by session.
660
659
661 Parameters
660 Parameters
662 ----------
661 ----------
663 session : int
662 session : int
664 Session number to retrieve. The current session is 0, and negative
663 Session number to retrieve. The current session is 0, and negative
665 numbers count back from current session, so -1 is previous session.
664 numbers count back from current session, so -1 is previous session.
666 start : int
665 start : int
667 First line to retrieve.
666 First line to retrieve.
668 stop : int
667 stop : int
669 End of line range (excluded from output itself). If None, retrieve
668 End of line range (excluded from output itself). If None, retrieve
670 to the end of the session.
669 to the end of the session.
671 raw : bool
670 raw : bool
672 If True, return untranslated input
671 If True, return untranslated input
673 output : bool
672 output : bool
674 If True, attempt to include output. This will be 'real' Python
673 If True, attempt to include output. This will be 'real' Python
675 objects for the current session, or text reprs from previous
674 objects for the current session, or text reprs from previous
676 sessions if db_log_output was enabled at the time. Where no output
675 sessions if db_log_output was enabled at the time. Where no output
677 is found, None is used.
676 is found, None is used.
678
677
679 Returns
678 Returns
680 -------
679 -------
681 entries
680 entries
682 An iterator over the desired lines. Each line is a 3-tuple, either
681 An iterator over the desired lines. Each line is a 3-tuple, either
683 (session, line, input) if output is False, or
682 (session, line, input) if output is False, or
684 (session, line, (input, output)) if output is True.
683 (session, line, (input, output)) if output is True.
685 """
684 """
686 if session <= 0:
685 if session <= 0:
687 session += self.session_number
686 session += self.session_number
688 if session==self.session_number: # Current session
687 if session==self.session_number: # Current session
689 return self._get_range_session(start, stop, raw, output)
688 return self._get_range_session(start, stop, raw, output)
690 return super(HistoryManager, self).get_range(session, start, stop, raw,
689 return super(HistoryManager, self).get_range(session, start, stop, raw,
691 output)
690 output)
692
691
693 ## ----------------------------
692 ## ----------------------------
694 ## Methods for storing history:
693 ## Methods for storing history:
695 ## ----------------------------
694 ## ----------------------------
696 def store_inputs(self, line_num, source, source_raw=None):
695 def store_inputs(self, line_num, source, source_raw=None):
697 """Store source and raw input in history and create input cache
696 """Store source and raw input in history and create input cache
698 variables ``_i*``.
697 variables ``_i*``.
699
698
700 Parameters
699 Parameters
701 ----------
700 ----------
702 line_num : int
701 line_num : int
703 The prompt number of this input.
702 The prompt number of this input.
704
703
705 source : str
704 source : str
706 Python input.
705 Python input.
707
706
708 source_raw : str, optional
707 source_raw : str, optional
709 If given, this is the raw input without any IPython transformations
708 If given, this is the raw input without any IPython transformations
710 applied to it. If not given, ``source`` is used.
709 applied to it. If not given, ``source`` is used.
711 """
710 """
712 if source_raw is None:
711 if source_raw is None:
713 source_raw = source
712 source_raw = source
714 source = source.rstrip('\n')
713 source = source.rstrip('\n')
715 source_raw = source_raw.rstrip('\n')
714 source_raw = source_raw.rstrip('\n')
716
715
717 # do not store exit/quit commands
716 # do not store exit/quit commands
718 if self._exit_re.match(source_raw.strip()):
717 if self._exit_re.match(source_raw.strip()):
719 return
718 return
720
719
721 self.input_hist_parsed.append(source)
720 self.input_hist_parsed.append(source)
722 self.input_hist_raw.append(source_raw)
721 self.input_hist_raw.append(source_raw)
723
722
724 with self.db_input_cache_lock:
723 with self.db_input_cache_lock:
725 self.db_input_cache.append((line_num, source, source_raw))
724 self.db_input_cache.append((line_num, source, source_raw))
726 # Trigger to flush cache and write to DB.
725 # Trigger to flush cache and write to DB.
727 if len(self.db_input_cache) >= self.db_cache_size:
726 if len(self.db_input_cache) >= self.db_cache_size:
728 self.save_flag.set()
727 self.save_flag.set()
729
728
730 # update the auto _i variables
729 # update the auto _i variables
731 self._iii = self._ii
730 self._iii = self._ii
732 self._ii = self._i
731 self._ii = self._i
733 self._i = self._i00
732 self._i = self._i00
734 self._i00 = source_raw
733 self._i00 = source_raw
735
734
736 # hackish access to user namespace to create _i1,_i2... dynamically
735 # hackish access to user namespace to create _i1,_i2... dynamically
737 new_i = '_i%s' % line_num
736 new_i = '_i%s' % line_num
738 to_main = {'_i': self._i,
737 to_main = {'_i': self._i,
739 '_ii': self._ii,
738 '_ii': self._ii,
740 '_iii': self._iii,
739 '_iii': self._iii,
741 new_i : self._i00 }
740 new_i : self._i00 }
742
741
743 if self.shell is not None:
742 if self.shell is not None:
744 self.shell.push(to_main, interactive=False)
743 self.shell.push(to_main, interactive=False)
745
744
746 def store_output(self, line_num):
745 def store_output(self, line_num):
747 """If database output logging is enabled, this saves all the
746 """If database output logging is enabled, this saves all the
748 outputs from the indicated prompt number to the database. It's
747 outputs from the indicated prompt number to the database. It's
749 called by run_cell after code has been executed.
748 called by run_cell after code has been executed.
750
749
751 Parameters
750 Parameters
752 ----------
751 ----------
753 line_num : int
752 line_num : int
754 The line number from which to save outputs
753 The line number from which to save outputs
755 """
754 """
756 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
755 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
757 return
756 return
758 output = self.output_hist_reprs[line_num]
757 output = self.output_hist_reprs[line_num]
759
758
760 with self.db_output_cache_lock:
759 with self.db_output_cache_lock:
761 self.db_output_cache.append((line_num, output))
760 self.db_output_cache.append((line_num, output))
762 if self.db_cache_size <= 1:
761 if self.db_cache_size <= 1:
763 self.save_flag.set()
762 self.save_flag.set()
764
763
765 def _writeout_input_cache(self, conn):
764 def _writeout_input_cache(self, conn):
766 with conn:
765 with conn:
767 for line in self.db_input_cache:
766 for line in self.db_input_cache:
768 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
767 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
769 (self.session_number,)+line)
768 (self.session_number,)+line)
770
769
771 def _writeout_output_cache(self, conn):
770 def _writeout_output_cache(self, conn):
772 with conn:
771 with conn:
773 for line in self.db_output_cache:
772 for line in self.db_output_cache:
774 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
773 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
775 (self.session_number,)+line)
774 (self.session_number,)+line)
776
775
777 @needs_sqlite
776 @needs_sqlite
778 def writeout_cache(self, conn=None):
777 def writeout_cache(self, conn=None):
779 """Write any entries in the cache to the database."""
778 """Write any entries in the cache to the database."""
780 if conn is None:
779 if conn is None:
781 conn = self.db
780 conn = self.db
782
781
783 with self.db_input_cache_lock:
782 with self.db_input_cache_lock:
784 try:
783 try:
785 self._writeout_input_cache(conn)
784 self._writeout_input_cache(conn)
786 except sqlite3.IntegrityError:
785 except sqlite3.IntegrityError:
787 self.new_session(conn)
786 self.new_session(conn)
788 print("ERROR! Session/line number was not unique in",
787 print("ERROR! Session/line number was not unique in",
789 "database. History logging moved to new session",
788 "database. History logging moved to new session",
790 self.session_number)
789 self.session_number)
791 try:
790 try:
792 # Try writing to the new session. If this fails, don't
791 # Try writing to the new session. If this fails, don't
793 # recurse
792 # recurse
794 self._writeout_input_cache(conn)
793 self._writeout_input_cache(conn)
795 except sqlite3.IntegrityError:
794 except sqlite3.IntegrityError:
796 pass
795 pass
797 finally:
796 finally:
798 self.db_input_cache = []
797 self.db_input_cache = []
799
798
800 with self.db_output_cache_lock:
799 with self.db_output_cache_lock:
801 try:
800 try:
802 self._writeout_output_cache(conn)
801 self._writeout_output_cache(conn)
803 except sqlite3.IntegrityError:
802 except sqlite3.IntegrityError:
804 print("!! Session/line number for output was not unique",
803 print("!! Session/line number for output was not unique",
805 "in database. Output will not be stored.")
804 "in database. Output will not be stored.")
806 finally:
805 finally:
807 self.db_output_cache = []
806 self.db_output_cache = []
808
807
809
808
810 class HistorySavingThread(threading.Thread):
809 class HistorySavingThread(threading.Thread):
811 """This thread takes care of writing history to the database, so that
810 """This thread takes care of writing history to the database, so that
812 the UI isn't held up while that happens.
811 the UI isn't held up while that happens.
813
812
814 It waits for the HistoryManager's save_flag to be set, then writes out
813 It waits for the HistoryManager's save_flag to be set, then writes out
815 the history cache. The main thread is responsible for setting the flag when
814 the history cache. The main thread is responsible for setting the flag when
816 the cache size reaches a defined threshold."""
815 the cache size reaches a defined threshold."""
817 daemon = True
816 daemon = True
818 stop_now = False
817 stop_now = False
819 enabled = True
818 enabled = True
820 def __init__(self, history_manager):
819 def __init__(self, history_manager):
821 super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
820 super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
822 self.history_manager = history_manager
821 self.history_manager = history_manager
823 self.enabled = history_manager.enabled
822 self.enabled = history_manager.enabled
824 atexit.register(self.stop)
823 atexit.register(self.stop)
825
824
826 @needs_sqlite
825 @needs_sqlite
827 def run(self):
826 def run(self):
828 # We need a separate db connection per thread:
827 # We need a separate db connection per thread:
829 try:
828 try:
830 self.db = sqlite3.connect(self.history_manager.hist_file,
829 self.db = sqlite3.connect(self.history_manager.hist_file,
831 **self.history_manager.connection_options
830 **self.history_manager.connection_options
832 )
831 )
833 while True:
832 while True:
834 self.history_manager.save_flag.wait()
833 self.history_manager.save_flag.wait()
835 if self.stop_now:
834 if self.stop_now:
836 self.db.close()
835 self.db.close()
837 return
836 return
838 self.history_manager.save_flag.clear()
837 self.history_manager.save_flag.clear()
839 self.history_manager.writeout_cache(self.db)
838 self.history_manager.writeout_cache(self.db)
840 except Exception as e:
839 except Exception as e:
841 print(("The history saving thread hit an unexpected error (%s)."
840 print(("The history saving thread hit an unexpected error (%s)."
842 "History will not be written to the database.") % repr(e))
841 "History will not be written to the database.") % repr(e))
843
842
844 def stop(self):
843 def stop(self):
845 """This can be called from the main thread to safely stop this thread.
844 """This can be called from the main thread to safely stop this thread.
846
845
847 Note that it does not attempt to write out remaining history before
846 Note that it does not attempt to write out remaining history before
848 exiting. That should be done by calling the HistoryManager's
847 exiting. That should be done by calling the HistoryManager's
849 end_session method."""
848 end_session method."""
850 self.stop_now = True
849 self.stop_now = True
851 self.history_manager.save_flag.set()
850 self.history_manager.save_flag.set()
852 self.join()
851 self.join()
853
852
854
853
855 # To match, e.g. ~5/8-~2/3
854 # To match, e.g. ~5/8-~2/3
856 range_re = re.compile(r"""
855 range_re = re.compile(r"""
857 ((?P<startsess>~?\d+)/)?
856 ((?P<startsess>~?\d+)/)?
858 (?P<start>\d+)?
857 (?P<start>\d+)?
859 ((?P<sep>[\-:])
858 ((?P<sep>[\-:])
860 ((?P<endsess>~?\d+)/)?
859 ((?P<endsess>~?\d+)/)?
861 (?P<end>\d+))?
860 (?P<end>\d+))?
862 $""", re.VERBOSE)
861 $""", re.VERBOSE)
863
862
864
863
865 def extract_hist_ranges(ranges_str):
864 def extract_hist_ranges(ranges_str):
866 """Turn a string of history ranges into 3-tuples of (session, start, stop).
865 """Turn a string of history ranges into 3-tuples of (session, start, stop).
867
866
868 Examples
867 Examples
869 --------
868 --------
870 >>> list(extract_hist_ranges("~8/5-~7/4 2"))
869 >>> list(extract_hist_ranges("~8/5-~7/4 2"))
871 [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
870 [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
872 """
871 """
873 for range_str in ranges_str.split():
872 for range_str in ranges_str.split():
874 rmatch = range_re.match(range_str)
873 rmatch = range_re.match(range_str)
875 if not rmatch:
874 if not rmatch:
876 continue
875 continue
877 start = rmatch.group("start")
876 start = rmatch.group("start")
878 if start:
877 if start:
879 start = int(start)
878 start = int(start)
880 end = rmatch.group("end")
879 end = rmatch.group("end")
881 # If no end specified, get (a, a + 1)
880 # If no end specified, get (a, a + 1)
882 end = int(end) if end else start + 1
881 end = int(end) if end else start + 1
883 else: # start not specified
882 else: # start not specified
884 if not rmatch.group('startsess'): # no startsess
883 if not rmatch.group('startsess'): # no startsess
885 continue
884 continue
886 start = 1
885 start = 1
887 end = None # provide the entire session hist
886 end = None # provide the entire session hist
888
887
889 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
888 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
890 end += 1
889 end += 1
891 startsess = rmatch.group("startsess") or "0"
890 startsess = rmatch.group("startsess") or "0"
892 endsess = rmatch.group("endsess") or startsess
891 endsess = rmatch.group("endsess") or startsess
893 startsess = int(startsess.replace("~","-"))
892 startsess = int(startsess.replace("~","-"))
894 endsess = int(endsess.replace("~","-"))
893 endsess = int(endsess.replace("~","-"))
895 assert endsess >= startsess, "start session must be earlier than end session"
894 assert endsess >= startsess, "start session must be earlier than end session"
896
895
897 if endsess == startsess:
896 if endsess == startsess:
898 yield (startsess, start, end)
897 yield (startsess, start, end)
899 continue
898 continue
900 # Multiple sessions in one range:
899 # Multiple sessions in one range:
901 yield (startsess, start, None)
900 yield (startsess, start, None)
902 for sess in range(startsess+1, endsess):
901 for sess in range(startsess+1, endsess):
903 yield (sess, 1, None)
902 yield (sess, 1, None)
904 yield (endsess, 1, end)
903 yield (endsess, 1, end)
905
904
906
905
907 def _format_lineno(session, line):
906 def _format_lineno(session, line):
908 """Helper function to format line numbers properly."""
907 """Helper function to format line numbers properly."""
909 if session == 0:
908 if session == 0:
910 return str(line)
909 return str(line)
911 return "%s#%s" % (session, line)
910 return "%s#%s" % (session, line)
@@ -1,162 +1,161 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 An application for managing IPython history.
3 An application for managing IPython history.
4
4
5 To be invoked as the `ipython history` subcommand.
5 To be invoked as the `ipython history` subcommand.
6 """
6 """
7 from __future__ import print_function
8
7
9 import os
8 import os
10 import sqlite3
9 import sqlite3
11
10
12 from traitlets.config.application import Application
11 from traitlets.config.application import Application
13 from IPython.core.application import BaseIPythonApplication
12 from IPython.core.application import BaseIPythonApplication
14 from traitlets import Bool, Int, Dict
13 from traitlets import Bool, Int, Dict
15 from IPython.utils.io import ask_yes_no
14 from IPython.utils.io import ask_yes_no
16
15
17 trim_hist_help = """Trim the IPython history database to the last 1000 entries.
16 trim_hist_help = """Trim the IPython history database to the last 1000 entries.
18
17
19 This actually copies the last 1000 entries to a new database, and then replaces
18 This actually copies the last 1000 entries to a new database, and then replaces
20 the old file with the new. Use the `--keep=` argument to specify a number
19 the old file with the new. Use the `--keep=` argument to specify a number
21 other than 1000.
20 other than 1000.
22 """
21 """
23
22
24 clear_hist_help = """Clear the IPython history database, deleting all entries.
23 clear_hist_help = """Clear the IPython history database, deleting all entries.
25
24
26 Because this is a destructive operation, IPython will prompt the user if they
25 Because this is a destructive operation, IPython will prompt the user if they
27 really want to do this. Passing a `-f` flag will force clearing without a
26 really want to do this. Passing a `-f` flag will force clearing without a
28 prompt.
27 prompt.
29
28
30 This is an handy alias to `ipython history trim --keep=0`
29 This is an handy alias to `ipython history trim --keep=0`
31 """
30 """
32
31
33
32
34 class HistoryTrim(BaseIPythonApplication):
33 class HistoryTrim(BaseIPythonApplication):
35 description = trim_hist_help
34 description = trim_hist_help
36
35
37 backup = Bool(False,
36 backup = Bool(False,
38 help="Keep the old history file as history.sqlite.<N>"
37 help="Keep the old history file as history.sqlite.<N>"
39 ).tag(config=True)
38 ).tag(config=True)
40
39
41 keep = Int(1000,
40 keep = Int(1000,
42 help="Number of recent lines to keep in the database."
41 help="Number of recent lines to keep in the database."
43 ).tag(config=True)
42 ).tag(config=True)
44
43
45 flags = Dict(dict(
44 flags = Dict(dict(
46 backup = ({'HistoryTrim' : {'backup' : True}},
45 backup = ({'HistoryTrim' : {'backup' : True}},
47 backup.help
46 backup.help
48 )
47 )
49 ))
48 ))
50
49
51 aliases=Dict(dict(
50 aliases=Dict(dict(
52 keep = 'HistoryTrim.keep'
51 keep = 'HistoryTrim.keep'
53 ))
52 ))
54
53
55 def start(self):
54 def start(self):
56 profile_dir = self.profile_dir.location
55 profile_dir = self.profile_dir.location
57 hist_file = os.path.join(profile_dir, 'history.sqlite')
56 hist_file = os.path.join(profile_dir, 'history.sqlite')
58 con = sqlite3.connect(hist_file)
57 con = sqlite3.connect(hist_file)
59
58
60 # Grab the recent history from the current database.
59 # Grab the recent history from the current database.
61 inputs = list(con.execute('SELECT session, line, source, source_raw FROM '
60 inputs = list(con.execute('SELECT session, line, source, source_raw FROM '
62 'history ORDER BY session DESC, line DESC LIMIT ?', (self.keep+1,)))
61 'history ORDER BY session DESC, line DESC LIMIT ?', (self.keep+1,)))
63 if len(inputs) <= self.keep:
62 if len(inputs) <= self.keep:
64 print("There are already at most %d entries in the history database." % self.keep)
63 print("There are already at most %d entries in the history database." % self.keep)
65 print("Not doing anything. Use --keep= argument to keep fewer entries")
64 print("Not doing anything. Use --keep= argument to keep fewer entries")
66 return
65 return
67
66
68 print("Trimming history to the most recent %d entries." % self.keep)
67 print("Trimming history to the most recent %d entries." % self.keep)
69
68
70 inputs.pop() # Remove the extra element we got to check the length.
69 inputs.pop() # Remove the extra element we got to check the length.
71 inputs.reverse()
70 inputs.reverse()
72 if inputs:
71 if inputs:
73 first_session = inputs[0][0]
72 first_session = inputs[0][0]
74 outputs = list(con.execute('SELECT session, line, output FROM '
73 outputs = list(con.execute('SELECT session, line, output FROM '
75 'output_history WHERE session >= ?', (first_session,)))
74 'output_history WHERE session >= ?', (first_session,)))
76 sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM '
75 sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM '
77 'sessions WHERE session >= ?', (first_session,)))
76 'sessions WHERE session >= ?', (first_session,)))
78 con.close()
77 con.close()
79
78
80 # Create the new history database.
79 # Create the new history database.
81 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new')
80 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new')
82 i = 0
81 i = 0
83 while os.path.exists(new_hist_file):
82 while os.path.exists(new_hist_file):
84 # Make sure we don't interfere with an existing file.
83 # Make sure we don't interfere with an existing file.
85 i += 1
84 i += 1
86 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new'+str(i))
85 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new'+str(i))
87 new_db = sqlite3.connect(new_hist_file)
86 new_db = sqlite3.connect(new_hist_file)
88 new_db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
87 new_db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
89 primary key autoincrement, start timestamp,
88 primary key autoincrement, start timestamp,
90 end timestamp, num_cmds integer, remark text)""")
89 end timestamp, num_cmds integer, remark text)""")
91 new_db.execute("""CREATE TABLE IF NOT EXISTS history
90 new_db.execute("""CREATE TABLE IF NOT EXISTS history
92 (session integer, line integer, source text, source_raw text,
91 (session integer, line integer, source text, source_raw text,
93 PRIMARY KEY (session, line))""")
92 PRIMARY KEY (session, line))""")
94 new_db.execute("""CREATE TABLE IF NOT EXISTS output_history
93 new_db.execute("""CREATE TABLE IF NOT EXISTS output_history
95 (session integer, line integer, output text,
94 (session integer, line integer, output text,
96 PRIMARY KEY (session, line))""")
95 PRIMARY KEY (session, line))""")
97 new_db.commit()
96 new_db.commit()
98
97
99
98
100 if inputs:
99 if inputs:
101 with new_db:
100 with new_db:
102 # Add the recent history into the new database.
101 # Add the recent history into the new database.
103 new_db.executemany('insert into sessions values (?,?,?,?,?)', sessions)
102 new_db.executemany('insert into sessions values (?,?,?,?,?)', sessions)
104 new_db.executemany('insert into history values (?,?,?,?)', inputs)
103 new_db.executemany('insert into history values (?,?,?,?)', inputs)
105 new_db.executemany('insert into output_history values (?,?,?)', outputs)
104 new_db.executemany('insert into output_history values (?,?,?)', outputs)
106 new_db.close()
105 new_db.close()
107
106
108 if self.backup:
107 if self.backup:
109 i = 1
108 i = 1
110 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
109 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
111 while os.path.exists(backup_hist_file):
110 while os.path.exists(backup_hist_file):
112 i += 1
111 i += 1
113 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
112 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
114 os.rename(hist_file, backup_hist_file)
113 os.rename(hist_file, backup_hist_file)
115 print("Backed up longer history file to", backup_hist_file)
114 print("Backed up longer history file to", backup_hist_file)
116 else:
115 else:
117 os.remove(hist_file)
116 os.remove(hist_file)
118
117
119 os.rename(new_hist_file, hist_file)
118 os.rename(new_hist_file, hist_file)
120
119
121 class HistoryClear(HistoryTrim):
120 class HistoryClear(HistoryTrim):
122 description = clear_hist_help
121 description = clear_hist_help
123 keep = Int(0,
122 keep = Int(0,
124 help="Number of recent lines to keep in the database.")
123 help="Number of recent lines to keep in the database.")
125
124
126 force = Bool(False,
125 force = Bool(False,
127 help="Don't prompt user for confirmation"
126 help="Don't prompt user for confirmation"
128 ).tag(config=True)
127 ).tag(config=True)
129
128
130 flags = Dict(dict(
129 flags = Dict(dict(
131 force = ({'HistoryClear' : {'force' : True}},
130 force = ({'HistoryClear' : {'force' : True}},
132 force.help),
131 force.help),
133 f = ({'HistoryTrim' : {'force' : True}},
132 f = ({'HistoryTrim' : {'force' : True}},
134 force.help
133 force.help
135 )
134 )
136 ))
135 ))
137 aliases = Dict()
136 aliases = Dict()
138
137
139 def start(self):
138 def start(self):
140 if self.force or ask_yes_no("Really delete all ipython history? ",
139 if self.force or ask_yes_no("Really delete all ipython history? ",
141 default="no", interrupt="no"):
140 default="no", interrupt="no"):
142 HistoryTrim.start(self)
141 HistoryTrim.start(self)
143
142
144 class HistoryApp(Application):
143 class HistoryApp(Application):
145 name = u'ipython-history'
144 name = u'ipython-history'
146 description = "Manage the IPython history database."
145 description = "Manage the IPython history database."
147
146
148 subcommands = Dict(dict(
147 subcommands = Dict(dict(
149 trim = (HistoryTrim, HistoryTrim.description.splitlines()[0]),
148 trim = (HistoryTrim, HistoryTrim.description.splitlines()[0]),
150 clear = (HistoryClear, HistoryClear.description.splitlines()[0]),
149 clear = (HistoryClear, HistoryClear.description.splitlines()[0]),
151 ))
150 ))
152
151
153 def start(self):
152 def start(self):
154 if self.subapp is None:
153 if self.subapp is None:
155 print("No subcommand specified. Must specify one of: %s" % \
154 print("No subcommand specified. Must specify one of: %s" % \
156 (self.subcommands.keys()))
155 (self.subcommands.keys()))
157 print()
156 print()
158 self.print_description()
157 self.print_description()
159 self.print_subcommands()
158 self.print_subcommands()
160 self.exit(1)
159 self.exit(1)
161 else:
160 else:
162 return self.subapp.start()
161 return self.subapp.start()
@@ -1,3226 +1,3225 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 from __future__ import absolute_import, print_function
14
13
15 import __future__
14 import __future__
16 import abc
15 import abc
17 import ast
16 import ast
18 import atexit
17 import atexit
19 import functools
18 import functools
20 import os
19 import os
21 import re
20 import re
22 import runpy
21 import runpy
23 import sys
22 import sys
24 import tempfile
23 import tempfile
25 import traceback
24 import traceback
26 import types
25 import types
27 import subprocess
26 import subprocess
28 import warnings
27 import warnings
29 from io import open as io_open
28 from io import open as io_open
30
29
31 from pickleshare import PickleShareDB
30 from pickleshare import PickleShareDB
32
31
33 from traitlets.config.configurable import SingletonConfigurable
32 from traitlets.config.configurable import SingletonConfigurable
34 from IPython.core import oinspect
33 from IPython.core import oinspect
35 from IPython.core import magic
34 from IPython.core import magic
36 from IPython.core import page
35 from IPython.core import page
37 from IPython.core import prefilter
36 from IPython.core import prefilter
38 from IPython.core import shadowns
37 from IPython.core import shadowns
39 from IPython.core import ultratb
38 from IPython.core import ultratb
40 from IPython.core.alias import Alias, AliasManager
39 from IPython.core.alias import Alias, AliasManager
41 from IPython.core.autocall import ExitAutocall
40 from IPython.core.autocall import ExitAutocall
42 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.events import EventManager, available_events
42 from IPython.core.events import EventManager, available_events
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
43 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 from IPython.core.debugger import Pdb
44 from IPython.core.debugger import Pdb
46 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
47 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
48 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
49 from IPython.core.error import InputRejected, UsageError
48 from IPython.core.error import InputRejected, UsageError
50 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
51 from IPython.core.formatters import DisplayFormatter
50 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.history import HistoryManager
51 from IPython.core.history import HistoryManager
53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
52 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
54 from IPython.core.logger import Logger
53 from IPython.core.logger import Logger
55 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
56 from IPython.core.payload import PayloadManager
55 from IPython.core.payload import PayloadManager
57 from IPython.core.prefilter import PrefilterManager
56 from IPython.core.prefilter import PrefilterManager
58 from IPython.core.profiledir import ProfileDir
57 from IPython.core.profiledir import ProfileDir
59 from IPython.core.usage import default_banner
58 from IPython.core.usage import default_banner
60 from IPython.testing.skipdoctest import skip_doctest
59 from IPython.testing.skipdoctest import skip_doctest
61 from IPython.utils import PyColorize
60 from IPython.utils import PyColorize
62 from IPython.utils import io
61 from IPython.utils import io
63 from IPython.utils import py3compat
62 from IPython.utils import py3compat
64 from IPython.utils import openpy
63 from IPython.utils import openpy
65 from IPython.utils.decorators import undoc
64 from IPython.utils.decorators import undoc
66 from IPython.utils.io import ask_yes_no
65 from IPython.utils.io import ask_yes_no
67 from IPython.utils.ipstruct import Struct
66 from IPython.utils.ipstruct import Struct
68 from IPython.paths import get_ipython_dir
67 from IPython.paths import get_ipython_dir
69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
70 from IPython.utils.process import system, getoutput
69 from IPython.utils.process import system, getoutput
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
70 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 with_metaclass, iteritems)
71 with_metaclass, iteritems)
73 from IPython.utils.strdispatch import StrDispatch
72 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.syspathcontext import prepended_to_syspath
73 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
74 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 from IPython.utils.tempdir import TemporaryDirectory
75 from IPython.utils.tempdir import TemporaryDirectory
77 from traitlets import (
76 from traitlets import (
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
77 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 observe, default,
78 observe, default,
80 )
79 )
81 from warnings import warn
80 from warnings import warn
82 from logging import error
81 from logging import error
83 import IPython.core.hooks
82 import IPython.core.hooks
84
83
85 # NoOpContext is deprecated, but ipykernel imports it from here.
84 # NoOpContext is deprecated, but ipykernel imports it from here.
86 # See https://github.com/ipython/ipykernel/issues/157
85 # See https://github.com/ipython/ipykernel/issues/157
87 from IPython.utils.contexts import NoOpContext
86 from IPython.utils.contexts import NoOpContext
88
87
89 try:
88 try:
90 import docrepr.sphinxify as sphx
89 import docrepr.sphinxify as sphx
91
90
92 def sphinxify(doc):
91 def sphinxify(doc):
93 with TemporaryDirectory() as dirname:
92 with TemporaryDirectory() as dirname:
94 return {
93 return {
95 'text/html': sphx.sphinxify(doc, dirname),
94 'text/html': sphx.sphinxify(doc, dirname),
96 'text/plain': doc
95 'text/plain': doc
97 }
96 }
98 except ImportError:
97 except ImportError:
99 sphinxify = None
98 sphinxify = None
100
99
101
100
102 class ProvisionalWarning(DeprecationWarning):
101 class ProvisionalWarning(DeprecationWarning):
103 """
102 """
104 Warning class for unstable features
103 Warning class for unstable features
105 """
104 """
106 pass
105 pass
107
106
108 #-----------------------------------------------------------------------------
107 #-----------------------------------------------------------------------------
109 # Globals
108 # Globals
110 #-----------------------------------------------------------------------------
109 #-----------------------------------------------------------------------------
111
110
112 # compiled regexps for autoindent management
111 # compiled regexps for autoindent management
113 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
112 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
114
113
115 #-----------------------------------------------------------------------------
114 #-----------------------------------------------------------------------------
116 # Utilities
115 # Utilities
117 #-----------------------------------------------------------------------------
116 #-----------------------------------------------------------------------------
118
117
119 @undoc
118 @undoc
120 def softspace(file, newvalue):
119 def softspace(file, newvalue):
121 """Copied from code.py, to remove the dependency"""
120 """Copied from code.py, to remove the dependency"""
122
121
123 oldvalue = 0
122 oldvalue = 0
124 try:
123 try:
125 oldvalue = file.softspace
124 oldvalue = file.softspace
126 except AttributeError:
125 except AttributeError:
127 pass
126 pass
128 try:
127 try:
129 file.softspace = newvalue
128 file.softspace = newvalue
130 except (AttributeError, TypeError):
129 except (AttributeError, TypeError):
131 # "attribute-less object" or "read-only attributes"
130 # "attribute-less object" or "read-only attributes"
132 pass
131 pass
133 return oldvalue
132 return oldvalue
134
133
135 @undoc
134 @undoc
136 def no_op(*a, **kw): pass
135 def no_op(*a, **kw): pass
137
136
138
137
139 class SpaceInInput(Exception): pass
138 class SpaceInInput(Exception): pass
140
139
141
140
142 def get_default_colors():
141 def get_default_colors():
143 "DEPRECATED"
142 "DEPRECATED"
144 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
143 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
145 DeprecationWarning, stacklevel=2)
144 DeprecationWarning, stacklevel=2)
146 return 'Neutral'
145 return 'Neutral'
147
146
148
147
149 class SeparateUnicode(Unicode):
148 class SeparateUnicode(Unicode):
150 r"""A Unicode subclass to validate separate_in, separate_out, etc.
149 r"""A Unicode subclass to validate separate_in, separate_out, etc.
151
150
152 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
151 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
153 """
152 """
154
153
155 def validate(self, obj, value):
154 def validate(self, obj, value):
156 if value == '0': value = ''
155 if value == '0': value = ''
157 value = value.replace('\\n','\n')
156 value = value.replace('\\n','\n')
158 return super(SeparateUnicode, self).validate(obj, value)
157 return super(SeparateUnicode, self).validate(obj, value)
159
158
160
159
161 @undoc
160 @undoc
162 class DummyMod(object):
161 class DummyMod(object):
163 """A dummy module used for IPython's interactive module when
162 """A dummy module used for IPython's interactive module when
164 a namespace must be assigned to the module's __dict__."""
163 a namespace must be assigned to the module's __dict__."""
165 pass
164 pass
166
165
167
166
168 class ExecutionResult(object):
167 class ExecutionResult(object):
169 """The result of a call to :meth:`InteractiveShell.run_cell`
168 """The result of a call to :meth:`InteractiveShell.run_cell`
170
169
171 Stores information about what took place.
170 Stores information about what took place.
172 """
171 """
173 execution_count = None
172 execution_count = None
174 error_before_exec = None
173 error_before_exec = None
175 error_in_exec = None
174 error_in_exec = None
176 result = None
175 result = None
177
176
178 @property
177 @property
179 def success(self):
178 def success(self):
180 return (self.error_before_exec is None) and (self.error_in_exec is None)
179 return (self.error_before_exec is None) and (self.error_in_exec is None)
181
180
182 def raise_error(self):
181 def raise_error(self):
183 """Reraises error if `success` is `False`, otherwise does nothing"""
182 """Reraises error if `success` is `False`, otherwise does nothing"""
184 if self.error_before_exec is not None:
183 if self.error_before_exec is not None:
185 raise self.error_before_exec
184 raise self.error_before_exec
186 if self.error_in_exec is not None:
185 if self.error_in_exec is not None:
187 raise self.error_in_exec
186 raise self.error_in_exec
188
187
189 def __repr__(self):
188 def __repr__(self):
190 name = self.__class__.__qualname__
189 name = self.__class__.__qualname__
191 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
190 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
192 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
191 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
193
192
194
193
195 class InteractiveShell(SingletonConfigurable):
194 class InteractiveShell(SingletonConfigurable):
196 """An enhanced, interactive shell for Python."""
195 """An enhanced, interactive shell for Python."""
197
196
198 _instance = None
197 _instance = None
199
198
200 ast_transformers = List([], help=
199 ast_transformers = List([], help=
201 """
200 """
202 A list of ast.NodeTransformer subclass instances, which will be applied
201 A list of ast.NodeTransformer subclass instances, which will be applied
203 to user input before code is run.
202 to user input before code is run.
204 """
203 """
205 ).tag(config=True)
204 ).tag(config=True)
206
205
207 autocall = Enum((0,1,2), default_value=0, help=
206 autocall = Enum((0,1,2), default_value=0, help=
208 """
207 """
209 Make IPython automatically call any callable object even if you didn't
208 Make IPython automatically call any callable object even if you didn't
210 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
209 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
211 automatically. The value can be '0' to disable the feature, '1' for
210 automatically. The value can be '0' to disable the feature, '1' for
212 'smart' autocall, where it is not applied if there are no more
211 'smart' autocall, where it is not applied if there are no more
213 arguments on the line, and '2' for 'full' autocall, where all callable
212 arguments on the line, and '2' for 'full' autocall, where all callable
214 objects are automatically called (even if no arguments are present).
213 objects are automatically called (even if no arguments are present).
215 """
214 """
216 ).tag(config=True)
215 ).tag(config=True)
217 # TODO: remove all autoindent logic and put into frontends.
216 # TODO: remove all autoindent logic and put into frontends.
218 # We can't do this yet because even runlines uses the autoindent.
217 # We can't do this yet because even runlines uses the autoindent.
219 autoindent = Bool(True, help=
218 autoindent = Bool(True, help=
220 """
219 """
221 Autoindent IPython code entered interactively.
220 Autoindent IPython code entered interactively.
222 """
221 """
223 ).tag(config=True)
222 ).tag(config=True)
224
223
225 automagic = Bool(True, help=
224 automagic = Bool(True, help=
226 """
225 """
227 Enable magic commands to be called without the leading %.
226 Enable magic commands to be called without the leading %.
228 """
227 """
229 ).tag(config=True)
228 ).tag(config=True)
230
229
231 banner1 = Unicode(default_banner,
230 banner1 = Unicode(default_banner,
232 help="""The part of the banner to be printed before the profile"""
231 help="""The part of the banner to be printed before the profile"""
233 ).tag(config=True)
232 ).tag(config=True)
234 banner2 = Unicode('',
233 banner2 = Unicode('',
235 help="""The part of the banner to be printed after the profile"""
234 help="""The part of the banner to be printed after the profile"""
236 ).tag(config=True)
235 ).tag(config=True)
237
236
238 cache_size = Integer(1000, help=
237 cache_size = Integer(1000, help=
239 """
238 """
240 Set the size of the output cache. The default is 1000, you can
239 Set the size of the output cache. The default is 1000, you can
241 change it permanently in your config file. Setting it to 0 completely
240 change it permanently in your config file. Setting it to 0 completely
242 disables the caching system, and the minimum value accepted is 20 (if
241 disables the caching system, and the minimum value accepted is 20 (if
243 you provide a value less than 20, it is reset to 0 and a warning is
242 you provide a value less than 20, it is reset to 0 and a warning is
244 issued). This limit is defined because otherwise you'll spend more
243 issued). This limit is defined because otherwise you'll spend more
245 time re-flushing a too small cache than working
244 time re-flushing a too small cache than working
246 """
245 """
247 ).tag(config=True)
246 ).tag(config=True)
248 color_info = Bool(True, help=
247 color_info = Bool(True, help=
249 """
248 """
250 Use colors for displaying information about objects. Because this
249 Use colors for displaying information about objects. Because this
251 information is passed through a pager (like 'less'), and some pagers
250 information is passed through a pager (like 'less'), and some pagers
252 get confused with color codes, this capability can be turned off.
251 get confused with color codes, this capability can be turned off.
253 """
252 """
254 ).tag(config=True)
253 ).tag(config=True)
255 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
254 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
256 default_value='Neutral',
255 default_value='Neutral',
257 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
256 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
258 ).tag(config=True)
257 ).tag(config=True)
259 debug = Bool(False).tag(config=True)
258 debug = Bool(False).tag(config=True)
260 disable_failing_post_execute = Bool(False,
259 disable_failing_post_execute = Bool(False,
261 help="Don't call post-execute functions that have failed in the past."
260 help="Don't call post-execute functions that have failed in the past."
262 ).tag(config=True)
261 ).tag(config=True)
263 display_formatter = Instance(DisplayFormatter, allow_none=True)
262 display_formatter = Instance(DisplayFormatter, allow_none=True)
264 displayhook_class = Type(DisplayHook)
263 displayhook_class = Type(DisplayHook)
265 display_pub_class = Type(DisplayPublisher)
264 display_pub_class = Type(DisplayPublisher)
266
265
267 sphinxify_docstring = Bool(False, help=
266 sphinxify_docstring = Bool(False, help=
268 """
267 """
269 Enables rich html representation of docstrings. (This requires the
268 Enables rich html representation of docstrings. (This requires the
270 docrepr module).
269 docrepr module).
271 """).tag(config=True)
270 """).tag(config=True)
272
271
273 @observe("sphinxify_docstring")
272 @observe("sphinxify_docstring")
274 def _sphinxify_docstring_changed(self, change):
273 def _sphinxify_docstring_changed(self, change):
275 if change['new']:
274 if change['new']:
276 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
275 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
277
276
278 enable_html_pager = Bool(False, help=
277 enable_html_pager = Bool(False, help=
279 """
278 """
280 (Provisional API) enables html representation in mime bundles sent
279 (Provisional API) enables html representation in mime bundles sent
281 to pagers.
280 to pagers.
282 """).tag(config=True)
281 """).tag(config=True)
283
282
284 @observe("enable_html_pager")
283 @observe("enable_html_pager")
285 def _enable_html_pager_changed(self, change):
284 def _enable_html_pager_changed(self, change):
286 if change['new']:
285 if change['new']:
287 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
286 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
288
287
289 data_pub_class = None
288 data_pub_class = None
290
289
291 exit_now = Bool(False)
290 exit_now = Bool(False)
292 exiter = Instance(ExitAutocall)
291 exiter = Instance(ExitAutocall)
293 @default('exiter')
292 @default('exiter')
294 def _exiter_default(self):
293 def _exiter_default(self):
295 return ExitAutocall(self)
294 return ExitAutocall(self)
296 # Monotonically increasing execution counter
295 # Monotonically increasing execution counter
297 execution_count = Integer(1)
296 execution_count = Integer(1)
298 filename = Unicode("<ipython console>")
297 filename = Unicode("<ipython console>")
299 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
298 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
300
299
301 # Input splitter, to transform input line by line and detect when a block
300 # Input splitter, to transform input line by line and detect when a block
302 # is ready to be executed.
301 # is ready to be executed.
303 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
302 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
304 (), {'line_input_checker': True})
303 (), {'line_input_checker': True})
305
304
306 # This InputSplitter instance is used to transform completed cells before
305 # This InputSplitter instance is used to transform completed cells before
307 # running them. It allows cell magics to contain blank lines.
306 # running them. It allows cell magics to contain blank lines.
308 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
307 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
309 (), {'line_input_checker': False})
308 (), {'line_input_checker': False})
310
309
311 logstart = Bool(False, help=
310 logstart = Bool(False, help=
312 """
311 """
313 Start logging to the default log file in overwrite mode.
312 Start logging to the default log file in overwrite mode.
314 Use `logappend` to specify a log file to **append** logs to.
313 Use `logappend` to specify a log file to **append** logs to.
315 """
314 """
316 ).tag(config=True)
315 ).tag(config=True)
317 logfile = Unicode('', help=
316 logfile = Unicode('', help=
318 """
317 """
319 The name of the logfile to use.
318 The name of the logfile to use.
320 """
319 """
321 ).tag(config=True)
320 ).tag(config=True)
322 logappend = Unicode('', help=
321 logappend = Unicode('', help=
323 """
322 """
324 Start logging to the given file in append mode.
323 Start logging to the given file in append mode.
325 Use `logfile` to specify a log file to **overwrite** logs to.
324 Use `logfile` to specify a log file to **overwrite** logs to.
326 """
325 """
327 ).tag(config=True)
326 ).tag(config=True)
328 object_info_string_level = Enum((0,1,2), default_value=0,
327 object_info_string_level = Enum((0,1,2), default_value=0,
329 ).tag(config=True)
328 ).tag(config=True)
330 pdb = Bool(False, help=
329 pdb = Bool(False, help=
331 """
330 """
332 Automatically call the pdb debugger after every exception.
331 Automatically call the pdb debugger after every exception.
333 """
332 """
334 ).tag(config=True)
333 ).tag(config=True)
335 display_page = Bool(False,
334 display_page = Bool(False,
336 help="""If True, anything that would be passed to the pager
335 help="""If True, anything that would be passed to the pager
337 will be displayed as regular output instead."""
336 will be displayed as regular output instead."""
338 ).tag(config=True)
337 ).tag(config=True)
339
338
340 # deprecated prompt traits:
339 # deprecated prompt traits:
341
340
342 prompt_in1 = Unicode('In [\\#]: ',
341 prompt_in1 = Unicode('In [\\#]: ',
343 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
342 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
344 ).tag(config=True)
343 ).tag(config=True)
345 prompt_in2 = Unicode(' .\\D.: ',
344 prompt_in2 = Unicode(' .\\D.: ',
346 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
345 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
347 ).tag(config=True)
346 ).tag(config=True)
348 prompt_out = Unicode('Out[\\#]: ',
347 prompt_out = Unicode('Out[\\#]: ',
349 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
348 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
350 ).tag(config=True)
349 ).tag(config=True)
351 prompts_pad_left = Bool(True,
350 prompts_pad_left = Bool(True,
352 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
351 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
353 ).tag(config=True)
352 ).tag(config=True)
354
353
355 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
354 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
356 def _prompt_trait_changed(self, change):
355 def _prompt_trait_changed(self, change):
357 name = change['name']
356 name = change['name']
358 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
357 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
359 name=name)
358 name=name)
360 )
359 )
361 # protect against weird cases where self.config may not exist:
360 # protect against weird cases where self.config may not exist:
362
361
363 show_rewritten_input = Bool(True,
362 show_rewritten_input = Bool(True,
364 help="Show rewritten input, e.g. for autocall."
363 help="Show rewritten input, e.g. for autocall."
365 ).tag(config=True)
364 ).tag(config=True)
366
365
367 quiet = Bool(False).tag(config=True)
366 quiet = Bool(False).tag(config=True)
368
367
369 history_length = Integer(10000,
368 history_length = Integer(10000,
370 help='Total length of command history'
369 help='Total length of command history'
371 ).tag(config=True)
370 ).tag(config=True)
372
371
373 history_load_length = Integer(1000, help=
372 history_load_length = Integer(1000, help=
374 """
373 """
375 The number of saved history entries to be loaded
374 The number of saved history entries to be loaded
376 into the history buffer at startup.
375 into the history buffer at startup.
377 """
376 """
378 ).tag(config=True)
377 ).tag(config=True)
379
378
380 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
379 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
381 default_value='last_expr',
380 default_value='last_expr',
382 help="""
381 help="""
383 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
382 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
384 run interactively (displaying output from expressions)."""
383 run interactively (displaying output from expressions)."""
385 ).tag(config=True)
384 ).tag(config=True)
386
385
387 # TODO: this part of prompt management should be moved to the frontends.
386 # TODO: this part of prompt management should be moved to the frontends.
388 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
387 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
389 separate_in = SeparateUnicode('\n').tag(config=True)
388 separate_in = SeparateUnicode('\n').tag(config=True)
390 separate_out = SeparateUnicode('').tag(config=True)
389 separate_out = SeparateUnicode('').tag(config=True)
391 separate_out2 = SeparateUnicode('').tag(config=True)
390 separate_out2 = SeparateUnicode('').tag(config=True)
392 wildcards_case_sensitive = Bool(True).tag(config=True)
391 wildcards_case_sensitive = Bool(True).tag(config=True)
393 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
392 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
394 default_value='Context').tag(config=True)
393 default_value='Context').tag(config=True)
395
394
396 # Subcomponents of InteractiveShell
395 # Subcomponents of InteractiveShell
397 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
396 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
398 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
397 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
399 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
398 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
400 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
399 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
401 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
400 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
402 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
401 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
403 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
402 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
404 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
403 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
405
404
406 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
405 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
407 @property
406 @property
408 def profile(self):
407 def profile(self):
409 if self.profile_dir is not None:
408 if self.profile_dir is not None:
410 name = os.path.basename(self.profile_dir.location)
409 name = os.path.basename(self.profile_dir.location)
411 return name.replace('profile_','')
410 return name.replace('profile_','')
412
411
413
412
414 # Private interface
413 # Private interface
415 _post_execute = Dict()
414 _post_execute = Dict()
416
415
417 # Tracks any GUI loop loaded for pylab
416 # Tracks any GUI loop loaded for pylab
418 pylab_gui_select = None
417 pylab_gui_select = None
419
418
420 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
419 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
421
420
422 def __init__(self, ipython_dir=None, profile_dir=None,
421 def __init__(self, ipython_dir=None, profile_dir=None,
423 user_module=None, user_ns=None,
422 user_module=None, user_ns=None,
424 custom_exceptions=((), None), **kwargs):
423 custom_exceptions=((), None), **kwargs):
425
424
426 # This is where traits with a config_key argument are updated
425 # This is where traits with a config_key argument are updated
427 # from the values on config.
426 # from the values on config.
428 super(InteractiveShell, self).__init__(**kwargs)
427 super(InteractiveShell, self).__init__(**kwargs)
429 if 'PromptManager' in self.config:
428 if 'PromptManager' in self.config:
430 warn('As of IPython 5.0 `PromptManager` config will have no effect'
429 warn('As of IPython 5.0 `PromptManager` config will have no effect'
431 ' and has been replaced by TerminalInteractiveShell.prompts_class')
430 ' and has been replaced by TerminalInteractiveShell.prompts_class')
432 self.configurables = [self]
431 self.configurables = [self]
433
432
434 # These are relatively independent and stateless
433 # These are relatively independent and stateless
435 self.init_ipython_dir(ipython_dir)
434 self.init_ipython_dir(ipython_dir)
436 self.init_profile_dir(profile_dir)
435 self.init_profile_dir(profile_dir)
437 self.init_instance_attrs()
436 self.init_instance_attrs()
438 self.init_environment()
437 self.init_environment()
439
438
440 # Check if we're in a virtualenv, and set up sys.path.
439 # Check if we're in a virtualenv, and set up sys.path.
441 self.init_virtualenv()
440 self.init_virtualenv()
442
441
443 # Create namespaces (user_ns, user_global_ns, etc.)
442 # Create namespaces (user_ns, user_global_ns, etc.)
444 self.init_create_namespaces(user_module, user_ns)
443 self.init_create_namespaces(user_module, user_ns)
445 # This has to be done after init_create_namespaces because it uses
444 # This has to be done after init_create_namespaces because it uses
446 # something in self.user_ns, but before init_sys_modules, which
445 # something in self.user_ns, but before init_sys_modules, which
447 # is the first thing to modify sys.
446 # is the first thing to modify sys.
448 # TODO: When we override sys.stdout and sys.stderr before this class
447 # TODO: When we override sys.stdout and sys.stderr before this class
449 # is created, we are saving the overridden ones here. Not sure if this
448 # is created, we are saving the overridden ones here. Not sure if this
450 # is what we want to do.
449 # is what we want to do.
451 self.save_sys_module_state()
450 self.save_sys_module_state()
452 self.init_sys_modules()
451 self.init_sys_modules()
453
452
454 # While we're trying to have each part of the code directly access what
453 # While we're trying to have each part of the code directly access what
455 # it needs without keeping redundant references to objects, we have too
454 # it needs without keeping redundant references to objects, we have too
456 # much legacy code that expects ip.db to exist.
455 # much legacy code that expects ip.db to exist.
457 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
456 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
458
457
459 self.init_history()
458 self.init_history()
460 self.init_encoding()
459 self.init_encoding()
461 self.init_prefilter()
460 self.init_prefilter()
462
461
463 self.init_syntax_highlighting()
462 self.init_syntax_highlighting()
464 self.init_hooks()
463 self.init_hooks()
465 self.init_events()
464 self.init_events()
466 self.init_pushd_popd_magic()
465 self.init_pushd_popd_magic()
467 self.init_user_ns()
466 self.init_user_ns()
468 self.init_logger()
467 self.init_logger()
469 self.init_builtins()
468 self.init_builtins()
470
469
471 # The following was in post_config_initialization
470 # The following was in post_config_initialization
472 self.init_inspector()
471 self.init_inspector()
473 self.raw_input_original = input
472 self.raw_input_original = input
474 self.init_completer()
473 self.init_completer()
475 # TODO: init_io() needs to happen before init_traceback handlers
474 # TODO: init_io() needs to happen before init_traceback handlers
476 # because the traceback handlers hardcode the stdout/stderr streams.
475 # because the traceback handlers hardcode the stdout/stderr streams.
477 # This logic in in debugger.Pdb and should eventually be changed.
476 # This logic in in debugger.Pdb and should eventually be changed.
478 self.init_io()
477 self.init_io()
479 self.init_traceback_handlers(custom_exceptions)
478 self.init_traceback_handlers(custom_exceptions)
480 self.init_prompts()
479 self.init_prompts()
481 self.init_display_formatter()
480 self.init_display_formatter()
482 self.init_display_pub()
481 self.init_display_pub()
483 self.init_data_pub()
482 self.init_data_pub()
484 self.init_displayhook()
483 self.init_displayhook()
485 self.init_magics()
484 self.init_magics()
486 self.init_alias()
485 self.init_alias()
487 self.init_logstart()
486 self.init_logstart()
488 self.init_pdb()
487 self.init_pdb()
489 self.init_extension_manager()
488 self.init_extension_manager()
490 self.init_payload()
489 self.init_payload()
491 self.init_deprecation_warnings()
490 self.init_deprecation_warnings()
492 self.hooks.late_startup_hook()
491 self.hooks.late_startup_hook()
493 self.events.trigger('shell_initialized', self)
492 self.events.trigger('shell_initialized', self)
494 atexit.register(self.atexit_operations)
493 atexit.register(self.atexit_operations)
495
494
496 def get_ipython(self):
495 def get_ipython(self):
497 """Return the currently running IPython instance."""
496 """Return the currently running IPython instance."""
498 return self
497 return self
499
498
500 #-------------------------------------------------------------------------
499 #-------------------------------------------------------------------------
501 # Trait changed handlers
500 # Trait changed handlers
502 #-------------------------------------------------------------------------
501 #-------------------------------------------------------------------------
503 @observe('ipython_dir')
502 @observe('ipython_dir')
504 def _ipython_dir_changed(self, change):
503 def _ipython_dir_changed(self, change):
505 ensure_dir_exists(change['new'])
504 ensure_dir_exists(change['new'])
506
505
507 def set_autoindent(self,value=None):
506 def set_autoindent(self,value=None):
508 """Set the autoindent flag.
507 """Set the autoindent flag.
509
508
510 If called with no arguments, it acts as a toggle."""
509 If called with no arguments, it acts as a toggle."""
511 if value is None:
510 if value is None:
512 self.autoindent = not self.autoindent
511 self.autoindent = not self.autoindent
513 else:
512 else:
514 self.autoindent = value
513 self.autoindent = value
515
514
516 #-------------------------------------------------------------------------
515 #-------------------------------------------------------------------------
517 # init_* methods called by __init__
516 # init_* methods called by __init__
518 #-------------------------------------------------------------------------
517 #-------------------------------------------------------------------------
519
518
520 def init_ipython_dir(self, ipython_dir):
519 def init_ipython_dir(self, ipython_dir):
521 if ipython_dir is not None:
520 if ipython_dir is not None:
522 self.ipython_dir = ipython_dir
521 self.ipython_dir = ipython_dir
523 return
522 return
524
523
525 self.ipython_dir = get_ipython_dir()
524 self.ipython_dir = get_ipython_dir()
526
525
527 def init_profile_dir(self, profile_dir):
526 def init_profile_dir(self, profile_dir):
528 if profile_dir is not None:
527 if profile_dir is not None:
529 self.profile_dir = profile_dir
528 self.profile_dir = profile_dir
530 return
529 return
531 self.profile_dir =\
530 self.profile_dir =\
532 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
531 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
533
532
534 def init_instance_attrs(self):
533 def init_instance_attrs(self):
535 self.more = False
534 self.more = False
536
535
537 # command compiler
536 # command compiler
538 self.compile = CachingCompiler()
537 self.compile = CachingCompiler()
539
538
540 # Make an empty namespace, which extension writers can rely on both
539 # Make an empty namespace, which extension writers can rely on both
541 # existing and NEVER being used by ipython itself. This gives them a
540 # existing and NEVER being used by ipython itself. This gives them a
542 # convenient location for storing additional information and state
541 # convenient location for storing additional information and state
543 # their extensions may require, without fear of collisions with other
542 # their extensions may require, without fear of collisions with other
544 # ipython names that may develop later.
543 # ipython names that may develop later.
545 self.meta = Struct()
544 self.meta = Struct()
546
545
547 # Temporary files used for various purposes. Deleted at exit.
546 # Temporary files used for various purposes. Deleted at exit.
548 self.tempfiles = []
547 self.tempfiles = []
549 self.tempdirs = []
548 self.tempdirs = []
550
549
551 # keep track of where we started running (mainly for crash post-mortem)
550 # keep track of where we started running (mainly for crash post-mortem)
552 # This is not being used anywhere currently.
551 # This is not being used anywhere currently.
553 self.starting_dir = py3compat.getcwd()
552 self.starting_dir = py3compat.getcwd()
554
553
555 # Indentation management
554 # Indentation management
556 self.indent_current_nsp = 0
555 self.indent_current_nsp = 0
557
556
558 # Dict to track post-execution functions that have been registered
557 # Dict to track post-execution functions that have been registered
559 self._post_execute = {}
558 self._post_execute = {}
560
559
561 def init_environment(self):
560 def init_environment(self):
562 """Any changes we need to make to the user's environment."""
561 """Any changes we need to make to the user's environment."""
563 pass
562 pass
564
563
565 def init_encoding(self):
564 def init_encoding(self):
566 # Get system encoding at startup time. Certain terminals (like Emacs
565 # Get system encoding at startup time. Certain terminals (like Emacs
567 # under Win32 have it set to None, and we need to have a known valid
566 # under Win32 have it set to None, and we need to have a known valid
568 # encoding to use in the raw_input() method
567 # encoding to use in the raw_input() method
569 try:
568 try:
570 self.stdin_encoding = sys.stdin.encoding or 'ascii'
569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
571 except AttributeError:
570 except AttributeError:
572 self.stdin_encoding = 'ascii'
571 self.stdin_encoding = 'ascii'
573
572
574
573
575 @observe('colors')
574 @observe('colors')
576 def init_syntax_highlighting(self, changes=None):
575 def init_syntax_highlighting(self, changes=None):
577 # Python source parser/formatter for syntax highlighting
576 # Python source parser/formatter for syntax highlighting
578 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
577 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
579 self.pycolorize = lambda src: pyformat(src,'str')
578 self.pycolorize = lambda src: pyformat(src,'str')
580
579
581 def refresh_style(self):
580 def refresh_style(self):
582 # No-op here, used in subclass
581 # No-op here, used in subclass
583 pass
582 pass
584
583
585 def init_pushd_popd_magic(self):
584 def init_pushd_popd_magic(self):
586 # for pushd/popd management
585 # for pushd/popd management
587 self.home_dir = get_home_dir()
586 self.home_dir = get_home_dir()
588
587
589 self.dir_stack = []
588 self.dir_stack = []
590
589
591 def init_logger(self):
590 def init_logger(self):
592 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
591 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
593 logmode='rotate')
592 logmode='rotate')
594
593
595 def init_logstart(self):
594 def init_logstart(self):
596 """Initialize logging in case it was requested at the command line.
595 """Initialize logging in case it was requested at the command line.
597 """
596 """
598 if self.logappend:
597 if self.logappend:
599 self.magic('logstart %s append' % self.logappend)
598 self.magic('logstart %s append' % self.logappend)
600 elif self.logfile:
599 elif self.logfile:
601 self.magic('logstart %s' % self.logfile)
600 self.magic('logstart %s' % self.logfile)
602 elif self.logstart:
601 elif self.logstart:
603 self.magic('logstart')
602 self.magic('logstart')
604
603
605 def init_deprecation_warnings(self):
604 def init_deprecation_warnings(self):
606 """
605 """
607 register default filter for deprecation warning.
606 register default filter for deprecation warning.
608
607
609 This will allow deprecation warning of function used interactively to show
608 This will allow deprecation warning of function used interactively to show
610 warning to users, and still hide deprecation warning from libraries import.
609 warning to users, and still hide deprecation warning from libraries import.
611 """
610 """
612 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
611 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
613
612
614 def init_builtins(self):
613 def init_builtins(self):
615 # A single, static flag that we set to True. Its presence indicates
614 # A single, static flag that we set to True. Its presence indicates
616 # that an IPython shell has been created, and we make no attempts at
615 # that an IPython shell has been created, and we make no attempts at
617 # removing on exit or representing the existence of more than one
616 # removing on exit or representing the existence of more than one
618 # IPython at a time.
617 # IPython at a time.
619 builtin_mod.__dict__['__IPYTHON__'] = True
618 builtin_mod.__dict__['__IPYTHON__'] = True
620
619
621 self.builtin_trap = BuiltinTrap(shell=self)
620 self.builtin_trap = BuiltinTrap(shell=self)
622
621
623 def init_inspector(self):
622 def init_inspector(self):
624 # Object inspector
623 # Object inspector
625 self.inspector = oinspect.Inspector(oinspect.InspectColors,
624 self.inspector = oinspect.Inspector(oinspect.InspectColors,
626 PyColorize.ANSICodeColors,
625 PyColorize.ANSICodeColors,
627 'NoColor',
626 'NoColor',
628 self.object_info_string_level)
627 self.object_info_string_level)
629
628
630 def init_io(self):
629 def init_io(self):
631 # This will just use sys.stdout and sys.stderr. If you want to
630 # This will just use sys.stdout and sys.stderr. If you want to
632 # override sys.stdout and sys.stderr themselves, you need to do that
631 # override sys.stdout and sys.stderr themselves, you need to do that
633 # *before* instantiating this class, because io holds onto
632 # *before* instantiating this class, because io holds onto
634 # references to the underlying streams.
633 # references to the underlying streams.
635 # io.std* are deprecated, but don't show our own deprecation warnings
634 # io.std* are deprecated, but don't show our own deprecation warnings
636 # during initialization of the deprecated API.
635 # during initialization of the deprecated API.
637 with warnings.catch_warnings():
636 with warnings.catch_warnings():
638 warnings.simplefilter('ignore', DeprecationWarning)
637 warnings.simplefilter('ignore', DeprecationWarning)
639 io.stdout = io.IOStream(sys.stdout)
638 io.stdout = io.IOStream(sys.stdout)
640 io.stderr = io.IOStream(sys.stderr)
639 io.stderr = io.IOStream(sys.stderr)
641
640
642 def init_prompts(self):
641 def init_prompts(self):
643 # Set system prompts, so that scripts can decide if they are running
642 # Set system prompts, so that scripts can decide if they are running
644 # interactively.
643 # interactively.
645 sys.ps1 = 'In : '
644 sys.ps1 = 'In : '
646 sys.ps2 = '...: '
645 sys.ps2 = '...: '
647 sys.ps3 = 'Out: '
646 sys.ps3 = 'Out: '
648
647
649 def init_display_formatter(self):
648 def init_display_formatter(self):
650 self.display_formatter = DisplayFormatter(parent=self)
649 self.display_formatter = DisplayFormatter(parent=self)
651 self.configurables.append(self.display_formatter)
650 self.configurables.append(self.display_formatter)
652
651
653 def init_display_pub(self):
652 def init_display_pub(self):
654 self.display_pub = self.display_pub_class(parent=self)
653 self.display_pub = self.display_pub_class(parent=self)
655 self.configurables.append(self.display_pub)
654 self.configurables.append(self.display_pub)
656
655
657 def init_data_pub(self):
656 def init_data_pub(self):
658 if not self.data_pub_class:
657 if not self.data_pub_class:
659 self.data_pub = None
658 self.data_pub = None
660 return
659 return
661 self.data_pub = self.data_pub_class(parent=self)
660 self.data_pub = self.data_pub_class(parent=self)
662 self.configurables.append(self.data_pub)
661 self.configurables.append(self.data_pub)
663
662
664 def init_displayhook(self):
663 def init_displayhook(self):
665 # Initialize displayhook, set in/out prompts and printing system
664 # Initialize displayhook, set in/out prompts and printing system
666 self.displayhook = self.displayhook_class(
665 self.displayhook = self.displayhook_class(
667 parent=self,
666 parent=self,
668 shell=self,
667 shell=self,
669 cache_size=self.cache_size,
668 cache_size=self.cache_size,
670 )
669 )
671 self.configurables.append(self.displayhook)
670 self.configurables.append(self.displayhook)
672 # This is a context manager that installs/revmoes the displayhook at
671 # This is a context manager that installs/revmoes the displayhook at
673 # the appropriate time.
672 # the appropriate time.
674 self.display_trap = DisplayTrap(hook=self.displayhook)
673 self.display_trap = DisplayTrap(hook=self.displayhook)
675
674
676 def init_virtualenv(self):
675 def init_virtualenv(self):
677 """Add a virtualenv to sys.path so the user can import modules from it.
676 """Add a virtualenv to sys.path so the user can import modules from it.
678 This isn't perfect: it doesn't use the Python interpreter with which the
677 This isn't perfect: it doesn't use the Python interpreter with which the
679 virtualenv was built, and it ignores the --no-site-packages option. A
678 virtualenv was built, and it ignores the --no-site-packages option. A
680 warning will appear suggesting the user installs IPython in the
679 warning will appear suggesting the user installs IPython in the
681 virtualenv, but for many cases, it probably works well enough.
680 virtualenv, but for many cases, it probably works well enough.
682
681
683 Adapted from code snippets online.
682 Adapted from code snippets online.
684
683
685 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
684 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
686 """
685 """
687 if 'VIRTUAL_ENV' not in os.environ:
686 if 'VIRTUAL_ENV' not in os.environ:
688 # Not in a virtualenv
687 # Not in a virtualenv
689 return
688 return
690
689
691 # venv detection:
690 # venv detection:
692 # stdlib venv may symlink sys.executable, so we can't use realpath.
691 # stdlib venv may symlink sys.executable, so we can't use realpath.
693 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
692 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
694 # So we just check every item in the symlink tree (generally <= 3)
693 # So we just check every item in the symlink tree (generally <= 3)
695 p = os.path.normcase(sys.executable)
694 p = os.path.normcase(sys.executable)
696 paths = [p]
695 paths = [p]
697 while os.path.islink(p):
696 while os.path.islink(p):
698 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
697 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
699 paths.append(p)
698 paths.append(p)
700 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
699 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
701 if any(p.startswith(p_venv) for p in paths):
700 if any(p.startswith(p_venv) for p in paths):
702 # Running properly in the virtualenv, don't need to do anything
701 # Running properly in the virtualenv, don't need to do anything
703 return
702 return
704
703
705 warn("Attempting to work in a virtualenv. If you encounter problems, please "
704 warn("Attempting to work in a virtualenv. If you encounter problems, please "
706 "install IPython inside the virtualenv.")
705 "install IPython inside the virtualenv.")
707 if sys.platform == "win32":
706 if sys.platform == "win32":
708 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
707 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
709 else:
708 else:
710 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
709 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
711 'python%d.%d' % sys.version_info[:2], 'site-packages')
710 'python%d.%d' % sys.version_info[:2], 'site-packages')
712
711
713 import site
712 import site
714 sys.path.insert(0, virtual_env)
713 sys.path.insert(0, virtual_env)
715 site.addsitedir(virtual_env)
714 site.addsitedir(virtual_env)
716
715
717 #-------------------------------------------------------------------------
716 #-------------------------------------------------------------------------
718 # Things related to injections into the sys module
717 # Things related to injections into the sys module
719 #-------------------------------------------------------------------------
718 #-------------------------------------------------------------------------
720
719
721 def save_sys_module_state(self):
720 def save_sys_module_state(self):
722 """Save the state of hooks in the sys module.
721 """Save the state of hooks in the sys module.
723
722
724 This has to be called after self.user_module is created.
723 This has to be called after self.user_module is created.
725 """
724 """
726 self._orig_sys_module_state = {'stdin': sys.stdin,
725 self._orig_sys_module_state = {'stdin': sys.stdin,
727 'stdout': sys.stdout,
726 'stdout': sys.stdout,
728 'stderr': sys.stderr,
727 'stderr': sys.stderr,
729 'excepthook': sys.excepthook}
728 'excepthook': sys.excepthook}
730 self._orig_sys_modules_main_name = self.user_module.__name__
729 self._orig_sys_modules_main_name = self.user_module.__name__
731 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
730 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
732
731
733 def restore_sys_module_state(self):
732 def restore_sys_module_state(self):
734 """Restore the state of the sys module."""
733 """Restore the state of the sys module."""
735 try:
734 try:
736 for k, v in iteritems(self._orig_sys_module_state):
735 for k, v in iteritems(self._orig_sys_module_state):
737 setattr(sys, k, v)
736 setattr(sys, k, v)
738 except AttributeError:
737 except AttributeError:
739 pass
738 pass
740 # Reset what what done in self.init_sys_modules
739 # Reset what what done in self.init_sys_modules
741 if self._orig_sys_modules_main_mod is not None:
740 if self._orig_sys_modules_main_mod is not None:
742 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
741 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
743
742
744 #-------------------------------------------------------------------------
743 #-------------------------------------------------------------------------
745 # Things related to the banner
744 # Things related to the banner
746 #-------------------------------------------------------------------------
745 #-------------------------------------------------------------------------
747
746
748 @property
747 @property
749 def banner(self):
748 def banner(self):
750 banner = self.banner1
749 banner = self.banner1
751 if self.profile and self.profile != 'default':
750 if self.profile and self.profile != 'default':
752 banner += '\nIPython profile: %s\n' % self.profile
751 banner += '\nIPython profile: %s\n' % self.profile
753 if self.banner2:
752 if self.banner2:
754 banner += '\n' + self.banner2
753 banner += '\n' + self.banner2
755 return banner
754 return banner
756
755
757 def show_banner(self, banner=None):
756 def show_banner(self, banner=None):
758 if banner is None:
757 if banner is None:
759 banner = self.banner
758 banner = self.banner
760 sys.stdout.write(banner)
759 sys.stdout.write(banner)
761
760
762 #-------------------------------------------------------------------------
761 #-------------------------------------------------------------------------
763 # Things related to hooks
762 # Things related to hooks
764 #-------------------------------------------------------------------------
763 #-------------------------------------------------------------------------
765
764
766 def init_hooks(self):
765 def init_hooks(self):
767 # hooks holds pointers used for user-side customizations
766 # hooks holds pointers used for user-side customizations
768 self.hooks = Struct()
767 self.hooks = Struct()
769
768
770 self.strdispatchers = {}
769 self.strdispatchers = {}
771
770
772 # Set all default hooks, defined in the IPython.hooks module.
771 # Set all default hooks, defined in the IPython.hooks module.
773 hooks = IPython.core.hooks
772 hooks = IPython.core.hooks
774 for hook_name in hooks.__all__:
773 for hook_name in hooks.__all__:
775 # default hooks have priority 100, i.e. low; user hooks should have
774 # default hooks have priority 100, i.e. low; user hooks should have
776 # 0-100 priority
775 # 0-100 priority
777 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
776 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
778
777
779 if self.display_page:
778 if self.display_page:
780 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
779 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
781
780
782 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
781 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
783 _warn_deprecated=True):
782 _warn_deprecated=True):
784 """set_hook(name,hook) -> sets an internal IPython hook.
783 """set_hook(name,hook) -> sets an internal IPython hook.
785
784
786 IPython exposes some of its internal API as user-modifiable hooks. By
785 IPython exposes some of its internal API as user-modifiable hooks. By
787 adding your function to one of these hooks, you can modify IPython's
786 adding your function to one of these hooks, you can modify IPython's
788 behavior to call at runtime your own routines."""
787 behavior to call at runtime your own routines."""
789
788
790 # At some point in the future, this should validate the hook before it
789 # At some point in the future, this should validate the hook before it
791 # accepts it. Probably at least check that the hook takes the number
790 # accepts it. Probably at least check that the hook takes the number
792 # of args it's supposed to.
791 # of args it's supposed to.
793
792
794 f = types.MethodType(hook,self)
793 f = types.MethodType(hook,self)
795
794
796 # check if the hook is for strdispatcher first
795 # check if the hook is for strdispatcher first
797 if str_key is not None:
796 if str_key is not None:
798 sdp = self.strdispatchers.get(name, StrDispatch())
797 sdp = self.strdispatchers.get(name, StrDispatch())
799 sdp.add_s(str_key, f, priority )
798 sdp.add_s(str_key, f, priority )
800 self.strdispatchers[name] = sdp
799 self.strdispatchers[name] = sdp
801 return
800 return
802 if re_key is not None:
801 if re_key is not None:
803 sdp = self.strdispatchers.get(name, StrDispatch())
802 sdp = self.strdispatchers.get(name, StrDispatch())
804 sdp.add_re(re.compile(re_key), f, priority )
803 sdp.add_re(re.compile(re_key), f, priority )
805 self.strdispatchers[name] = sdp
804 self.strdispatchers[name] = sdp
806 return
805 return
807
806
808 dp = getattr(self.hooks, name, None)
807 dp = getattr(self.hooks, name, None)
809 if name not in IPython.core.hooks.__all__:
808 if name not in IPython.core.hooks.__all__:
810 print("Warning! Hook '%s' is not one of %s" % \
809 print("Warning! Hook '%s' is not one of %s" % \
811 (name, IPython.core.hooks.__all__ ))
810 (name, IPython.core.hooks.__all__ ))
812
811
813 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
812 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
814 alternative = IPython.core.hooks.deprecated[name]
813 alternative = IPython.core.hooks.deprecated[name]
815 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
814 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
816
815
817 if not dp:
816 if not dp:
818 dp = IPython.core.hooks.CommandChainDispatcher()
817 dp = IPython.core.hooks.CommandChainDispatcher()
819
818
820 try:
819 try:
821 dp.add(f,priority)
820 dp.add(f,priority)
822 except AttributeError:
821 except AttributeError:
823 # it was not commandchain, plain old func - replace
822 # it was not commandchain, plain old func - replace
824 dp = f
823 dp = f
825
824
826 setattr(self.hooks,name, dp)
825 setattr(self.hooks,name, dp)
827
826
828 #-------------------------------------------------------------------------
827 #-------------------------------------------------------------------------
829 # Things related to events
828 # Things related to events
830 #-------------------------------------------------------------------------
829 #-------------------------------------------------------------------------
831
830
832 def init_events(self):
831 def init_events(self):
833 self.events = EventManager(self, available_events)
832 self.events = EventManager(self, available_events)
834
833
835 self.events.register("pre_execute", self._clear_warning_registry)
834 self.events.register("pre_execute", self._clear_warning_registry)
836
835
837 def register_post_execute(self, func):
836 def register_post_execute(self, func):
838 """DEPRECATED: Use ip.events.register('post_run_cell', func)
837 """DEPRECATED: Use ip.events.register('post_run_cell', func)
839
838
840 Register a function for calling after code execution.
839 Register a function for calling after code execution.
841 """
840 """
842 warn("ip.register_post_execute is deprecated, use "
841 warn("ip.register_post_execute is deprecated, use "
843 "ip.events.register('post_run_cell', func) instead.")
842 "ip.events.register('post_run_cell', func) instead.")
844 self.events.register('post_run_cell', func)
843 self.events.register('post_run_cell', func)
845
844
846 def _clear_warning_registry(self):
845 def _clear_warning_registry(self):
847 # clear the warning registry, so that different code blocks with
846 # clear the warning registry, so that different code blocks with
848 # overlapping line number ranges don't cause spurious suppression of
847 # overlapping line number ranges don't cause spurious suppression of
849 # warnings (see gh-6611 for details)
848 # warnings (see gh-6611 for details)
850 if "__warningregistry__" in self.user_global_ns:
849 if "__warningregistry__" in self.user_global_ns:
851 del self.user_global_ns["__warningregistry__"]
850 del self.user_global_ns["__warningregistry__"]
852
851
853 #-------------------------------------------------------------------------
852 #-------------------------------------------------------------------------
854 # Things related to the "main" module
853 # Things related to the "main" module
855 #-------------------------------------------------------------------------
854 #-------------------------------------------------------------------------
856
855
857 def new_main_mod(self, filename, modname):
856 def new_main_mod(self, filename, modname):
858 """Return a new 'main' module object for user code execution.
857 """Return a new 'main' module object for user code execution.
859
858
860 ``filename`` should be the path of the script which will be run in the
859 ``filename`` should be the path of the script which will be run in the
861 module. Requests with the same filename will get the same module, with
860 module. Requests with the same filename will get the same module, with
862 its namespace cleared.
861 its namespace cleared.
863
862
864 ``modname`` should be the module name - normally either '__main__' or
863 ``modname`` should be the module name - normally either '__main__' or
865 the basename of the file without the extension.
864 the basename of the file without the extension.
866
865
867 When scripts are executed via %run, we must keep a reference to their
866 When scripts are executed via %run, we must keep a reference to their
868 __main__ module around so that Python doesn't
867 __main__ module around so that Python doesn't
869 clear it, rendering references to module globals useless.
868 clear it, rendering references to module globals useless.
870
869
871 This method keeps said reference in a private dict, keyed by the
870 This method keeps said reference in a private dict, keyed by the
872 absolute path of the script. This way, for multiple executions of the
871 absolute path of the script. This way, for multiple executions of the
873 same script we only keep one copy of the namespace (the last one),
872 same script we only keep one copy of the namespace (the last one),
874 thus preventing memory leaks from old references while allowing the
873 thus preventing memory leaks from old references while allowing the
875 objects from the last execution to be accessible.
874 objects from the last execution to be accessible.
876 """
875 """
877 filename = os.path.abspath(filename)
876 filename = os.path.abspath(filename)
878 try:
877 try:
879 main_mod = self._main_mod_cache[filename]
878 main_mod = self._main_mod_cache[filename]
880 except KeyError:
879 except KeyError:
881 main_mod = self._main_mod_cache[filename] = types.ModuleType(
880 main_mod = self._main_mod_cache[filename] = types.ModuleType(
882 py3compat.cast_bytes_py2(modname),
881 py3compat.cast_bytes_py2(modname),
883 doc="Module created for script run in IPython")
882 doc="Module created for script run in IPython")
884 else:
883 else:
885 main_mod.__dict__.clear()
884 main_mod.__dict__.clear()
886 main_mod.__name__ = modname
885 main_mod.__name__ = modname
887
886
888 main_mod.__file__ = filename
887 main_mod.__file__ = filename
889 # It seems pydoc (and perhaps others) needs any module instance to
888 # It seems pydoc (and perhaps others) needs any module instance to
890 # implement a __nonzero__ method
889 # implement a __nonzero__ method
891 main_mod.__nonzero__ = lambda : True
890 main_mod.__nonzero__ = lambda : True
892
891
893 return main_mod
892 return main_mod
894
893
895 def clear_main_mod_cache(self):
894 def clear_main_mod_cache(self):
896 """Clear the cache of main modules.
895 """Clear the cache of main modules.
897
896
898 Mainly for use by utilities like %reset.
897 Mainly for use by utilities like %reset.
899
898
900 Examples
899 Examples
901 --------
900 --------
902
901
903 In [15]: import IPython
902 In [15]: import IPython
904
903
905 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
904 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
906
905
907 In [17]: len(_ip._main_mod_cache) > 0
906 In [17]: len(_ip._main_mod_cache) > 0
908 Out[17]: True
907 Out[17]: True
909
908
910 In [18]: _ip.clear_main_mod_cache()
909 In [18]: _ip.clear_main_mod_cache()
911
910
912 In [19]: len(_ip._main_mod_cache) == 0
911 In [19]: len(_ip._main_mod_cache) == 0
913 Out[19]: True
912 Out[19]: True
914 """
913 """
915 self._main_mod_cache.clear()
914 self._main_mod_cache.clear()
916
915
917 #-------------------------------------------------------------------------
916 #-------------------------------------------------------------------------
918 # Things related to debugging
917 # Things related to debugging
919 #-------------------------------------------------------------------------
918 #-------------------------------------------------------------------------
920
919
921 def init_pdb(self):
920 def init_pdb(self):
922 # Set calling of pdb on exceptions
921 # Set calling of pdb on exceptions
923 # self.call_pdb is a property
922 # self.call_pdb is a property
924 self.call_pdb = self.pdb
923 self.call_pdb = self.pdb
925
924
926 def _get_call_pdb(self):
925 def _get_call_pdb(self):
927 return self._call_pdb
926 return self._call_pdb
928
927
929 def _set_call_pdb(self,val):
928 def _set_call_pdb(self,val):
930
929
931 if val not in (0,1,False,True):
930 if val not in (0,1,False,True):
932 raise ValueError('new call_pdb value must be boolean')
931 raise ValueError('new call_pdb value must be boolean')
933
932
934 # store value in instance
933 # store value in instance
935 self._call_pdb = val
934 self._call_pdb = val
936
935
937 # notify the actual exception handlers
936 # notify the actual exception handlers
938 self.InteractiveTB.call_pdb = val
937 self.InteractiveTB.call_pdb = val
939
938
940 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
939 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
941 'Control auto-activation of pdb at exceptions')
940 'Control auto-activation of pdb at exceptions')
942
941
943 def debugger(self,force=False):
942 def debugger(self,force=False):
944 """Call the pdb debugger.
943 """Call the pdb debugger.
945
944
946 Keywords:
945 Keywords:
947
946
948 - force(False): by default, this routine checks the instance call_pdb
947 - force(False): by default, this routine checks the instance call_pdb
949 flag and does not actually invoke the debugger if the flag is false.
948 flag and does not actually invoke the debugger if the flag is false.
950 The 'force' option forces the debugger to activate even if the flag
949 The 'force' option forces the debugger to activate even if the flag
951 is false.
950 is false.
952 """
951 """
953
952
954 if not (force or self.call_pdb):
953 if not (force or self.call_pdb):
955 return
954 return
956
955
957 if not hasattr(sys,'last_traceback'):
956 if not hasattr(sys,'last_traceback'):
958 error('No traceback has been produced, nothing to debug.')
957 error('No traceback has been produced, nothing to debug.')
959 return
958 return
960
959
961 self.InteractiveTB.debugger(force=True)
960 self.InteractiveTB.debugger(force=True)
962
961
963 #-------------------------------------------------------------------------
962 #-------------------------------------------------------------------------
964 # Things related to IPython's various namespaces
963 # Things related to IPython's various namespaces
965 #-------------------------------------------------------------------------
964 #-------------------------------------------------------------------------
966 default_user_namespaces = True
965 default_user_namespaces = True
967
966
968 def init_create_namespaces(self, user_module=None, user_ns=None):
967 def init_create_namespaces(self, user_module=None, user_ns=None):
969 # Create the namespace where the user will operate. user_ns is
968 # Create the namespace where the user will operate. user_ns is
970 # normally the only one used, and it is passed to the exec calls as
969 # normally the only one used, and it is passed to the exec calls as
971 # the locals argument. But we do carry a user_global_ns namespace
970 # the locals argument. But we do carry a user_global_ns namespace
972 # given as the exec 'globals' argument, This is useful in embedding
971 # given as the exec 'globals' argument, This is useful in embedding
973 # situations where the ipython shell opens in a context where the
972 # situations where the ipython shell opens in a context where the
974 # distinction between locals and globals is meaningful. For
973 # distinction between locals and globals is meaningful. For
975 # non-embedded contexts, it is just the same object as the user_ns dict.
974 # non-embedded contexts, it is just the same object as the user_ns dict.
976
975
977 # FIXME. For some strange reason, __builtins__ is showing up at user
976 # FIXME. For some strange reason, __builtins__ is showing up at user
978 # level as a dict instead of a module. This is a manual fix, but I
977 # level as a dict instead of a module. This is a manual fix, but I
979 # should really track down where the problem is coming from. Alex
978 # should really track down where the problem is coming from. Alex
980 # Schmolck reported this problem first.
979 # Schmolck reported this problem first.
981
980
982 # A useful post by Alex Martelli on this topic:
981 # A useful post by Alex Martelli on this topic:
983 # Re: inconsistent value from __builtins__
982 # Re: inconsistent value from __builtins__
984 # Von: Alex Martelli <aleaxit@yahoo.com>
983 # Von: Alex Martelli <aleaxit@yahoo.com>
985 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
984 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
986 # Gruppen: comp.lang.python
985 # Gruppen: comp.lang.python
987
986
988 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
987 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
989 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
988 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
990 # > <type 'dict'>
989 # > <type 'dict'>
991 # > >>> print type(__builtins__)
990 # > >>> print type(__builtins__)
992 # > <type 'module'>
991 # > <type 'module'>
993 # > Is this difference in return value intentional?
992 # > Is this difference in return value intentional?
994
993
995 # Well, it's documented that '__builtins__' can be either a dictionary
994 # Well, it's documented that '__builtins__' can be either a dictionary
996 # or a module, and it's been that way for a long time. Whether it's
995 # or a module, and it's been that way for a long time. Whether it's
997 # intentional (or sensible), I don't know. In any case, the idea is
996 # intentional (or sensible), I don't know. In any case, the idea is
998 # that if you need to access the built-in namespace directly, you
997 # that if you need to access the built-in namespace directly, you
999 # should start with "import __builtin__" (note, no 's') which will
998 # should start with "import __builtin__" (note, no 's') which will
1000 # definitely give you a module. Yeah, it's somewhat confusing:-(.
999 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1001
1000
1002 # These routines return a properly built module and dict as needed by
1001 # These routines return a properly built module and dict as needed by
1003 # the rest of the code, and can also be used by extension writers to
1002 # the rest of the code, and can also be used by extension writers to
1004 # generate properly initialized namespaces.
1003 # generate properly initialized namespaces.
1005 if (user_ns is not None) or (user_module is not None):
1004 if (user_ns is not None) or (user_module is not None):
1006 self.default_user_namespaces = False
1005 self.default_user_namespaces = False
1007 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1006 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1008
1007
1009 # A record of hidden variables we have added to the user namespace, so
1008 # A record of hidden variables we have added to the user namespace, so
1010 # we can list later only variables defined in actual interactive use.
1009 # we can list later only variables defined in actual interactive use.
1011 self.user_ns_hidden = {}
1010 self.user_ns_hidden = {}
1012
1011
1013 # Now that FakeModule produces a real module, we've run into a nasty
1012 # Now that FakeModule produces a real module, we've run into a nasty
1014 # problem: after script execution (via %run), the module where the user
1013 # problem: after script execution (via %run), the module where the user
1015 # code ran is deleted. Now that this object is a true module (needed
1014 # code ran is deleted. Now that this object is a true module (needed
1016 # so doctest and other tools work correctly), the Python module
1015 # so doctest and other tools work correctly), the Python module
1017 # teardown mechanism runs over it, and sets to None every variable
1016 # teardown mechanism runs over it, and sets to None every variable
1018 # present in that module. Top-level references to objects from the
1017 # present in that module. Top-level references to objects from the
1019 # script survive, because the user_ns is updated with them. However,
1018 # script survive, because the user_ns is updated with them. However,
1020 # calling functions defined in the script that use other things from
1019 # calling functions defined in the script that use other things from
1021 # the script will fail, because the function's closure had references
1020 # the script will fail, because the function's closure had references
1022 # to the original objects, which are now all None. So we must protect
1021 # to the original objects, which are now all None. So we must protect
1023 # these modules from deletion by keeping a cache.
1022 # these modules from deletion by keeping a cache.
1024 #
1023 #
1025 # To avoid keeping stale modules around (we only need the one from the
1024 # To avoid keeping stale modules around (we only need the one from the
1026 # last run), we use a dict keyed with the full path to the script, so
1025 # last run), we use a dict keyed with the full path to the script, so
1027 # only the last version of the module is held in the cache. Note,
1026 # only the last version of the module is held in the cache. Note,
1028 # however, that we must cache the module *namespace contents* (their
1027 # however, that we must cache the module *namespace contents* (their
1029 # __dict__). Because if we try to cache the actual modules, old ones
1028 # __dict__). Because if we try to cache the actual modules, old ones
1030 # (uncached) could be destroyed while still holding references (such as
1029 # (uncached) could be destroyed while still holding references (such as
1031 # those held by GUI objects that tend to be long-lived)>
1030 # those held by GUI objects that tend to be long-lived)>
1032 #
1031 #
1033 # The %reset command will flush this cache. See the cache_main_mod()
1032 # The %reset command will flush this cache. See the cache_main_mod()
1034 # and clear_main_mod_cache() methods for details on use.
1033 # and clear_main_mod_cache() methods for details on use.
1035
1034
1036 # This is the cache used for 'main' namespaces
1035 # This is the cache used for 'main' namespaces
1037 self._main_mod_cache = {}
1036 self._main_mod_cache = {}
1038
1037
1039 # A table holding all the namespaces IPython deals with, so that
1038 # A table holding all the namespaces IPython deals with, so that
1040 # introspection facilities can search easily.
1039 # introspection facilities can search easily.
1041 self.ns_table = {'user_global':self.user_module.__dict__,
1040 self.ns_table = {'user_global':self.user_module.__dict__,
1042 'user_local':self.user_ns,
1041 'user_local':self.user_ns,
1043 'builtin':builtin_mod.__dict__
1042 'builtin':builtin_mod.__dict__
1044 }
1043 }
1045
1044
1046 @property
1045 @property
1047 def user_global_ns(self):
1046 def user_global_ns(self):
1048 return self.user_module.__dict__
1047 return self.user_module.__dict__
1049
1048
1050 def prepare_user_module(self, user_module=None, user_ns=None):
1049 def prepare_user_module(self, user_module=None, user_ns=None):
1051 """Prepare the module and namespace in which user code will be run.
1050 """Prepare the module and namespace in which user code will be run.
1052
1051
1053 When IPython is started normally, both parameters are None: a new module
1052 When IPython is started normally, both parameters are None: a new module
1054 is created automatically, and its __dict__ used as the namespace.
1053 is created automatically, and its __dict__ used as the namespace.
1055
1054
1056 If only user_module is provided, its __dict__ is used as the namespace.
1055 If only user_module is provided, its __dict__ is used as the namespace.
1057 If only user_ns is provided, a dummy module is created, and user_ns
1056 If only user_ns is provided, a dummy module is created, and user_ns
1058 becomes the global namespace. If both are provided (as they may be
1057 becomes the global namespace. If both are provided (as they may be
1059 when embedding), user_ns is the local namespace, and user_module
1058 when embedding), user_ns is the local namespace, and user_module
1060 provides the global namespace.
1059 provides the global namespace.
1061
1060
1062 Parameters
1061 Parameters
1063 ----------
1062 ----------
1064 user_module : module, optional
1063 user_module : module, optional
1065 The current user module in which IPython is being run. If None,
1064 The current user module in which IPython is being run. If None,
1066 a clean module will be created.
1065 a clean module will be created.
1067 user_ns : dict, optional
1066 user_ns : dict, optional
1068 A namespace in which to run interactive commands.
1067 A namespace in which to run interactive commands.
1069
1068
1070 Returns
1069 Returns
1071 -------
1070 -------
1072 A tuple of user_module and user_ns, each properly initialised.
1071 A tuple of user_module and user_ns, each properly initialised.
1073 """
1072 """
1074 if user_module is None and user_ns is not None:
1073 if user_module is None and user_ns is not None:
1075 user_ns.setdefault("__name__", "__main__")
1074 user_ns.setdefault("__name__", "__main__")
1076 user_module = DummyMod()
1075 user_module = DummyMod()
1077 user_module.__dict__ = user_ns
1076 user_module.__dict__ = user_ns
1078
1077
1079 if user_module is None:
1078 if user_module is None:
1080 user_module = types.ModuleType("__main__",
1079 user_module = types.ModuleType("__main__",
1081 doc="Automatically created module for IPython interactive environment")
1080 doc="Automatically created module for IPython interactive environment")
1082
1081
1083 # We must ensure that __builtin__ (without the final 's') is always
1082 # We must ensure that __builtin__ (without the final 's') is always
1084 # available and pointing to the __builtin__ *module*. For more details:
1083 # available and pointing to the __builtin__ *module*. For more details:
1085 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1084 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1086 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1085 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1087 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1086 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1088
1087
1089 if user_ns is None:
1088 if user_ns is None:
1090 user_ns = user_module.__dict__
1089 user_ns = user_module.__dict__
1091
1090
1092 return user_module, user_ns
1091 return user_module, user_ns
1093
1092
1094 def init_sys_modules(self):
1093 def init_sys_modules(self):
1095 # We need to insert into sys.modules something that looks like a
1094 # We need to insert into sys.modules something that looks like a
1096 # module but which accesses the IPython namespace, for shelve and
1095 # module but which accesses the IPython namespace, for shelve and
1097 # pickle to work interactively. Normally they rely on getting
1096 # pickle to work interactively. Normally they rely on getting
1098 # everything out of __main__, but for embedding purposes each IPython
1097 # everything out of __main__, but for embedding purposes each IPython
1099 # instance has its own private namespace, so we can't go shoving
1098 # instance has its own private namespace, so we can't go shoving
1100 # everything into __main__.
1099 # everything into __main__.
1101
1100
1102 # note, however, that we should only do this for non-embedded
1101 # note, however, that we should only do this for non-embedded
1103 # ipythons, which really mimic the __main__.__dict__ with their own
1102 # ipythons, which really mimic the __main__.__dict__ with their own
1104 # namespace. Embedded instances, on the other hand, should not do
1103 # namespace. Embedded instances, on the other hand, should not do
1105 # this because they need to manage the user local/global namespaces
1104 # this because they need to manage the user local/global namespaces
1106 # only, but they live within a 'normal' __main__ (meaning, they
1105 # only, but they live within a 'normal' __main__ (meaning, they
1107 # shouldn't overtake the execution environment of the script they're
1106 # shouldn't overtake the execution environment of the script they're
1108 # embedded in).
1107 # embedded in).
1109
1108
1110 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1109 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1111 main_name = self.user_module.__name__
1110 main_name = self.user_module.__name__
1112 sys.modules[main_name] = self.user_module
1111 sys.modules[main_name] = self.user_module
1113
1112
1114 def init_user_ns(self):
1113 def init_user_ns(self):
1115 """Initialize all user-visible namespaces to their minimum defaults.
1114 """Initialize all user-visible namespaces to their minimum defaults.
1116
1115
1117 Certain history lists are also initialized here, as they effectively
1116 Certain history lists are also initialized here, as they effectively
1118 act as user namespaces.
1117 act as user namespaces.
1119
1118
1120 Notes
1119 Notes
1121 -----
1120 -----
1122 All data structures here are only filled in, they are NOT reset by this
1121 All data structures here are only filled in, they are NOT reset by this
1123 method. If they were not empty before, data will simply be added to
1122 method. If they were not empty before, data will simply be added to
1124 therm.
1123 therm.
1125 """
1124 """
1126 # This function works in two parts: first we put a few things in
1125 # This function works in two parts: first we put a few things in
1127 # user_ns, and we sync that contents into user_ns_hidden so that these
1126 # user_ns, and we sync that contents into user_ns_hidden so that these
1128 # initial variables aren't shown by %who. After the sync, we add the
1127 # initial variables aren't shown by %who. After the sync, we add the
1129 # rest of what we *do* want the user to see with %who even on a new
1128 # rest of what we *do* want the user to see with %who even on a new
1130 # session (probably nothing, so they really only see their own stuff)
1129 # session (probably nothing, so they really only see their own stuff)
1131
1130
1132 # The user dict must *always* have a __builtin__ reference to the
1131 # The user dict must *always* have a __builtin__ reference to the
1133 # Python standard __builtin__ namespace, which must be imported.
1132 # Python standard __builtin__ namespace, which must be imported.
1134 # This is so that certain operations in prompt evaluation can be
1133 # This is so that certain operations in prompt evaluation can be
1135 # reliably executed with builtins. Note that we can NOT use
1134 # reliably executed with builtins. Note that we can NOT use
1136 # __builtins__ (note the 's'), because that can either be a dict or a
1135 # __builtins__ (note the 's'), because that can either be a dict or a
1137 # module, and can even mutate at runtime, depending on the context
1136 # module, and can even mutate at runtime, depending on the context
1138 # (Python makes no guarantees on it). In contrast, __builtin__ is
1137 # (Python makes no guarantees on it). In contrast, __builtin__ is
1139 # always a module object, though it must be explicitly imported.
1138 # always a module object, though it must be explicitly imported.
1140
1139
1141 # For more details:
1140 # For more details:
1142 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1141 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1143 ns = dict()
1142 ns = dict()
1144
1143
1145 # make global variables for user access to the histories
1144 # make global variables for user access to the histories
1146 ns['_ih'] = self.history_manager.input_hist_parsed
1145 ns['_ih'] = self.history_manager.input_hist_parsed
1147 ns['_oh'] = self.history_manager.output_hist
1146 ns['_oh'] = self.history_manager.output_hist
1148 ns['_dh'] = self.history_manager.dir_hist
1147 ns['_dh'] = self.history_manager.dir_hist
1149
1148
1150 ns['_sh'] = shadowns
1149 ns['_sh'] = shadowns
1151
1150
1152 # user aliases to input and output histories. These shouldn't show up
1151 # user aliases to input and output histories. These shouldn't show up
1153 # in %who, as they can have very large reprs.
1152 # in %who, as they can have very large reprs.
1154 ns['In'] = self.history_manager.input_hist_parsed
1153 ns['In'] = self.history_manager.input_hist_parsed
1155 ns['Out'] = self.history_manager.output_hist
1154 ns['Out'] = self.history_manager.output_hist
1156
1155
1157 # Store myself as the public api!!!
1156 # Store myself as the public api!!!
1158 ns['get_ipython'] = self.get_ipython
1157 ns['get_ipython'] = self.get_ipython
1159
1158
1160 ns['exit'] = self.exiter
1159 ns['exit'] = self.exiter
1161 ns['quit'] = self.exiter
1160 ns['quit'] = self.exiter
1162
1161
1163 # Sync what we've added so far to user_ns_hidden so these aren't seen
1162 # Sync what we've added so far to user_ns_hidden so these aren't seen
1164 # by %who
1163 # by %who
1165 self.user_ns_hidden.update(ns)
1164 self.user_ns_hidden.update(ns)
1166
1165
1167 # Anything put into ns now would show up in %who. Think twice before
1166 # Anything put into ns now would show up in %who. Think twice before
1168 # putting anything here, as we really want %who to show the user their
1167 # putting anything here, as we really want %who to show the user their
1169 # stuff, not our variables.
1168 # stuff, not our variables.
1170
1169
1171 # Finally, update the real user's namespace
1170 # Finally, update the real user's namespace
1172 self.user_ns.update(ns)
1171 self.user_ns.update(ns)
1173
1172
1174 @property
1173 @property
1175 def all_ns_refs(self):
1174 def all_ns_refs(self):
1176 """Get a list of references to all the namespace dictionaries in which
1175 """Get a list of references to all the namespace dictionaries in which
1177 IPython might store a user-created object.
1176 IPython might store a user-created object.
1178
1177
1179 Note that this does not include the displayhook, which also caches
1178 Note that this does not include the displayhook, which also caches
1180 objects from the output."""
1179 objects from the output."""
1181 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1180 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1182 [m.__dict__ for m in self._main_mod_cache.values()]
1181 [m.__dict__ for m in self._main_mod_cache.values()]
1183
1182
1184 def reset(self, new_session=True):
1183 def reset(self, new_session=True):
1185 """Clear all internal namespaces, and attempt to release references to
1184 """Clear all internal namespaces, and attempt to release references to
1186 user objects.
1185 user objects.
1187
1186
1188 If new_session is True, a new history session will be opened.
1187 If new_session is True, a new history session will be opened.
1189 """
1188 """
1190 # Clear histories
1189 # Clear histories
1191 self.history_manager.reset(new_session)
1190 self.history_manager.reset(new_session)
1192 # Reset counter used to index all histories
1191 # Reset counter used to index all histories
1193 if new_session:
1192 if new_session:
1194 self.execution_count = 1
1193 self.execution_count = 1
1195
1194
1196 # Flush cached output items
1195 # Flush cached output items
1197 if self.displayhook.do_full_cache:
1196 if self.displayhook.do_full_cache:
1198 self.displayhook.flush()
1197 self.displayhook.flush()
1199
1198
1200 # The main execution namespaces must be cleared very carefully,
1199 # The main execution namespaces must be cleared very carefully,
1201 # skipping the deletion of the builtin-related keys, because doing so
1200 # skipping the deletion of the builtin-related keys, because doing so
1202 # would cause errors in many object's __del__ methods.
1201 # would cause errors in many object's __del__ methods.
1203 if self.user_ns is not self.user_global_ns:
1202 if self.user_ns is not self.user_global_ns:
1204 self.user_ns.clear()
1203 self.user_ns.clear()
1205 ns = self.user_global_ns
1204 ns = self.user_global_ns
1206 drop_keys = set(ns.keys())
1205 drop_keys = set(ns.keys())
1207 drop_keys.discard('__builtin__')
1206 drop_keys.discard('__builtin__')
1208 drop_keys.discard('__builtins__')
1207 drop_keys.discard('__builtins__')
1209 drop_keys.discard('__name__')
1208 drop_keys.discard('__name__')
1210 for k in drop_keys:
1209 for k in drop_keys:
1211 del ns[k]
1210 del ns[k]
1212
1211
1213 self.user_ns_hidden.clear()
1212 self.user_ns_hidden.clear()
1214
1213
1215 # Restore the user namespaces to minimal usability
1214 # Restore the user namespaces to minimal usability
1216 self.init_user_ns()
1215 self.init_user_ns()
1217
1216
1218 # Restore the default and user aliases
1217 # Restore the default and user aliases
1219 self.alias_manager.clear_aliases()
1218 self.alias_manager.clear_aliases()
1220 self.alias_manager.init_aliases()
1219 self.alias_manager.init_aliases()
1221
1220
1222 # Flush the private list of module references kept for script
1221 # Flush the private list of module references kept for script
1223 # execution protection
1222 # execution protection
1224 self.clear_main_mod_cache()
1223 self.clear_main_mod_cache()
1225
1224
1226 def del_var(self, varname, by_name=False):
1225 def del_var(self, varname, by_name=False):
1227 """Delete a variable from the various namespaces, so that, as
1226 """Delete a variable from the various namespaces, so that, as
1228 far as possible, we're not keeping any hidden references to it.
1227 far as possible, we're not keeping any hidden references to it.
1229
1228
1230 Parameters
1229 Parameters
1231 ----------
1230 ----------
1232 varname : str
1231 varname : str
1233 The name of the variable to delete.
1232 The name of the variable to delete.
1234 by_name : bool
1233 by_name : bool
1235 If True, delete variables with the given name in each
1234 If True, delete variables with the given name in each
1236 namespace. If False (default), find the variable in the user
1235 namespace. If False (default), find the variable in the user
1237 namespace, and delete references to it.
1236 namespace, and delete references to it.
1238 """
1237 """
1239 if varname in ('__builtin__', '__builtins__'):
1238 if varname in ('__builtin__', '__builtins__'):
1240 raise ValueError("Refusing to delete %s" % varname)
1239 raise ValueError("Refusing to delete %s" % varname)
1241
1240
1242 ns_refs = self.all_ns_refs
1241 ns_refs = self.all_ns_refs
1243
1242
1244 if by_name: # Delete by name
1243 if by_name: # Delete by name
1245 for ns in ns_refs:
1244 for ns in ns_refs:
1246 try:
1245 try:
1247 del ns[varname]
1246 del ns[varname]
1248 except KeyError:
1247 except KeyError:
1249 pass
1248 pass
1250 else: # Delete by object
1249 else: # Delete by object
1251 try:
1250 try:
1252 obj = self.user_ns[varname]
1251 obj = self.user_ns[varname]
1253 except KeyError:
1252 except KeyError:
1254 raise NameError("name '%s' is not defined" % varname)
1253 raise NameError("name '%s' is not defined" % varname)
1255 # Also check in output history
1254 # Also check in output history
1256 ns_refs.append(self.history_manager.output_hist)
1255 ns_refs.append(self.history_manager.output_hist)
1257 for ns in ns_refs:
1256 for ns in ns_refs:
1258 to_delete = [n for n, o in iteritems(ns) if o is obj]
1257 to_delete = [n for n, o in iteritems(ns) if o is obj]
1259 for name in to_delete:
1258 for name in to_delete:
1260 del ns[name]
1259 del ns[name]
1261
1260
1262 # displayhook keeps extra references, but not in a dictionary
1261 # displayhook keeps extra references, but not in a dictionary
1263 for name in ('_', '__', '___'):
1262 for name in ('_', '__', '___'):
1264 if getattr(self.displayhook, name) is obj:
1263 if getattr(self.displayhook, name) is obj:
1265 setattr(self.displayhook, name, None)
1264 setattr(self.displayhook, name, None)
1266
1265
1267 def reset_selective(self, regex=None):
1266 def reset_selective(self, regex=None):
1268 """Clear selective variables from internal namespaces based on a
1267 """Clear selective variables from internal namespaces based on a
1269 specified regular expression.
1268 specified regular expression.
1270
1269
1271 Parameters
1270 Parameters
1272 ----------
1271 ----------
1273 regex : string or compiled pattern, optional
1272 regex : string or compiled pattern, optional
1274 A regular expression pattern that will be used in searching
1273 A regular expression pattern that will be used in searching
1275 variable names in the users namespaces.
1274 variable names in the users namespaces.
1276 """
1275 """
1277 if regex is not None:
1276 if regex is not None:
1278 try:
1277 try:
1279 m = re.compile(regex)
1278 m = re.compile(regex)
1280 except TypeError:
1279 except TypeError:
1281 raise TypeError('regex must be a string or compiled pattern')
1280 raise TypeError('regex must be a string or compiled pattern')
1282 # Search for keys in each namespace that match the given regex
1281 # Search for keys in each namespace that match the given regex
1283 # If a match is found, delete the key/value pair.
1282 # If a match is found, delete the key/value pair.
1284 for ns in self.all_ns_refs:
1283 for ns in self.all_ns_refs:
1285 for var in ns:
1284 for var in ns:
1286 if m.search(var):
1285 if m.search(var):
1287 del ns[var]
1286 del ns[var]
1288
1287
1289 def push(self, variables, interactive=True):
1288 def push(self, variables, interactive=True):
1290 """Inject a group of variables into the IPython user namespace.
1289 """Inject a group of variables into the IPython user namespace.
1291
1290
1292 Parameters
1291 Parameters
1293 ----------
1292 ----------
1294 variables : dict, str or list/tuple of str
1293 variables : dict, str or list/tuple of str
1295 The variables to inject into the user's namespace. If a dict, a
1294 The variables to inject into the user's namespace. If a dict, a
1296 simple update is done. If a str, the string is assumed to have
1295 simple update is done. If a str, the string is assumed to have
1297 variable names separated by spaces. A list/tuple of str can also
1296 variable names separated by spaces. A list/tuple of str can also
1298 be used to give the variable names. If just the variable names are
1297 be used to give the variable names. If just the variable names are
1299 give (list/tuple/str) then the variable values looked up in the
1298 give (list/tuple/str) then the variable values looked up in the
1300 callers frame.
1299 callers frame.
1301 interactive : bool
1300 interactive : bool
1302 If True (default), the variables will be listed with the ``who``
1301 If True (default), the variables will be listed with the ``who``
1303 magic.
1302 magic.
1304 """
1303 """
1305 vdict = None
1304 vdict = None
1306
1305
1307 # We need a dict of name/value pairs to do namespace updates.
1306 # We need a dict of name/value pairs to do namespace updates.
1308 if isinstance(variables, dict):
1307 if isinstance(variables, dict):
1309 vdict = variables
1308 vdict = variables
1310 elif isinstance(variables, string_types+(list, tuple)):
1309 elif isinstance(variables, string_types+(list, tuple)):
1311 if isinstance(variables, string_types):
1310 if isinstance(variables, string_types):
1312 vlist = variables.split()
1311 vlist = variables.split()
1313 else:
1312 else:
1314 vlist = variables
1313 vlist = variables
1315 vdict = {}
1314 vdict = {}
1316 cf = sys._getframe(1)
1315 cf = sys._getframe(1)
1317 for name in vlist:
1316 for name in vlist:
1318 try:
1317 try:
1319 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1318 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1320 except:
1319 except:
1321 print('Could not get variable %s from %s' %
1320 print('Could not get variable %s from %s' %
1322 (name,cf.f_code.co_name))
1321 (name,cf.f_code.co_name))
1323 else:
1322 else:
1324 raise ValueError('variables must be a dict/str/list/tuple')
1323 raise ValueError('variables must be a dict/str/list/tuple')
1325
1324
1326 # Propagate variables to user namespace
1325 # Propagate variables to user namespace
1327 self.user_ns.update(vdict)
1326 self.user_ns.update(vdict)
1328
1327
1329 # And configure interactive visibility
1328 # And configure interactive visibility
1330 user_ns_hidden = self.user_ns_hidden
1329 user_ns_hidden = self.user_ns_hidden
1331 if interactive:
1330 if interactive:
1332 for name in vdict:
1331 for name in vdict:
1333 user_ns_hidden.pop(name, None)
1332 user_ns_hidden.pop(name, None)
1334 else:
1333 else:
1335 user_ns_hidden.update(vdict)
1334 user_ns_hidden.update(vdict)
1336
1335
1337 def drop_by_id(self, variables):
1336 def drop_by_id(self, variables):
1338 """Remove a dict of variables from the user namespace, if they are the
1337 """Remove a dict of variables from the user namespace, if they are the
1339 same as the values in the dictionary.
1338 same as the values in the dictionary.
1340
1339
1341 This is intended for use by extensions: variables that they've added can
1340 This is intended for use by extensions: variables that they've added can
1342 be taken back out if they are unloaded, without removing any that the
1341 be taken back out if they are unloaded, without removing any that the
1343 user has overwritten.
1342 user has overwritten.
1344
1343
1345 Parameters
1344 Parameters
1346 ----------
1345 ----------
1347 variables : dict
1346 variables : dict
1348 A dictionary mapping object names (as strings) to the objects.
1347 A dictionary mapping object names (as strings) to the objects.
1349 """
1348 """
1350 for name, obj in iteritems(variables):
1349 for name, obj in iteritems(variables):
1351 if name in self.user_ns and self.user_ns[name] is obj:
1350 if name in self.user_ns and self.user_ns[name] is obj:
1352 del self.user_ns[name]
1351 del self.user_ns[name]
1353 self.user_ns_hidden.pop(name, None)
1352 self.user_ns_hidden.pop(name, None)
1354
1353
1355 #-------------------------------------------------------------------------
1354 #-------------------------------------------------------------------------
1356 # Things related to object introspection
1355 # Things related to object introspection
1357 #-------------------------------------------------------------------------
1356 #-------------------------------------------------------------------------
1358
1357
1359 def _ofind(self, oname, namespaces=None):
1358 def _ofind(self, oname, namespaces=None):
1360 """Find an object in the available namespaces.
1359 """Find an object in the available namespaces.
1361
1360
1362 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1361 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1363
1362
1364 Has special code to detect magic functions.
1363 Has special code to detect magic functions.
1365 """
1364 """
1366 oname = oname.strip()
1365 oname = oname.strip()
1367 #print '1- oname: <%r>' % oname # dbg
1366 #print '1- oname: <%r>' % oname # dbg
1368 if not oname.startswith(ESC_MAGIC) and \
1367 if not oname.startswith(ESC_MAGIC) and \
1369 not oname.startswith(ESC_MAGIC2) and \
1368 not oname.startswith(ESC_MAGIC2) and \
1370 not py3compat.isidentifier(oname, dotted=True):
1369 not py3compat.isidentifier(oname, dotted=True):
1371 return dict(found=False)
1370 return dict(found=False)
1372
1371
1373 if namespaces is None:
1372 if namespaces is None:
1374 # Namespaces to search in:
1373 # Namespaces to search in:
1375 # Put them in a list. The order is important so that we
1374 # Put them in a list. The order is important so that we
1376 # find things in the same order that Python finds them.
1375 # find things in the same order that Python finds them.
1377 namespaces = [ ('Interactive', self.user_ns),
1376 namespaces = [ ('Interactive', self.user_ns),
1378 ('Interactive (global)', self.user_global_ns),
1377 ('Interactive (global)', self.user_global_ns),
1379 ('Python builtin', builtin_mod.__dict__),
1378 ('Python builtin', builtin_mod.__dict__),
1380 ]
1379 ]
1381
1380
1382 # initialize results to 'null'
1381 # initialize results to 'null'
1383 found = False; obj = None; ospace = None;
1382 found = False; obj = None; ospace = None;
1384 ismagic = False; isalias = False; parent = None
1383 ismagic = False; isalias = False; parent = None
1385
1384
1386 # We need to special-case 'print', which as of python2.6 registers as a
1385 # We need to special-case 'print', which as of python2.6 registers as a
1387 # function but should only be treated as one if print_function was
1386 # function but should only be treated as one if print_function was
1388 # loaded with a future import. In this case, just bail.
1387 # loaded with a future import. In this case, just bail.
1389 if (oname == 'print' and not py3compat.PY3 and not \
1388 if (oname == 'print' and not py3compat.PY3 and not \
1390 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1389 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1391 return {'found':found, 'obj':obj, 'namespace':ospace,
1390 return {'found':found, 'obj':obj, 'namespace':ospace,
1392 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1391 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1393
1392
1394 # Look for the given name by splitting it in parts. If the head is
1393 # Look for the given name by splitting it in parts. If the head is
1395 # found, then we look for all the remaining parts as members, and only
1394 # found, then we look for all the remaining parts as members, and only
1396 # declare success if we can find them all.
1395 # declare success if we can find them all.
1397 oname_parts = oname.split('.')
1396 oname_parts = oname.split('.')
1398 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1397 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1399 for nsname,ns in namespaces:
1398 for nsname,ns in namespaces:
1400 try:
1399 try:
1401 obj = ns[oname_head]
1400 obj = ns[oname_head]
1402 except KeyError:
1401 except KeyError:
1403 continue
1402 continue
1404 else:
1403 else:
1405 #print 'oname_rest:', oname_rest # dbg
1404 #print 'oname_rest:', oname_rest # dbg
1406 for idx, part in enumerate(oname_rest):
1405 for idx, part in enumerate(oname_rest):
1407 try:
1406 try:
1408 parent = obj
1407 parent = obj
1409 # The last part is looked up in a special way to avoid
1408 # The last part is looked up in a special way to avoid
1410 # descriptor invocation as it may raise or have side
1409 # descriptor invocation as it may raise or have side
1411 # effects.
1410 # effects.
1412 if idx == len(oname_rest) - 1:
1411 if idx == len(oname_rest) - 1:
1413 obj = self._getattr_property(obj, part)
1412 obj = self._getattr_property(obj, part)
1414 else:
1413 else:
1415 obj = getattr(obj, part)
1414 obj = getattr(obj, part)
1416 except:
1415 except:
1417 # Blanket except b/c some badly implemented objects
1416 # Blanket except b/c some badly implemented objects
1418 # allow __getattr__ to raise exceptions other than
1417 # allow __getattr__ to raise exceptions other than
1419 # AttributeError, which then crashes IPython.
1418 # AttributeError, which then crashes IPython.
1420 break
1419 break
1421 else:
1420 else:
1422 # If we finish the for loop (no break), we got all members
1421 # If we finish the for loop (no break), we got all members
1423 found = True
1422 found = True
1424 ospace = nsname
1423 ospace = nsname
1425 break # namespace loop
1424 break # namespace loop
1426
1425
1427 # Try to see if it's magic
1426 # Try to see if it's magic
1428 if not found:
1427 if not found:
1429 obj = None
1428 obj = None
1430 if oname.startswith(ESC_MAGIC2):
1429 if oname.startswith(ESC_MAGIC2):
1431 oname = oname.lstrip(ESC_MAGIC2)
1430 oname = oname.lstrip(ESC_MAGIC2)
1432 obj = self.find_cell_magic(oname)
1431 obj = self.find_cell_magic(oname)
1433 elif oname.startswith(ESC_MAGIC):
1432 elif oname.startswith(ESC_MAGIC):
1434 oname = oname.lstrip(ESC_MAGIC)
1433 oname = oname.lstrip(ESC_MAGIC)
1435 obj = self.find_line_magic(oname)
1434 obj = self.find_line_magic(oname)
1436 else:
1435 else:
1437 # search without prefix, so run? will find %run?
1436 # search without prefix, so run? will find %run?
1438 obj = self.find_line_magic(oname)
1437 obj = self.find_line_magic(oname)
1439 if obj is None:
1438 if obj is None:
1440 obj = self.find_cell_magic(oname)
1439 obj = self.find_cell_magic(oname)
1441 if obj is not None:
1440 if obj is not None:
1442 found = True
1441 found = True
1443 ospace = 'IPython internal'
1442 ospace = 'IPython internal'
1444 ismagic = True
1443 ismagic = True
1445 isalias = isinstance(obj, Alias)
1444 isalias = isinstance(obj, Alias)
1446
1445
1447 # Last try: special-case some literals like '', [], {}, etc:
1446 # Last try: special-case some literals like '', [], {}, etc:
1448 if not found and oname_head in ["''",'""','[]','{}','()']:
1447 if not found and oname_head in ["''",'""','[]','{}','()']:
1449 obj = eval(oname_head)
1448 obj = eval(oname_head)
1450 found = True
1449 found = True
1451 ospace = 'Interactive'
1450 ospace = 'Interactive'
1452
1451
1453 return {'found':found, 'obj':obj, 'namespace':ospace,
1452 return {'found':found, 'obj':obj, 'namespace':ospace,
1454 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1453 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1455
1454
1456 @staticmethod
1455 @staticmethod
1457 def _getattr_property(obj, attrname):
1456 def _getattr_property(obj, attrname):
1458 """Property-aware getattr to use in object finding.
1457 """Property-aware getattr to use in object finding.
1459
1458
1460 If attrname represents a property, return it unevaluated (in case it has
1459 If attrname represents a property, return it unevaluated (in case it has
1461 side effects or raises an error.
1460 side effects or raises an error.
1462
1461
1463 """
1462 """
1464 if not isinstance(obj, type):
1463 if not isinstance(obj, type):
1465 try:
1464 try:
1466 # `getattr(type(obj), attrname)` is not guaranteed to return
1465 # `getattr(type(obj), attrname)` is not guaranteed to return
1467 # `obj`, but does so for property:
1466 # `obj`, but does so for property:
1468 #
1467 #
1469 # property.__get__(self, None, cls) -> self
1468 # property.__get__(self, None, cls) -> self
1470 #
1469 #
1471 # The universal alternative is to traverse the mro manually
1470 # The universal alternative is to traverse the mro manually
1472 # searching for attrname in class dicts.
1471 # searching for attrname in class dicts.
1473 attr = getattr(type(obj), attrname)
1472 attr = getattr(type(obj), attrname)
1474 except AttributeError:
1473 except AttributeError:
1475 pass
1474 pass
1476 else:
1475 else:
1477 # This relies on the fact that data descriptors (with both
1476 # This relies on the fact that data descriptors (with both
1478 # __get__ & __set__ magic methods) take precedence over
1477 # __get__ & __set__ magic methods) take precedence over
1479 # instance-level attributes:
1478 # instance-level attributes:
1480 #
1479 #
1481 # class A(object):
1480 # class A(object):
1482 # @property
1481 # @property
1483 # def foobar(self): return 123
1482 # def foobar(self): return 123
1484 # a = A()
1483 # a = A()
1485 # a.__dict__['foobar'] = 345
1484 # a.__dict__['foobar'] = 345
1486 # a.foobar # == 123
1485 # a.foobar # == 123
1487 #
1486 #
1488 # So, a property may be returned right away.
1487 # So, a property may be returned right away.
1489 if isinstance(attr, property):
1488 if isinstance(attr, property):
1490 return attr
1489 return attr
1491
1490
1492 # Nothing helped, fall back.
1491 # Nothing helped, fall back.
1493 return getattr(obj, attrname)
1492 return getattr(obj, attrname)
1494
1493
1495 def _object_find(self, oname, namespaces=None):
1494 def _object_find(self, oname, namespaces=None):
1496 """Find an object and return a struct with info about it."""
1495 """Find an object and return a struct with info about it."""
1497 return Struct(self._ofind(oname, namespaces))
1496 return Struct(self._ofind(oname, namespaces))
1498
1497
1499 def _inspect(self, meth, oname, namespaces=None, **kw):
1498 def _inspect(self, meth, oname, namespaces=None, **kw):
1500 """Generic interface to the inspector system.
1499 """Generic interface to the inspector system.
1501
1500
1502 This function is meant to be called by pdef, pdoc & friends.
1501 This function is meant to be called by pdef, pdoc & friends.
1503 """
1502 """
1504 info = self._object_find(oname, namespaces)
1503 info = self._object_find(oname, namespaces)
1505 docformat = sphinxify if self.sphinxify_docstring else None
1504 docformat = sphinxify if self.sphinxify_docstring else None
1506 if info.found:
1505 if info.found:
1507 pmethod = getattr(self.inspector, meth)
1506 pmethod = getattr(self.inspector, meth)
1508 # TODO: only apply format_screen to the plain/text repr of the mime
1507 # TODO: only apply format_screen to the plain/text repr of the mime
1509 # bundle.
1508 # bundle.
1510 formatter = format_screen if info.ismagic else docformat
1509 formatter = format_screen if info.ismagic else docformat
1511 if meth == 'pdoc':
1510 if meth == 'pdoc':
1512 pmethod(info.obj, oname, formatter)
1511 pmethod(info.obj, oname, formatter)
1513 elif meth == 'pinfo':
1512 elif meth == 'pinfo':
1514 pmethod(info.obj, oname, formatter, info,
1513 pmethod(info.obj, oname, formatter, info,
1515 enable_html_pager=self.enable_html_pager, **kw)
1514 enable_html_pager=self.enable_html_pager, **kw)
1516 else:
1515 else:
1517 pmethod(info.obj, oname)
1516 pmethod(info.obj, oname)
1518 else:
1517 else:
1519 print('Object `%s` not found.' % oname)
1518 print('Object `%s` not found.' % oname)
1520 return 'not found' # so callers can take other action
1519 return 'not found' # so callers can take other action
1521
1520
1522 def object_inspect(self, oname, detail_level=0):
1521 def object_inspect(self, oname, detail_level=0):
1523 """Get object info about oname"""
1522 """Get object info about oname"""
1524 with self.builtin_trap:
1523 with self.builtin_trap:
1525 info = self._object_find(oname)
1524 info = self._object_find(oname)
1526 if info.found:
1525 if info.found:
1527 return self.inspector.info(info.obj, oname, info=info,
1526 return self.inspector.info(info.obj, oname, info=info,
1528 detail_level=detail_level
1527 detail_level=detail_level
1529 )
1528 )
1530 else:
1529 else:
1531 return oinspect.object_info(name=oname, found=False)
1530 return oinspect.object_info(name=oname, found=False)
1532
1531
1533 def object_inspect_text(self, oname, detail_level=0):
1532 def object_inspect_text(self, oname, detail_level=0):
1534 """Get object info as formatted text"""
1533 """Get object info as formatted text"""
1535 return self.object_inspect_mime(oname, detail_level)['text/plain']
1534 return self.object_inspect_mime(oname, detail_level)['text/plain']
1536
1535
1537 def object_inspect_mime(self, oname, detail_level=0):
1536 def object_inspect_mime(self, oname, detail_level=0):
1538 """Get object info as a mimebundle of formatted representations.
1537 """Get object info as a mimebundle of formatted representations.
1539
1538
1540 A mimebundle is a dictionary, keyed by mime-type.
1539 A mimebundle is a dictionary, keyed by mime-type.
1541 It must always have the key `'text/plain'`.
1540 It must always have the key `'text/plain'`.
1542 """
1541 """
1543 with self.builtin_trap:
1542 with self.builtin_trap:
1544 info = self._object_find(oname)
1543 info = self._object_find(oname)
1545 if info.found:
1544 if info.found:
1546 return self.inspector._get_info(info.obj, oname, info=info,
1545 return self.inspector._get_info(info.obj, oname, info=info,
1547 detail_level=detail_level
1546 detail_level=detail_level
1548 )
1547 )
1549 else:
1548 else:
1550 raise KeyError(oname)
1549 raise KeyError(oname)
1551
1550
1552 #-------------------------------------------------------------------------
1551 #-------------------------------------------------------------------------
1553 # Things related to history management
1552 # Things related to history management
1554 #-------------------------------------------------------------------------
1553 #-------------------------------------------------------------------------
1555
1554
1556 def init_history(self):
1555 def init_history(self):
1557 """Sets up the command history, and starts regular autosaves."""
1556 """Sets up the command history, and starts regular autosaves."""
1558 self.history_manager = HistoryManager(shell=self, parent=self)
1557 self.history_manager = HistoryManager(shell=self, parent=self)
1559 self.configurables.append(self.history_manager)
1558 self.configurables.append(self.history_manager)
1560
1559
1561 #-------------------------------------------------------------------------
1560 #-------------------------------------------------------------------------
1562 # Things related to exception handling and tracebacks (not debugging)
1561 # Things related to exception handling and tracebacks (not debugging)
1563 #-------------------------------------------------------------------------
1562 #-------------------------------------------------------------------------
1564
1563
1565 debugger_cls = Pdb
1564 debugger_cls = Pdb
1566
1565
1567 def init_traceback_handlers(self, custom_exceptions):
1566 def init_traceback_handlers(self, custom_exceptions):
1568 # Syntax error handler.
1567 # Syntax error handler.
1569 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1568 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1570
1569
1571 # The interactive one is initialized with an offset, meaning we always
1570 # The interactive one is initialized with an offset, meaning we always
1572 # want to remove the topmost item in the traceback, which is our own
1571 # want to remove the topmost item in the traceback, which is our own
1573 # internal code. Valid modes: ['Plain','Context','Verbose']
1572 # internal code. Valid modes: ['Plain','Context','Verbose']
1574 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1573 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1575 color_scheme='NoColor',
1574 color_scheme='NoColor',
1576 tb_offset = 1,
1575 tb_offset = 1,
1577 check_cache=check_linecache_ipython,
1576 check_cache=check_linecache_ipython,
1578 debugger_cls=self.debugger_cls, parent=self)
1577 debugger_cls=self.debugger_cls, parent=self)
1579
1578
1580 # The instance will store a pointer to the system-wide exception hook,
1579 # The instance will store a pointer to the system-wide exception hook,
1581 # so that runtime code (such as magics) can access it. This is because
1580 # so that runtime code (such as magics) can access it. This is because
1582 # during the read-eval loop, it may get temporarily overwritten.
1581 # during the read-eval loop, it may get temporarily overwritten.
1583 self.sys_excepthook = sys.excepthook
1582 self.sys_excepthook = sys.excepthook
1584
1583
1585 # and add any custom exception handlers the user may have specified
1584 # and add any custom exception handlers the user may have specified
1586 self.set_custom_exc(*custom_exceptions)
1585 self.set_custom_exc(*custom_exceptions)
1587
1586
1588 # Set the exception mode
1587 # Set the exception mode
1589 self.InteractiveTB.set_mode(mode=self.xmode)
1588 self.InteractiveTB.set_mode(mode=self.xmode)
1590
1589
1591 def set_custom_exc(self, exc_tuple, handler):
1590 def set_custom_exc(self, exc_tuple, handler):
1592 """set_custom_exc(exc_tuple, handler)
1591 """set_custom_exc(exc_tuple, handler)
1593
1592
1594 Set a custom exception handler, which will be called if any of the
1593 Set a custom exception handler, which will be called if any of the
1595 exceptions in exc_tuple occur in the mainloop (specifically, in the
1594 exceptions in exc_tuple occur in the mainloop (specifically, in the
1596 run_code() method).
1595 run_code() method).
1597
1596
1598 Parameters
1597 Parameters
1599 ----------
1598 ----------
1600
1599
1601 exc_tuple : tuple of exception classes
1600 exc_tuple : tuple of exception classes
1602 A *tuple* of exception classes, for which to call the defined
1601 A *tuple* of exception classes, for which to call the defined
1603 handler. It is very important that you use a tuple, and NOT A
1602 handler. It is very important that you use a tuple, and NOT A
1604 LIST here, because of the way Python's except statement works. If
1603 LIST here, because of the way Python's except statement works. If
1605 you only want to trap a single exception, use a singleton tuple::
1604 you only want to trap a single exception, use a singleton tuple::
1606
1605
1607 exc_tuple == (MyCustomException,)
1606 exc_tuple == (MyCustomException,)
1608
1607
1609 handler : callable
1608 handler : callable
1610 handler must have the following signature::
1609 handler must have the following signature::
1611
1610
1612 def my_handler(self, etype, value, tb, tb_offset=None):
1611 def my_handler(self, etype, value, tb, tb_offset=None):
1613 ...
1612 ...
1614 return structured_traceback
1613 return structured_traceback
1615
1614
1616 Your handler must return a structured traceback (a list of strings),
1615 Your handler must return a structured traceback (a list of strings),
1617 or None.
1616 or None.
1618
1617
1619 This will be made into an instance method (via types.MethodType)
1618 This will be made into an instance method (via types.MethodType)
1620 of IPython itself, and it will be called if any of the exceptions
1619 of IPython itself, and it will be called if any of the exceptions
1621 listed in the exc_tuple are caught. If the handler is None, an
1620 listed in the exc_tuple are caught. If the handler is None, an
1622 internal basic one is used, which just prints basic info.
1621 internal basic one is used, which just prints basic info.
1623
1622
1624 To protect IPython from crashes, if your handler ever raises an
1623 To protect IPython from crashes, if your handler ever raises an
1625 exception or returns an invalid result, it will be immediately
1624 exception or returns an invalid result, it will be immediately
1626 disabled.
1625 disabled.
1627
1626
1628 WARNING: by putting in your own exception handler into IPython's main
1627 WARNING: by putting in your own exception handler into IPython's main
1629 execution loop, you run a very good chance of nasty crashes. This
1628 execution loop, you run a very good chance of nasty crashes. This
1630 facility should only be used if you really know what you are doing."""
1629 facility should only be used if you really know what you are doing."""
1631
1630
1632 assert type(exc_tuple)==type(()) , \
1631 assert type(exc_tuple)==type(()) , \
1633 "The custom exceptions must be given AS A TUPLE."
1632 "The custom exceptions must be given AS A TUPLE."
1634
1633
1635 def dummy_handler(self, etype, value, tb, tb_offset=None):
1634 def dummy_handler(self, etype, value, tb, tb_offset=None):
1636 print('*** Simple custom exception handler ***')
1635 print('*** Simple custom exception handler ***')
1637 print('Exception type :',etype)
1636 print('Exception type :',etype)
1638 print('Exception value:',value)
1637 print('Exception value:',value)
1639 print('Traceback :',tb)
1638 print('Traceback :',tb)
1640 #print 'Source code :','\n'.join(self.buffer)
1639 #print 'Source code :','\n'.join(self.buffer)
1641
1640
1642 def validate_stb(stb):
1641 def validate_stb(stb):
1643 """validate structured traceback return type
1642 """validate structured traceback return type
1644
1643
1645 return type of CustomTB *should* be a list of strings, but allow
1644 return type of CustomTB *should* be a list of strings, but allow
1646 single strings or None, which are harmless.
1645 single strings or None, which are harmless.
1647
1646
1648 This function will *always* return a list of strings,
1647 This function will *always* return a list of strings,
1649 and will raise a TypeError if stb is inappropriate.
1648 and will raise a TypeError if stb is inappropriate.
1650 """
1649 """
1651 msg = "CustomTB must return list of strings, not %r" % stb
1650 msg = "CustomTB must return list of strings, not %r" % stb
1652 if stb is None:
1651 if stb is None:
1653 return []
1652 return []
1654 elif isinstance(stb, string_types):
1653 elif isinstance(stb, string_types):
1655 return [stb]
1654 return [stb]
1656 elif not isinstance(stb, list):
1655 elif not isinstance(stb, list):
1657 raise TypeError(msg)
1656 raise TypeError(msg)
1658 # it's a list
1657 # it's a list
1659 for line in stb:
1658 for line in stb:
1660 # check every element
1659 # check every element
1661 if not isinstance(line, string_types):
1660 if not isinstance(line, string_types):
1662 raise TypeError(msg)
1661 raise TypeError(msg)
1663 return stb
1662 return stb
1664
1663
1665 if handler is None:
1664 if handler is None:
1666 wrapped = dummy_handler
1665 wrapped = dummy_handler
1667 else:
1666 else:
1668 def wrapped(self,etype,value,tb,tb_offset=None):
1667 def wrapped(self,etype,value,tb,tb_offset=None):
1669 """wrap CustomTB handler, to protect IPython from user code
1668 """wrap CustomTB handler, to protect IPython from user code
1670
1669
1671 This makes it harder (but not impossible) for custom exception
1670 This makes it harder (but not impossible) for custom exception
1672 handlers to crash IPython.
1671 handlers to crash IPython.
1673 """
1672 """
1674 try:
1673 try:
1675 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1674 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1676 return validate_stb(stb)
1675 return validate_stb(stb)
1677 except:
1676 except:
1678 # clear custom handler immediately
1677 # clear custom handler immediately
1679 self.set_custom_exc((), None)
1678 self.set_custom_exc((), None)
1680 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1679 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1681 # show the exception in handler first
1680 # show the exception in handler first
1682 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1681 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1683 print(self.InteractiveTB.stb2text(stb))
1682 print(self.InteractiveTB.stb2text(stb))
1684 print("The original exception:")
1683 print("The original exception:")
1685 stb = self.InteractiveTB.structured_traceback(
1684 stb = self.InteractiveTB.structured_traceback(
1686 (etype,value,tb), tb_offset=tb_offset
1685 (etype,value,tb), tb_offset=tb_offset
1687 )
1686 )
1688 return stb
1687 return stb
1689
1688
1690 self.CustomTB = types.MethodType(wrapped,self)
1689 self.CustomTB = types.MethodType(wrapped,self)
1691 self.custom_exceptions = exc_tuple
1690 self.custom_exceptions = exc_tuple
1692
1691
1693 def excepthook(self, etype, value, tb):
1692 def excepthook(self, etype, value, tb):
1694 """One more defense for GUI apps that call sys.excepthook.
1693 """One more defense for GUI apps that call sys.excepthook.
1695
1694
1696 GUI frameworks like wxPython trap exceptions and call
1695 GUI frameworks like wxPython trap exceptions and call
1697 sys.excepthook themselves. I guess this is a feature that
1696 sys.excepthook themselves. I guess this is a feature that
1698 enables them to keep running after exceptions that would
1697 enables them to keep running after exceptions that would
1699 otherwise kill their mainloop. This is a bother for IPython
1698 otherwise kill their mainloop. This is a bother for IPython
1700 which excepts to catch all of the program exceptions with a try:
1699 which excepts to catch all of the program exceptions with a try:
1701 except: statement.
1700 except: statement.
1702
1701
1703 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1702 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1704 any app directly invokes sys.excepthook, it will look to the user like
1703 any app directly invokes sys.excepthook, it will look to the user like
1705 IPython crashed. In order to work around this, we can disable the
1704 IPython crashed. In order to work around this, we can disable the
1706 CrashHandler and replace it with this excepthook instead, which prints a
1705 CrashHandler and replace it with this excepthook instead, which prints a
1707 regular traceback using our InteractiveTB. In this fashion, apps which
1706 regular traceback using our InteractiveTB. In this fashion, apps which
1708 call sys.excepthook will generate a regular-looking exception from
1707 call sys.excepthook will generate a regular-looking exception from
1709 IPython, and the CrashHandler will only be triggered by real IPython
1708 IPython, and the CrashHandler will only be triggered by real IPython
1710 crashes.
1709 crashes.
1711
1710
1712 This hook should be used sparingly, only in places which are not likely
1711 This hook should be used sparingly, only in places which are not likely
1713 to be true IPython errors.
1712 to be true IPython errors.
1714 """
1713 """
1715 self.showtraceback((etype, value, tb), tb_offset=0)
1714 self.showtraceback((etype, value, tb), tb_offset=0)
1716
1715
1717 def _get_exc_info(self, exc_tuple=None):
1716 def _get_exc_info(self, exc_tuple=None):
1718 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1717 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1719
1718
1720 Ensures sys.last_type,value,traceback hold the exc_info we found,
1719 Ensures sys.last_type,value,traceback hold the exc_info we found,
1721 from whichever source.
1720 from whichever source.
1722
1721
1723 raises ValueError if none of these contain any information
1722 raises ValueError if none of these contain any information
1724 """
1723 """
1725 if exc_tuple is None:
1724 if exc_tuple is None:
1726 etype, value, tb = sys.exc_info()
1725 etype, value, tb = sys.exc_info()
1727 else:
1726 else:
1728 etype, value, tb = exc_tuple
1727 etype, value, tb = exc_tuple
1729
1728
1730 if etype is None:
1729 if etype is None:
1731 if hasattr(sys, 'last_type'):
1730 if hasattr(sys, 'last_type'):
1732 etype, value, tb = sys.last_type, sys.last_value, \
1731 etype, value, tb = sys.last_type, sys.last_value, \
1733 sys.last_traceback
1732 sys.last_traceback
1734
1733
1735 if etype is None:
1734 if etype is None:
1736 raise ValueError("No exception to find")
1735 raise ValueError("No exception to find")
1737
1736
1738 # Now store the exception info in sys.last_type etc.
1737 # Now store the exception info in sys.last_type etc.
1739 # WARNING: these variables are somewhat deprecated and not
1738 # WARNING: these variables are somewhat deprecated and not
1740 # necessarily safe to use in a threaded environment, but tools
1739 # necessarily safe to use in a threaded environment, but tools
1741 # like pdb depend on their existence, so let's set them. If we
1740 # like pdb depend on their existence, so let's set them. If we
1742 # find problems in the field, we'll need to revisit their use.
1741 # find problems in the field, we'll need to revisit their use.
1743 sys.last_type = etype
1742 sys.last_type = etype
1744 sys.last_value = value
1743 sys.last_value = value
1745 sys.last_traceback = tb
1744 sys.last_traceback = tb
1746
1745
1747 return etype, value, tb
1746 return etype, value, tb
1748
1747
1749 def show_usage_error(self, exc):
1748 def show_usage_error(self, exc):
1750 """Show a short message for UsageErrors
1749 """Show a short message for UsageErrors
1751
1750
1752 These are special exceptions that shouldn't show a traceback.
1751 These are special exceptions that shouldn't show a traceback.
1753 """
1752 """
1754 print("UsageError: %s" % exc, file=sys.stderr)
1753 print("UsageError: %s" % exc, file=sys.stderr)
1755
1754
1756 def get_exception_only(self, exc_tuple=None):
1755 def get_exception_only(self, exc_tuple=None):
1757 """
1756 """
1758 Return as a string (ending with a newline) the exception that
1757 Return as a string (ending with a newline) the exception that
1759 just occurred, without any traceback.
1758 just occurred, without any traceback.
1760 """
1759 """
1761 etype, value, tb = self._get_exc_info(exc_tuple)
1760 etype, value, tb = self._get_exc_info(exc_tuple)
1762 msg = traceback.format_exception_only(etype, value)
1761 msg = traceback.format_exception_only(etype, value)
1763 return ''.join(msg)
1762 return ''.join(msg)
1764
1763
1765 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1764 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1766 exception_only=False):
1765 exception_only=False):
1767 """Display the exception that just occurred.
1766 """Display the exception that just occurred.
1768
1767
1769 If nothing is known about the exception, this is the method which
1768 If nothing is known about the exception, this is the method which
1770 should be used throughout the code for presenting user tracebacks,
1769 should be used throughout the code for presenting user tracebacks,
1771 rather than directly invoking the InteractiveTB object.
1770 rather than directly invoking the InteractiveTB object.
1772
1771
1773 A specific showsyntaxerror() also exists, but this method can take
1772 A specific showsyntaxerror() also exists, but this method can take
1774 care of calling it if needed, so unless you are explicitly catching a
1773 care of calling it if needed, so unless you are explicitly catching a
1775 SyntaxError exception, don't try to analyze the stack manually and
1774 SyntaxError exception, don't try to analyze the stack manually and
1776 simply call this method."""
1775 simply call this method."""
1777
1776
1778 try:
1777 try:
1779 try:
1778 try:
1780 etype, value, tb = self._get_exc_info(exc_tuple)
1779 etype, value, tb = self._get_exc_info(exc_tuple)
1781 except ValueError:
1780 except ValueError:
1782 print('No traceback available to show.', file=sys.stderr)
1781 print('No traceback available to show.', file=sys.stderr)
1783 return
1782 return
1784
1783
1785 if issubclass(etype, SyntaxError):
1784 if issubclass(etype, SyntaxError):
1786 # Though this won't be called by syntax errors in the input
1785 # Though this won't be called by syntax errors in the input
1787 # line, there may be SyntaxError cases with imported code.
1786 # line, there may be SyntaxError cases with imported code.
1788 self.showsyntaxerror(filename)
1787 self.showsyntaxerror(filename)
1789 elif etype is UsageError:
1788 elif etype is UsageError:
1790 self.show_usage_error(value)
1789 self.show_usage_error(value)
1791 else:
1790 else:
1792 if exception_only:
1791 if exception_only:
1793 stb = ['An exception has occurred, use %tb to see '
1792 stb = ['An exception has occurred, use %tb to see '
1794 'the full traceback.\n']
1793 'the full traceback.\n']
1795 stb.extend(self.InteractiveTB.get_exception_only(etype,
1794 stb.extend(self.InteractiveTB.get_exception_only(etype,
1796 value))
1795 value))
1797 else:
1796 else:
1798 try:
1797 try:
1799 # Exception classes can customise their traceback - we
1798 # Exception classes can customise their traceback - we
1800 # use this in IPython.parallel for exceptions occurring
1799 # use this in IPython.parallel for exceptions occurring
1801 # in the engines. This should return a list of strings.
1800 # in the engines. This should return a list of strings.
1802 stb = value._render_traceback_()
1801 stb = value._render_traceback_()
1803 except Exception:
1802 except Exception:
1804 stb = self.InteractiveTB.structured_traceback(etype,
1803 stb = self.InteractiveTB.structured_traceback(etype,
1805 value, tb, tb_offset=tb_offset)
1804 value, tb, tb_offset=tb_offset)
1806
1805
1807 self._showtraceback(etype, value, stb)
1806 self._showtraceback(etype, value, stb)
1808 if self.call_pdb:
1807 if self.call_pdb:
1809 # drop into debugger
1808 # drop into debugger
1810 self.debugger(force=True)
1809 self.debugger(force=True)
1811 return
1810 return
1812
1811
1813 # Actually show the traceback
1812 # Actually show the traceback
1814 self._showtraceback(etype, value, stb)
1813 self._showtraceback(etype, value, stb)
1815
1814
1816 except KeyboardInterrupt:
1815 except KeyboardInterrupt:
1817 print('\n' + self.get_exception_only(), file=sys.stderr)
1816 print('\n' + self.get_exception_only(), file=sys.stderr)
1818
1817
1819 def _showtraceback(self, etype, evalue, stb):
1818 def _showtraceback(self, etype, evalue, stb):
1820 """Actually show a traceback.
1819 """Actually show a traceback.
1821
1820
1822 Subclasses may override this method to put the traceback on a different
1821 Subclasses may override this method to put the traceback on a different
1823 place, like a side channel.
1822 place, like a side channel.
1824 """
1823 """
1825 print(self.InteractiveTB.stb2text(stb))
1824 print(self.InteractiveTB.stb2text(stb))
1826
1825
1827 def showsyntaxerror(self, filename=None):
1826 def showsyntaxerror(self, filename=None):
1828 """Display the syntax error that just occurred.
1827 """Display the syntax error that just occurred.
1829
1828
1830 This doesn't display a stack trace because there isn't one.
1829 This doesn't display a stack trace because there isn't one.
1831
1830
1832 If a filename is given, it is stuffed in the exception instead
1831 If a filename is given, it is stuffed in the exception instead
1833 of what was there before (because Python's parser always uses
1832 of what was there before (because Python's parser always uses
1834 "<string>" when reading from a string).
1833 "<string>" when reading from a string).
1835 """
1834 """
1836 etype, value, last_traceback = self._get_exc_info()
1835 etype, value, last_traceback = self._get_exc_info()
1837
1836
1838 if filename and issubclass(etype, SyntaxError):
1837 if filename and issubclass(etype, SyntaxError):
1839 try:
1838 try:
1840 value.filename = filename
1839 value.filename = filename
1841 except:
1840 except:
1842 # Not the format we expect; leave it alone
1841 # Not the format we expect; leave it alone
1843 pass
1842 pass
1844
1843
1845 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1844 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1846 self._showtraceback(etype, value, stb)
1845 self._showtraceback(etype, value, stb)
1847
1846
1848 # This is overridden in TerminalInteractiveShell to show a message about
1847 # This is overridden in TerminalInteractiveShell to show a message about
1849 # the %paste magic.
1848 # the %paste magic.
1850 def showindentationerror(self):
1849 def showindentationerror(self):
1851 """Called by run_cell when there's an IndentationError in code entered
1850 """Called by run_cell when there's an IndentationError in code entered
1852 at the prompt.
1851 at the prompt.
1853
1852
1854 This is overridden in TerminalInteractiveShell to show a message about
1853 This is overridden in TerminalInteractiveShell to show a message about
1855 the %paste magic."""
1854 the %paste magic."""
1856 self.showsyntaxerror()
1855 self.showsyntaxerror()
1857
1856
1858 #-------------------------------------------------------------------------
1857 #-------------------------------------------------------------------------
1859 # Things related to readline
1858 # Things related to readline
1860 #-------------------------------------------------------------------------
1859 #-------------------------------------------------------------------------
1861
1860
1862 def init_readline(self):
1861 def init_readline(self):
1863 """DEPRECATED
1862 """DEPRECATED
1864
1863
1865 Moved to terminal subclass, here only to simplify the init logic."""
1864 Moved to terminal subclass, here only to simplify the init logic."""
1866 # Set a number of methods that depend on readline to be no-op
1865 # Set a number of methods that depend on readline to be no-op
1867 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1866 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1868 DeprecationWarning, stacklevel=2)
1867 DeprecationWarning, stacklevel=2)
1869 self.set_custom_completer = no_op
1868 self.set_custom_completer = no_op
1870
1869
1871 @skip_doctest
1870 @skip_doctest
1872 def set_next_input(self, s, replace=False):
1871 def set_next_input(self, s, replace=False):
1873 """ Sets the 'default' input string for the next command line.
1872 """ Sets the 'default' input string for the next command line.
1874
1873
1875 Example::
1874 Example::
1876
1875
1877 In [1]: _ip.set_next_input("Hello Word")
1876 In [1]: _ip.set_next_input("Hello Word")
1878 In [2]: Hello Word_ # cursor is here
1877 In [2]: Hello Word_ # cursor is here
1879 """
1878 """
1880 self.rl_next_input = py3compat.cast_bytes_py2(s)
1879 self.rl_next_input = py3compat.cast_bytes_py2(s)
1881
1880
1882 def _indent_current_str(self):
1881 def _indent_current_str(self):
1883 """return the current level of indentation as a string"""
1882 """return the current level of indentation as a string"""
1884 return self.input_splitter.indent_spaces * ' '
1883 return self.input_splitter.indent_spaces * ' '
1885
1884
1886 #-------------------------------------------------------------------------
1885 #-------------------------------------------------------------------------
1887 # Things related to text completion
1886 # Things related to text completion
1888 #-------------------------------------------------------------------------
1887 #-------------------------------------------------------------------------
1889
1888
1890 def init_completer(self):
1889 def init_completer(self):
1891 """Initialize the completion machinery.
1890 """Initialize the completion machinery.
1892
1891
1893 This creates completion machinery that can be used by client code,
1892 This creates completion machinery that can be used by client code,
1894 either interactively in-process (typically triggered by the readline
1893 either interactively in-process (typically triggered by the readline
1895 library), programmatically (such as in test suites) or out-of-process
1894 library), programmatically (such as in test suites) or out-of-process
1896 (typically over the network by remote frontends).
1895 (typically over the network by remote frontends).
1897 """
1896 """
1898 from IPython.core.completer import IPCompleter
1897 from IPython.core.completer import IPCompleter
1899 from IPython.core.completerlib import (module_completer,
1898 from IPython.core.completerlib import (module_completer,
1900 magic_run_completer, cd_completer, reset_completer)
1899 magic_run_completer, cd_completer, reset_completer)
1901
1900
1902 self.Completer = IPCompleter(shell=self,
1901 self.Completer = IPCompleter(shell=self,
1903 namespace=self.user_ns,
1902 namespace=self.user_ns,
1904 global_namespace=self.user_global_ns,
1903 global_namespace=self.user_global_ns,
1905 parent=self,
1904 parent=self,
1906 )
1905 )
1907 self.configurables.append(self.Completer)
1906 self.configurables.append(self.Completer)
1908
1907
1909 # Add custom completers to the basic ones built into IPCompleter
1908 # Add custom completers to the basic ones built into IPCompleter
1910 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1909 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1911 self.strdispatchers['complete_command'] = sdisp
1910 self.strdispatchers['complete_command'] = sdisp
1912 self.Completer.custom_completers = sdisp
1911 self.Completer.custom_completers = sdisp
1913
1912
1914 self.set_hook('complete_command', module_completer, str_key = 'import')
1913 self.set_hook('complete_command', module_completer, str_key = 'import')
1915 self.set_hook('complete_command', module_completer, str_key = 'from')
1914 self.set_hook('complete_command', module_completer, str_key = 'from')
1916 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1915 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1917 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1916 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1918 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1917 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1919 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1918 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1920
1919
1921
1920
1922 def complete(self, text, line=None, cursor_pos=None):
1921 def complete(self, text, line=None, cursor_pos=None):
1923 """Return the completed text and a list of completions.
1922 """Return the completed text and a list of completions.
1924
1923
1925 Parameters
1924 Parameters
1926 ----------
1925 ----------
1927
1926
1928 text : string
1927 text : string
1929 A string of text to be completed on. It can be given as empty and
1928 A string of text to be completed on. It can be given as empty and
1930 instead a line/position pair are given. In this case, the
1929 instead a line/position pair are given. In this case, the
1931 completer itself will split the line like readline does.
1930 completer itself will split the line like readline does.
1932
1931
1933 line : string, optional
1932 line : string, optional
1934 The complete line that text is part of.
1933 The complete line that text is part of.
1935
1934
1936 cursor_pos : int, optional
1935 cursor_pos : int, optional
1937 The position of the cursor on the input line.
1936 The position of the cursor on the input line.
1938
1937
1939 Returns
1938 Returns
1940 -------
1939 -------
1941 text : string
1940 text : string
1942 The actual text that was completed.
1941 The actual text that was completed.
1943
1942
1944 matches : list
1943 matches : list
1945 A sorted list with all possible completions.
1944 A sorted list with all possible completions.
1946
1945
1947 The optional arguments allow the completion to take more context into
1946 The optional arguments allow the completion to take more context into
1948 account, and are part of the low-level completion API.
1947 account, and are part of the low-level completion API.
1949
1948
1950 This is a wrapper around the completion mechanism, similar to what
1949 This is a wrapper around the completion mechanism, similar to what
1951 readline does at the command line when the TAB key is hit. By
1950 readline does at the command line when the TAB key is hit. By
1952 exposing it as a method, it can be used by other non-readline
1951 exposing it as a method, it can be used by other non-readline
1953 environments (such as GUIs) for text completion.
1952 environments (such as GUIs) for text completion.
1954
1953
1955 Simple usage example:
1954 Simple usage example:
1956
1955
1957 In [1]: x = 'hello'
1956 In [1]: x = 'hello'
1958
1957
1959 In [2]: _ip.complete('x.l')
1958 In [2]: _ip.complete('x.l')
1960 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1959 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1961 """
1960 """
1962
1961
1963 # Inject names into __builtin__ so we can complete on the added names.
1962 # Inject names into __builtin__ so we can complete on the added names.
1964 with self.builtin_trap:
1963 with self.builtin_trap:
1965 return self.Completer.complete(text, line, cursor_pos)
1964 return self.Completer.complete(text, line, cursor_pos)
1966
1965
1967 def set_custom_completer(self, completer, pos=0):
1966 def set_custom_completer(self, completer, pos=0):
1968 """Adds a new custom completer function.
1967 """Adds a new custom completer function.
1969
1968
1970 The position argument (defaults to 0) is the index in the completers
1969 The position argument (defaults to 0) is the index in the completers
1971 list where you want the completer to be inserted."""
1970 list where you want the completer to be inserted."""
1972
1971
1973 newcomp = types.MethodType(completer,self.Completer)
1972 newcomp = types.MethodType(completer,self.Completer)
1974 self.Completer.matchers.insert(pos,newcomp)
1973 self.Completer.matchers.insert(pos,newcomp)
1975
1974
1976 def set_completer_frame(self, frame=None):
1975 def set_completer_frame(self, frame=None):
1977 """Set the frame of the completer."""
1976 """Set the frame of the completer."""
1978 if frame:
1977 if frame:
1979 self.Completer.namespace = frame.f_locals
1978 self.Completer.namespace = frame.f_locals
1980 self.Completer.global_namespace = frame.f_globals
1979 self.Completer.global_namespace = frame.f_globals
1981 else:
1980 else:
1982 self.Completer.namespace = self.user_ns
1981 self.Completer.namespace = self.user_ns
1983 self.Completer.global_namespace = self.user_global_ns
1982 self.Completer.global_namespace = self.user_global_ns
1984
1983
1985 #-------------------------------------------------------------------------
1984 #-------------------------------------------------------------------------
1986 # Things related to magics
1985 # Things related to magics
1987 #-------------------------------------------------------------------------
1986 #-------------------------------------------------------------------------
1988
1987
1989 def init_magics(self):
1988 def init_magics(self):
1990 from IPython.core import magics as m
1989 from IPython.core import magics as m
1991 self.magics_manager = magic.MagicsManager(shell=self,
1990 self.magics_manager = magic.MagicsManager(shell=self,
1992 parent=self,
1991 parent=self,
1993 user_magics=m.UserMagics(self))
1992 user_magics=m.UserMagics(self))
1994 self.configurables.append(self.magics_manager)
1993 self.configurables.append(self.magics_manager)
1995
1994
1996 # Expose as public API from the magics manager
1995 # Expose as public API from the magics manager
1997 self.register_magics = self.magics_manager.register
1996 self.register_magics = self.magics_manager.register
1998
1997
1999 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
1998 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2000 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
1999 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2001 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2000 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2002 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2001 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2003 )
2002 )
2004
2003
2005 # Register Magic Aliases
2004 # Register Magic Aliases
2006 mman = self.magics_manager
2005 mman = self.magics_manager
2007 # FIXME: magic aliases should be defined by the Magics classes
2006 # FIXME: magic aliases should be defined by the Magics classes
2008 # or in MagicsManager, not here
2007 # or in MagicsManager, not here
2009 mman.register_alias('ed', 'edit')
2008 mman.register_alias('ed', 'edit')
2010 mman.register_alias('hist', 'history')
2009 mman.register_alias('hist', 'history')
2011 mman.register_alias('rep', 'recall')
2010 mman.register_alias('rep', 'recall')
2012 mman.register_alias('SVG', 'svg', 'cell')
2011 mman.register_alias('SVG', 'svg', 'cell')
2013 mman.register_alias('HTML', 'html', 'cell')
2012 mman.register_alias('HTML', 'html', 'cell')
2014 mman.register_alias('file', 'writefile', 'cell')
2013 mman.register_alias('file', 'writefile', 'cell')
2015
2014
2016 # FIXME: Move the color initialization to the DisplayHook, which
2015 # FIXME: Move the color initialization to the DisplayHook, which
2017 # should be split into a prompt manager and displayhook. We probably
2016 # should be split into a prompt manager and displayhook. We probably
2018 # even need a centralize colors management object.
2017 # even need a centralize colors management object.
2019 self.magic('colors %s' % self.colors)
2018 self.magic('colors %s' % self.colors)
2020
2019
2021 # Defined here so that it's included in the documentation
2020 # Defined here so that it's included in the documentation
2022 @functools.wraps(magic.MagicsManager.register_function)
2021 @functools.wraps(magic.MagicsManager.register_function)
2023 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2022 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2024 self.magics_manager.register_function(func,
2023 self.magics_manager.register_function(func,
2025 magic_kind=magic_kind, magic_name=magic_name)
2024 magic_kind=magic_kind, magic_name=magic_name)
2026
2025
2027 def run_line_magic(self, magic_name, line):
2026 def run_line_magic(self, magic_name, line):
2028 """Execute the given line magic.
2027 """Execute the given line magic.
2029
2028
2030 Parameters
2029 Parameters
2031 ----------
2030 ----------
2032 magic_name : str
2031 magic_name : str
2033 Name of the desired magic function, without '%' prefix.
2032 Name of the desired magic function, without '%' prefix.
2034
2033
2035 line : str
2034 line : str
2036 The rest of the input line as a single string.
2035 The rest of the input line as a single string.
2037 """
2036 """
2038 fn = self.find_line_magic(magic_name)
2037 fn = self.find_line_magic(magic_name)
2039 if fn is None:
2038 if fn is None:
2040 cm = self.find_cell_magic(magic_name)
2039 cm = self.find_cell_magic(magic_name)
2041 etpl = "Line magic function `%%%s` not found%s."
2040 etpl = "Line magic function `%%%s` not found%s."
2042 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2041 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2043 'did you mean that instead?)' % magic_name )
2042 'did you mean that instead?)' % magic_name )
2044 error(etpl % (magic_name, extra))
2043 error(etpl % (magic_name, extra))
2045 else:
2044 else:
2046 # Note: this is the distance in the stack to the user's frame.
2045 # Note: this is the distance in the stack to the user's frame.
2047 # This will need to be updated if the internal calling logic gets
2046 # This will need to be updated if the internal calling logic gets
2048 # refactored, or else we'll be expanding the wrong variables.
2047 # refactored, or else we'll be expanding the wrong variables.
2049 stack_depth = 2
2048 stack_depth = 2
2050 magic_arg_s = self.var_expand(line, stack_depth)
2049 magic_arg_s = self.var_expand(line, stack_depth)
2051 # Put magic args in a list so we can call with f(*a) syntax
2050 # Put magic args in a list so we can call with f(*a) syntax
2052 args = [magic_arg_s]
2051 args = [magic_arg_s]
2053 kwargs = {}
2052 kwargs = {}
2054 # Grab local namespace if we need it:
2053 # Grab local namespace if we need it:
2055 if getattr(fn, "needs_local_scope", False):
2054 if getattr(fn, "needs_local_scope", False):
2056 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2055 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2057 with self.builtin_trap:
2056 with self.builtin_trap:
2058 result = fn(*args,**kwargs)
2057 result = fn(*args,**kwargs)
2059 return result
2058 return result
2060
2059
2061 def run_cell_magic(self, magic_name, line, cell):
2060 def run_cell_magic(self, magic_name, line, cell):
2062 """Execute the given cell magic.
2061 """Execute the given cell magic.
2063
2062
2064 Parameters
2063 Parameters
2065 ----------
2064 ----------
2066 magic_name : str
2065 magic_name : str
2067 Name of the desired magic function, without '%' prefix.
2066 Name of the desired magic function, without '%' prefix.
2068
2067
2069 line : str
2068 line : str
2070 The rest of the first input line as a single string.
2069 The rest of the first input line as a single string.
2071
2070
2072 cell : str
2071 cell : str
2073 The body of the cell as a (possibly multiline) string.
2072 The body of the cell as a (possibly multiline) string.
2074 """
2073 """
2075 fn = self.find_cell_magic(magic_name)
2074 fn = self.find_cell_magic(magic_name)
2076 if fn is None:
2075 if fn is None:
2077 lm = self.find_line_magic(magic_name)
2076 lm = self.find_line_magic(magic_name)
2078 etpl = "Cell magic `%%{0}` not found{1}."
2077 etpl = "Cell magic `%%{0}` not found{1}."
2079 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2078 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2080 'did you mean that instead?)'.format(magic_name))
2079 'did you mean that instead?)'.format(magic_name))
2081 error(etpl.format(magic_name, extra))
2080 error(etpl.format(magic_name, extra))
2082 elif cell == '':
2081 elif cell == '':
2083 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2082 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2084 if self.find_line_magic(magic_name) is not None:
2083 if self.find_line_magic(magic_name) is not None:
2085 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2084 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2086 raise UsageError(message)
2085 raise UsageError(message)
2087 else:
2086 else:
2088 # Note: this is the distance in the stack to the user's frame.
2087 # Note: this is the distance in the stack to the user's frame.
2089 # This will need to be updated if the internal calling logic gets
2088 # This will need to be updated if the internal calling logic gets
2090 # refactored, or else we'll be expanding the wrong variables.
2089 # refactored, or else we'll be expanding the wrong variables.
2091 stack_depth = 2
2090 stack_depth = 2
2092 magic_arg_s = self.var_expand(line, stack_depth)
2091 magic_arg_s = self.var_expand(line, stack_depth)
2093 with self.builtin_trap:
2092 with self.builtin_trap:
2094 result = fn(magic_arg_s, cell)
2093 result = fn(magic_arg_s, cell)
2095 return result
2094 return result
2096
2095
2097 def find_line_magic(self, magic_name):
2096 def find_line_magic(self, magic_name):
2098 """Find and return a line magic by name.
2097 """Find and return a line magic by name.
2099
2098
2100 Returns None if the magic isn't found."""
2099 Returns None if the magic isn't found."""
2101 return self.magics_manager.magics['line'].get(magic_name)
2100 return self.magics_manager.magics['line'].get(magic_name)
2102
2101
2103 def find_cell_magic(self, magic_name):
2102 def find_cell_magic(self, magic_name):
2104 """Find and return a cell magic by name.
2103 """Find and return a cell magic by name.
2105
2104
2106 Returns None if the magic isn't found."""
2105 Returns None if the magic isn't found."""
2107 return self.magics_manager.magics['cell'].get(magic_name)
2106 return self.magics_manager.magics['cell'].get(magic_name)
2108
2107
2109 def find_magic(self, magic_name, magic_kind='line'):
2108 def find_magic(self, magic_name, magic_kind='line'):
2110 """Find and return a magic of the given type by name.
2109 """Find and return a magic of the given type by name.
2111
2110
2112 Returns None if the magic isn't found."""
2111 Returns None if the magic isn't found."""
2113 return self.magics_manager.magics[magic_kind].get(magic_name)
2112 return self.magics_manager.magics[magic_kind].get(magic_name)
2114
2113
2115 def magic(self, arg_s):
2114 def magic(self, arg_s):
2116 """DEPRECATED. Use run_line_magic() instead.
2115 """DEPRECATED. Use run_line_magic() instead.
2117
2116
2118 Call a magic function by name.
2117 Call a magic function by name.
2119
2118
2120 Input: a string containing the name of the magic function to call and
2119 Input: a string containing the name of the magic function to call and
2121 any additional arguments to be passed to the magic.
2120 any additional arguments to be passed to the magic.
2122
2121
2123 magic('name -opt foo bar') is equivalent to typing at the ipython
2122 magic('name -opt foo bar') is equivalent to typing at the ipython
2124 prompt:
2123 prompt:
2125
2124
2126 In[1]: %name -opt foo bar
2125 In[1]: %name -opt foo bar
2127
2126
2128 To call a magic without arguments, simply use magic('name').
2127 To call a magic without arguments, simply use magic('name').
2129
2128
2130 This provides a proper Python function to call IPython's magics in any
2129 This provides a proper Python function to call IPython's magics in any
2131 valid Python code you can type at the interpreter, including loops and
2130 valid Python code you can type at the interpreter, including loops and
2132 compound statements.
2131 compound statements.
2133 """
2132 """
2134 # TODO: should we issue a loud deprecation warning here?
2133 # TODO: should we issue a loud deprecation warning here?
2135 magic_name, _, magic_arg_s = arg_s.partition(' ')
2134 magic_name, _, magic_arg_s = arg_s.partition(' ')
2136 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2135 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2137 return self.run_line_magic(magic_name, magic_arg_s)
2136 return self.run_line_magic(magic_name, magic_arg_s)
2138
2137
2139 #-------------------------------------------------------------------------
2138 #-------------------------------------------------------------------------
2140 # Things related to macros
2139 # Things related to macros
2141 #-------------------------------------------------------------------------
2140 #-------------------------------------------------------------------------
2142
2141
2143 def define_macro(self, name, themacro):
2142 def define_macro(self, name, themacro):
2144 """Define a new macro
2143 """Define a new macro
2145
2144
2146 Parameters
2145 Parameters
2147 ----------
2146 ----------
2148 name : str
2147 name : str
2149 The name of the macro.
2148 The name of the macro.
2150 themacro : str or Macro
2149 themacro : str or Macro
2151 The action to do upon invoking the macro. If a string, a new
2150 The action to do upon invoking the macro. If a string, a new
2152 Macro object is created by passing the string to it.
2151 Macro object is created by passing the string to it.
2153 """
2152 """
2154
2153
2155 from IPython.core import macro
2154 from IPython.core import macro
2156
2155
2157 if isinstance(themacro, string_types):
2156 if isinstance(themacro, string_types):
2158 themacro = macro.Macro(themacro)
2157 themacro = macro.Macro(themacro)
2159 if not isinstance(themacro, macro.Macro):
2158 if not isinstance(themacro, macro.Macro):
2160 raise ValueError('A macro must be a string or a Macro instance.')
2159 raise ValueError('A macro must be a string or a Macro instance.')
2161 self.user_ns[name] = themacro
2160 self.user_ns[name] = themacro
2162
2161
2163 #-------------------------------------------------------------------------
2162 #-------------------------------------------------------------------------
2164 # Things related to the running of system commands
2163 # Things related to the running of system commands
2165 #-------------------------------------------------------------------------
2164 #-------------------------------------------------------------------------
2166
2165
2167 def system_piped(self, cmd):
2166 def system_piped(self, cmd):
2168 """Call the given cmd in a subprocess, piping stdout/err
2167 """Call the given cmd in a subprocess, piping stdout/err
2169
2168
2170 Parameters
2169 Parameters
2171 ----------
2170 ----------
2172 cmd : str
2171 cmd : str
2173 Command to execute (can not end in '&', as background processes are
2172 Command to execute (can not end in '&', as background processes are
2174 not supported. Should not be a command that expects input
2173 not supported. Should not be a command that expects input
2175 other than simple text.
2174 other than simple text.
2176 """
2175 """
2177 if cmd.rstrip().endswith('&'):
2176 if cmd.rstrip().endswith('&'):
2178 # this is *far* from a rigorous test
2177 # this is *far* from a rigorous test
2179 # We do not support backgrounding processes because we either use
2178 # We do not support backgrounding processes because we either use
2180 # pexpect or pipes to read from. Users can always just call
2179 # pexpect or pipes to read from. Users can always just call
2181 # os.system() or use ip.system=ip.system_raw
2180 # os.system() or use ip.system=ip.system_raw
2182 # if they really want a background process.
2181 # if they really want a background process.
2183 raise OSError("Background processes not supported.")
2182 raise OSError("Background processes not supported.")
2184
2183
2185 # we explicitly do NOT return the subprocess status code, because
2184 # we explicitly do NOT return the subprocess status code, because
2186 # a non-None value would trigger :func:`sys.displayhook` calls.
2185 # a non-None value would trigger :func:`sys.displayhook` calls.
2187 # Instead, we store the exit_code in user_ns.
2186 # Instead, we store the exit_code in user_ns.
2188 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2187 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2189
2188
2190 def system_raw(self, cmd):
2189 def system_raw(self, cmd):
2191 """Call the given cmd in a subprocess using os.system on Windows or
2190 """Call the given cmd in a subprocess using os.system on Windows or
2192 subprocess.call using the system shell on other platforms.
2191 subprocess.call using the system shell on other platforms.
2193
2192
2194 Parameters
2193 Parameters
2195 ----------
2194 ----------
2196 cmd : str
2195 cmd : str
2197 Command to execute.
2196 Command to execute.
2198 """
2197 """
2199 cmd = self.var_expand(cmd, depth=1)
2198 cmd = self.var_expand(cmd, depth=1)
2200 # protect os.system from UNC paths on Windows, which it can't handle:
2199 # protect os.system from UNC paths on Windows, which it can't handle:
2201 if sys.platform == 'win32':
2200 if sys.platform == 'win32':
2202 from IPython.utils._process_win32 import AvoidUNCPath
2201 from IPython.utils._process_win32 import AvoidUNCPath
2203 with AvoidUNCPath() as path:
2202 with AvoidUNCPath() as path:
2204 if path is not None:
2203 if path is not None:
2205 cmd = '"pushd %s &&"%s' % (path, cmd)
2204 cmd = '"pushd %s &&"%s' % (path, cmd)
2206 cmd = py3compat.unicode_to_str(cmd)
2205 cmd = py3compat.unicode_to_str(cmd)
2207 try:
2206 try:
2208 ec = os.system(cmd)
2207 ec = os.system(cmd)
2209 except KeyboardInterrupt:
2208 except KeyboardInterrupt:
2210 print('\n' + self.get_exception_only(), file=sys.stderr)
2209 print('\n' + self.get_exception_only(), file=sys.stderr)
2211 ec = -2
2210 ec = -2
2212 else:
2211 else:
2213 cmd = py3compat.unicode_to_str(cmd)
2212 cmd = py3compat.unicode_to_str(cmd)
2214 # For posix the result of the subprocess.call() below is an exit
2213 # For posix the result of the subprocess.call() below is an exit
2215 # code, which by convention is zero for success, positive for
2214 # code, which by convention is zero for success, positive for
2216 # program failure. Exit codes above 128 are reserved for signals,
2215 # program failure. Exit codes above 128 are reserved for signals,
2217 # and the formula for converting a signal to an exit code is usually
2216 # and the formula for converting a signal to an exit code is usually
2218 # signal_number+128. To more easily differentiate between exit
2217 # signal_number+128. To more easily differentiate between exit
2219 # codes and signals, ipython uses negative numbers. For instance
2218 # codes and signals, ipython uses negative numbers. For instance
2220 # since control-c is signal 2 but exit code 130, ipython's
2219 # since control-c is signal 2 but exit code 130, ipython's
2221 # _exit_code variable will read -2. Note that some shells like
2220 # _exit_code variable will read -2. Note that some shells like
2222 # csh and fish don't follow sh/bash conventions for exit codes.
2221 # csh and fish don't follow sh/bash conventions for exit codes.
2223 executable = os.environ.get('SHELL', None)
2222 executable = os.environ.get('SHELL', None)
2224 try:
2223 try:
2225 # Use env shell instead of default /bin/sh
2224 # Use env shell instead of default /bin/sh
2226 ec = subprocess.call(cmd, shell=True, executable=executable)
2225 ec = subprocess.call(cmd, shell=True, executable=executable)
2227 except KeyboardInterrupt:
2226 except KeyboardInterrupt:
2228 # intercept control-C; a long traceback is not useful here
2227 # intercept control-C; a long traceback is not useful here
2229 print('\n' + self.get_exception_only(), file=sys.stderr)
2228 print('\n' + self.get_exception_only(), file=sys.stderr)
2230 ec = 130
2229 ec = 130
2231 if ec > 128:
2230 if ec > 128:
2232 ec = -(ec - 128)
2231 ec = -(ec - 128)
2233
2232
2234 # We explicitly do NOT return the subprocess status code, because
2233 # We explicitly do NOT return the subprocess status code, because
2235 # a non-None value would trigger :func:`sys.displayhook` calls.
2234 # a non-None value would trigger :func:`sys.displayhook` calls.
2236 # Instead, we store the exit_code in user_ns. Note the semantics
2235 # Instead, we store the exit_code in user_ns. Note the semantics
2237 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2236 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2238 # but raising SystemExit(_exit_code) will give status 254!
2237 # but raising SystemExit(_exit_code) will give status 254!
2239 self.user_ns['_exit_code'] = ec
2238 self.user_ns['_exit_code'] = ec
2240
2239
2241 # use piped system by default, because it is better behaved
2240 # use piped system by default, because it is better behaved
2242 system = system_piped
2241 system = system_piped
2243
2242
2244 def getoutput(self, cmd, split=True, depth=0):
2243 def getoutput(self, cmd, split=True, depth=0):
2245 """Get output (possibly including stderr) from a subprocess.
2244 """Get output (possibly including stderr) from a subprocess.
2246
2245
2247 Parameters
2246 Parameters
2248 ----------
2247 ----------
2249 cmd : str
2248 cmd : str
2250 Command to execute (can not end in '&', as background processes are
2249 Command to execute (can not end in '&', as background processes are
2251 not supported.
2250 not supported.
2252 split : bool, optional
2251 split : bool, optional
2253 If True, split the output into an IPython SList. Otherwise, an
2252 If True, split the output into an IPython SList. Otherwise, an
2254 IPython LSString is returned. These are objects similar to normal
2253 IPython LSString is returned. These are objects similar to normal
2255 lists and strings, with a few convenience attributes for easier
2254 lists and strings, with a few convenience attributes for easier
2256 manipulation of line-based output. You can use '?' on them for
2255 manipulation of line-based output. You can use '?' on them for
2257 details.
2256 details.
2258 depth : int, optional
2257 depth : int, optional
2259 How many frames above the caller are the local variables which should
2258 How many frames above the caller are the local variables which should
2260 be expanded in the command string? The default (0) assumes that the
2259 be expanded in the command string? The default (0) assumes that the
2261 expansion variables are in the stack frame calling this function.
2260 expansion variables are in the stack frame calling this function.
2262 """
2261 """
2263 if cmd.rstrip().endswith('&'):
2262 if cmd.rstrip().endswith('&'):
2264 # this is *far* from a rigorous test
2263 # this is *far* from a rigorous test
2265 raise OSError("Background processes not supported.")
2264 raise OSError("Background processes not supported.")
2266 out = getoutput(self.var_expand(cmd, depth=depth+1))
2265 out = getoutput(self.var_expand(cmd, depth=depth+1))
2267 if split:
2266 if split:
2268 out = SList(out.splitlines())
2267 out = SList(out.splitlines())
2269 else:
2268 else:
2270 out = LSString(out)
2269 out = LSString(out)
2271 return out
2270 return out
2272
2271
2273 #-------------------------------------------------------------------------
2272 #-------------------------------------------------------------------------
2274 # Things related to aliases
2273 # Things related to aliases
2275 #-------------------------------------------------------------------------
2274 #-------------------------------------------------------------------------
2276
2275
2277 def init_alias(self):
2276 def init_alias(self):
2278 self.alias_manager = AliasManager(shell=self, parent=self)
2277 self.alias_manager = AliasManager(shell=self, parent=self)
2279 self.configurables.append(self.alias_manager)
2278 self.configurables.append(self.alias_manager)
2280
2279
2281 #-------------------------------------------------------------------------
2280 #-------------------------------------------------------------------------
2282 # Things related to extensions
2281 # Things related to extensions
2283 #-------------------------------------------------------------------------
2282 #-------------------------------------------------------------------------
2284
2283
2285 def init_extension_manager(self):
2284 def init_extension_manager(self):
2286 self.extension_manager = ExtensionManager(shell=self, parent=self)
2285 self.extension_manager = ExtensionManager(shell=self, parent=self)
2287 self.configurables.append(self.extension_manager)
2286 self.configurables.append(self.extension_manager)
2288
2287
2289 #-------------------------------------------------------------------------
2288 #-------------------------------------------------------------------------
2290 # Things related to payloads
2289 # Things related to payloads
2291 #-------------------------------------------------------------------------
2290 #-------------------------------------------------------------------------
2292
2291
2293 def init_payload(self):
2292 def init_payload(self):
2294 self.payload_manager = PayloadManager(parent=self)
2293 self.payload_manager = PayloadManager(parent=self)
2295 self.configurables.append(self.payload_manager)
2294 self.configurables.append(self.payload_manager)
2296
2295
2297 #-------------------------------------------------------------------------
2296 #-------------------------------------------------------------------------
2298 # Things related to the prefilter
2297 # Things related to the prefilter
2299 #-------------------------------------------------------------------------
2298 #-------------------------------------------------------------------------
2300
2299
2301 def init_prefilter(self):
2300 def init_prefilter(self):
2302 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2301 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2303 self.configurables.append(self.prefilter_manager)
2302 self.configurables.append(self.prefilter_manager)
2304 # Ultimately this will be refactored in the new interpreter code, but
2303 # Ultimately this will be refactored in the new interpreter code, but
2305 # for now, we should expose the main prefilter method (there's legacy
2304 # for now, we should expose the main prefilter method (there's legacy
2306 # code out there that may rely on this).
2305 # code out there that may rely on this).
2307 self.prefilter = self.prefilter_manager.prefilter_lines
2306 self.prefilter = self.prefilter_manager.prefilter_lines
2308
2307
2309 def auto_rewrite_input(self, cmd):
2308 def auto_rewrite_input(self, cmd):
2310 """Print to the screen the rewritten form of the user's command.
2309 """Print to the screen the rewritten form of the user's command.
2311
2310
2312 This shows visual feedback by rewriting input lines that cause
2311 This shows visual feedback by rewriting input lines that cause
2313 automatic calling to kick in, like::
2312 automatic calling to kick in, like::
2314
2313
2315 /f x
2314 /f x
2316
2315
2317 into::
2316 into::
2318
2317
2319 ------> f(x)
2318 ------> f(x)
2320
2319
2321 after the user's input prompt. This helps the user understand that the
2320 after the user's input prompt. This helps the user understand that the
2322 input line was transformed automatically by IPython.
2321 input line was transformed automatically by IPython.
2323 """
2322 """
2324 if not self.show_rewritten_input:
2323 if not self.show_rewritten_input:
2325 return
2324 return
2326
2325
2327 # This is overridden in TerminalInteractiveShell to use fancy prompts
2326 # This is overridden in TerminalInteractiveShell to use fancy prompts
2328 print("------> " + cmd)
2327 print("------> " + cmd)
2329
2328
2330 #-------------------------------------------------------------------------
2329 #-------------------------------------------------------------------------
2331 # Things related to extracting values/expressions from kernel and user_ns
2330 # Things related to extracting values/expressions from kernel and user_ns
2332 #-------------------------------------------------------------------------
2331 #-------------------------------------------------------------------------
2333
2332
2334 def _user_obj_error(self):
2333 def _user_obj_error(self):
2335 """return simple exception dict
2334 """return simple exception dict
2336
2335
2337 for use in user_expressions
2336 for use in user_expressions
2338 """
2337 """
2339
2338
2340 etype, evalue, tb = self._get_exc_info()
2339 etype, evalue, tb = self._get_exc_info()
2341 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2340 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2342
2341
2343 exc_info = {
2342 exc_info = {
2344 u'status' : 'error',
2343 u'status' : 'error',
2345 u'traceback' : stb,
2344 u'traceback' : stb,
2346 u'ename' : unicode_type(etype.__name__),
2345 u'ename' : unicode_type(etype.__name__),
2347 u'evalue' : py3compat.safe_unicode(evalue),
2346 u'evalue' : py3compat.safe_unicode(evalue),
2348 }
2347 }
2349
2348
2350 return exc_info
2349 return exc_info
2351
2350
2352 def _format_user_obj(self, obj):
2351 def _format_user_obj(self, obj):
2353 """format a user object to display dict
2352 """format a user object to display dict
2354
2353
2355 for use in user_expressions
2354 for use in user_expressions
2356 """
2355 """
2357
2356
2358 data, md = self.display_formatter.format(obj)
2357 data, md = self.display_formatter.format(obj)
2359 value = {
2358 value = {
2360 'status' : 'ok',
2359 'status' : 'ok',
2361 'data' : data,
2360 'data' : data,
2362 'metadata' : md,
2361 'metadata' : md,
2363 }
2362 }
2364 return value
2363 return value
2365
2364
2366 def user_expressions(self, expressions):
2365 def user_expressions(self, expressions):
2367 """Evaluate a dict of expressions in the user's namespace.
2366 """Evaluate a dict of expressions in the user's namespace.
2368
2367
2369 Parameters
2368 Parameters
2370 ----------
2369 ----------
2371 expressions : dict
2370 expressions : dict
2372 A dict with string keys and string values. The expression values
2371 A dict with string keys and string values. The expression values
2373 should be valid Python expressions, each of which will be evaluated
2372 should be valid Python expressions, each of which will be evaluated
2374 in the user namespace.
2373 in the user namespace.
2375
2374
2376 Returns
2375 Returns
2377 -------
2376 -------
2378 A dict, keyed like the input expressions dict, with the rich mime-typed
2377 A dict, keyed like the input expressions dict, with the rich mime-typed
2379 display_data of each value.
2378 display_data of each value.
2380 """
2379 """
2381 out = {}
2380 out = {}
2382 user_ns = self.user_ns
2381 user_ns = self.user_ns
2383 global_ns = self.user_global_ns
2382 global_ns = self.user_global_ns
2384
2383
2385 for key, expr in iteritems(expressions):
2384 for key, expr in iteritems(expressions):
2386 try:
2385 try:
2387 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2386 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2388 except:
2387 except:
2389 value = self._user_obj_error()
2388 value = self._user_obj_error()
2390 out[key] = value
2389 out[key] = value
2391 return out
2390 return out
2392
2391
2393 #-------------------------------------------------------------------------
2392 #-------------------------------------------------------------------------
2394 # Things related to the running of code
2393 # Things related to the running of code
2395 #-------------------------------------------------------------------------
2394 #-------------------------------------------------------------------------
2396
2395
2397 def ex(self, cmd):
2396 def ex(self, cmd):
2398 """Execute a normal python statement in user namespace."""
2397 """Execute a normal python statement in user namespace."""
2399 with self.builtin_trap:
2398 with self.builtin_trap:
2400 exec(cmd, self.user_global_ns, self.user_ns)
2399 exec(cmd, self.user_global_ns, self.user_ns)
2401
2400
2402 def ev(self, expr):
2401 def ev(self, expr):
2403 """Evaluate python expression expr in user namespace.
2402 """Evaluate python expression expr in user namespace.
2404
2403
2405 Returns the result of evaluation
2404 Returns the result of evaluation
2406 """
2405 """
2407 with self.builtin_trap:
2406 with self.builtin_trap:
2408 return eval(expr, self.user_global_ns, self.user_ns)
2407 return eval(expr, self.user_global_ns, self.user_ns)
2409
2408
2410 def safe_execfile(self, fname, *where, **kw):
2409 def safe_execfile(self, fname, *where, **kw):
2411 """A safe version of the builtin execfile().
2410 """A safe version of the builtin execfile().
2412
2411
2413 This version will never throw an exception, but instead print
2412 This version will never throw an exception, but instead print
2414 helpful error messages to the screen. This only works on pure
2413 helpful error messages to the screen. This only works on pure
2415 Python files with the .py extension.
2414 Python files with the .py extension.
2416
2415
2417 Parameters
2416 Parameters
2418 ----------
2417 ----------
2419 fname : string
2418 fname : string
2420 The name of the file to be executed.
2419 The name of the file to be executed.
2421 where : tuple
2420 where : tuple
2422 One or two namespaces, passed to execfile() as (globals,locals).
2421 One or two namespaces, passed to execfile() as (globals,locals).
2423 If only one is given, it is passed as both.
2422 If only one is given, it is passed as both.
2424 exit_ignore : bool (False)
2423 exit_ignore : bool (False)
2425 If True, then silence SystemExit for non-zero status (it is always
2424 If True, then silence SystemExit for non-zero status (it is always
2426 silenced for zero status, as it is so common).
2425 silenced for zero status, as it is so common).
2427 raise_exceptions : bool (False)
2426 raise_exceptions : bool (False)
2428 If True raise exceptions everywhere. Meant for testing.
2427 If True raise exceptions everywhere. Meant for testing.
2429 shell_futures : bool (False)
2428 shell_futures : bool (False)
2430 If True, the code will share future statements with the interactive
2429 If True, the code will share future statements with the interactive
2431 shell. It will both be affected by previous __future__ imports, and
2430 shell. It will both be affected by previous __future__ imports, and
2432 any __future__ imports in the code will affect the shell. If False,
2431 any __future__ imports in the code will affect the shell. If False,
2433 __future__ imports are not shared in either direction.
2432 __future__ imports are not shared in either direction.
2434
2433
2435 """
2434 """
2436 kw.setdefault('exit_ignore', False)
2435 kw.setdefault('exit_ignore', False)
2437 kw.setdefault('raise_exceptions', False)
2436 kw.setdefault('raise_exceptions', False)
2438 kw.setdefault('shell_futures', False)
2437 kw.setdefault('shell_futures', False)
2439
2438
2440 fname = os.path.abspath(os.path.expanduser(fname))
2439 fname = os.path.abspath(os.path.expanduser(fname))
2441
2440
2442 # Make sure we can open the file
2441 # Make sure we can open the file
2443 try:
2442 try:
2444 with open(fname):
2443 with open(fname):
2445 pass
2444 pass
2446 except:
2445 except:
2447 warn('Could not open file <%s> for safe execution.' % fname)
2446 warn('Could not open file <%s> for safe execution.' % fname)
2448 return
2447 return
2449
2448
2450 # Find things also in current directory. This is needed to mimic the
2449 # Find things also in current directory. This is needed to mimic the
2451 # behavior of running a script from the system command line, where
2450 # behavior of running a script from the system command line, where
2452 # Python inserts the script's directory into sys.path
2451 # Python inserts the script's directory into sys.path
2453 dname = os.path.dirname(fname)
2452 dname = os.path.dirname(fname)
2454
2453
2455 with prepended_to_syspath(dname), self.builtin_trap:
2454 with prepended_to_syspath(dname), self.builtin_trap:
2456 try:
2455 try:
2457 glob, loc = (where + (None, ))[:2]
2456 glob, loc = (where + (None, ))[:2]
2458 py3compat.execfile(
2457 py3compat.execfile(
2459 fname, glob, loc,
2458 fname, glob, loc,
2460 self.compile if kw['shell_futures'] else None)
2459 self.compile if kw['shell_futures'] else None)
2461 except SystemExit as status:
2460 except SystemExit as status:
2462 # If the call was made with 0 or None exit status (sys.exit(0)
2461 # If the call was made with 0 or None exit status (sys.exit(0)
2463 # or sys.exit() ), don't bother showing a traceback, as both of
2462 # or sys.exit() ), don't bother showing a traceback, as both of
2464 # these are considered normal by the OS:
2463 # these are considered normal by the OS:
2465 # > python -c'import sys;sys.exit(0)'; echo $?
2464 # > python -c'import sys;sys.exit(0)'; echo $?
2466 # 0
2465 # 0
2467 # > python -c'import sys;sys.exit()'; echo $?
2466 # > python -c'import sys;sys.exit()'; echo $?
2468 # 0
2467 # 0
2469 # For other exit status, we show the exception unless
2468 # For other exit status, we show the exception unless
2470 # explicitly silenced, but only in short form.
2469 # explicitly silenced, but only in short form.
2471 if status.code:
2470 if status.code:
2472 if kw['raise_exceptions']:
2471 if kw['raise_exceptions']:
2473 raise
2472 raise
2474 if not kw['exit_ignore']:
2473 if not kw['exit_ignore']:
2475 self.showtraceback(exception_only=True)
2474 self.showtraceback(exception_only=True)
2476 except:
2475 except:
2477 if kw['raise_exceptions']:
2476 if kw['raise_exceptions']:
2478 raise
2477 raise
2479 # tb offset is 2 because we wrap execfile
2478 # tb offset is 2 because we wrap execfile
2480 self.showtraceback(tb_offset=2)
2479 self.showtraceback(tb_offset=2)
2481
2480
2482 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2481 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2483 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2482 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2484
2483
2485 Parameters
2484 Parameters
2486 ----------
2485 ----------
2487 fname : str
2486 fname : str
2488 The name of the file to execute. The filename must have a
2487 The name of the file to execute. The filename must have a
2489 .ipy or .ipynb extension.
2488 .ipy or .ipynb extension.
2490 shell_futures : bool (False)
2489 shell_futures : bool (False)
2491 If True, the code will share future statements with the interactive
2490 If True, the code will share future statements with the interactive
2492 shell. It will both be affected by previous __future__ imports, and
2491 shell. It will both be affected by previous __future__ imports, and
2493 any __future__ imports in the code will affect the shell. If False,
2492 any __future__ imports in the code will affect the shell. If False,
2494 __future__ imports are not shared in either direction.
2493 __future__ imports are not shared in either direction.
2495 raise_exceptions : bool (False)
2494 raise_exceptions : bool (False)
2496 If True raise exceptions everywhere. Meant for testing.
2495 If True raise exceptions everywhere. Meant for testing.
2497 """
2496 """
2498 fname = os.path.abspath(os.path.expanduser(fname))
2497 fname = os.path.abspath(os.path.expanduser(fname))
2499
2498
2500 # Make sure we can open the file
2499 # Make sure we can open the file
2501 try:
2500 try:
2502 with open(fname):
2501 with open(fname):
2503 pass
2502 pass
2504 except:
2503 except:
2505 warn('Could not open file <%s> for safe execution.' % fname)
2504 warn('Could not open file <%s> for safe execution.' % fname)
2506 return
2505 return
2507
2506
2508 # Find things also in current directory. This is needed to mimic the
2507 # Find things also in current directory. This is needed to mimic the
2509 # behavior of running a script from the system command line, where
2508 # behavior of running a script from the system command line, where
2510 # Python inserts the script's directory into sys.path
2509 # Python inserts the script's directory into sys.path
2511 dname = os.path.dirname(fname)
2510 dname = os.path.dirname(fname)
2512
2511
2513 def get_cells():
2512 def get_cells():
2514 """generator for sequence of code blocks to run"""
2513 """generator for sequence of code blocks to run"""
2515 if fname.endswith('.ipynb'):
2514 if fname.endswith('.ipynb'):
2516 from nbformat import read
2515 from nbformat import read
2517 with io_open(fname) as f:
2516 with io_open(fname) as f:
2518 nb = read(f, as_version=4)
2517 nb = read(f, as_version=4)
2519 if not nb.cells:
2518 if not nb.cells:
2520 return
2519 return
2521 for cell in nb.cells:
2520 for cell in nb.cells:
2522 if cell.cell_type == 'code':
2521 if cell.cell_type == 'code':
2523 yield cell.source
2522 yield cell.source
2524 else:
2523 else:
2525 with open(fname) as f:
2524 with open(fname) as f:
2526 yield f.read()
2525 yield f.read()
2527
2526
2528 with prepended_to_syspath(dname):
2527 with prepended_to_syspath(dname):
2529 try:
2528 try:
2530 for cell in get_cells():
2529 for cell in get_cells():
2531 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2530 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2532 if raise_exceptions:
2531 if raise_exceptions:
2533 result.raise_error()
2532 result.raise_error()
2534 elif not result.success:
2533 elif not result.success:
2535 break
2534 break
2536 except:
2535 except:
2537 if raise_exceptions:
2536 if raise_exceptions:
2538 raise
2537 raise
2539 self.showtraceback()
2538 self.showtraceback()
2540 warn('Unknown failure executing file: <%s>' % fname)
2539 warn('Unknown failure executing file: <%s>' % fname)
2541
2540
2542 def safe_run_module(self, mod_name, where):
2541 def safe_run_module(self, mod_name, where):
2543 """A safe version of runpy.run_module().
2542 """A safe version of runpy.run_module().
2544
2543
2545 This version will never throw an exception, but instead print
2544 This version will never throw an exception, but instead print
2546 helpful error messages to the screen.
2545 helpful error messages to the screen.
2547
2546
2548 `SystemExit` exceptions with status code 0 or None are ignored.
2547 `SystemExit` exceptions with status code 0 or None are ignored.
2549
2548
2550 Parameters
2549 Parameters
2551 ----------
2550 ----------
2552 mod_name : string
2551 mod_name : string
2553 The name of the module to be executed.
2552 The name of the module to be executed.
2554 where : dict
2553 where : dict
2555 The globals namespace.
2554 The globals namespace.
2556 """
2555 """
2557 try:
2556 try:
2558 try:
2557 try:
2559 where.update(
2558 where.update(
2560 runpy.run_module(str(mod_name), run_name="__main__",
2559 runpy.run_module(str(mod_name), run_name="__main__",
2561 alter_sys=True)
2560 alter_sys=True)
2562 )
2561 )
2563 except SystemExit as status:
2562 except SystemExit as status:
2564 if status.code:
2563 if status.code:
2565 raise
2564 raise
2566 except:
2565 except:
2567 self.showtraceback()
2566 self.showtraceback()
2568 warn('Unknown failure executing module: <%s>' % mod_name)
2567 warn('Unknown failure executing module: <%s>' % mod_name)
2569
2568
2570 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2569 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2571 """Run a complete IPython cell.
2570 """Run a complete IPython cell.
2572
2571
2573 Parameters
2572 Parameters
2574 ----------
2573 ----------
2575 raw_cell : str
2574 raw_cell : str
2576 The code (including IPython code such as %magic functions) to run.
2575 The code (including IPython code such as %magic functions) to run.
2577 store_history : bool
2576 store_history : bool
2578 If True, the raw and translated cell will be stored in IPython's
2577 If True, the raw and translated cell will be stored in IPython's
2579 history. For user code calling back into IPython's machinery, this
2578 history. For user code calling back into IPython's machinery, this
2580 should be set to False.
2579 should be set to False.
2581 silent : bool
2580 silent : bool
2582 If True, avoid side-effects, such as implicit displayhooks and
2581 If True, avoid side-effects, such as implicit displayhooks and
2583 and logging. silent=True forces store_history=False.
2582 and logging. silent=True forces store_history=False.
2584 shell_futures : bool
2583 shell_futures : bool
2585 If True, the code will share future statements with the interactive
2584 If True, the code will share future statements with the interactive
2586 shell. It will both be affected by previous __future__ imports, and
2585 shell. It will both be affected by previous __future__ imports, and
2587 any __future__ imports in the code will affect the shell. If False,
2586 any __future__ imports in the code will affect the shell. If False,
2588 __future__ imports are not shared in either direction.
2587 __future__ imports are not shared in either direction.
2589
2588
2590 Returns
2589 Returns
2591 -------
2590 -------
2592 result : :class:`ExecutionResult`
2591 result : :class:`ExecutionResult`
2593 """
2592 """
2594 result = ExecutionResult()
2593 result = ExecutionResult()
2595
2594
2596 if (not raw_cell) or raw_cell.isspace():
2595 if (not raw_cell) or raw_cell.isspace():
2597 self.last_execution_succeeded = True
2596 self.last_execution_succeeded = True
2598 return result
2597 return result
2599
2598
2600 if silent:
2599 if silent:
2601 store_history = False
2600 store_history = False
2602
2601
2603 if store_history:
2602 if store_history:
2604 result.execution_count = self.execution_count
2603 result.execution_count = self.execution_count
2605
2604
2606 def error_before_exec(value):
2605 def error_before_exec(value):
2607 result.error_before_exec = value
2606 result.error_before_exec = value
2608 self.last_execution_succeeded = False
2607 self.last_execution_succeeded = False
2609 return result
2608 return result
2610
2609
2611 self.events.trigger('pre_execute')
2610 self.events.trigger('pre_execute')
2612 if not silent:
2611 if not silent:
2613 self.events.trigger('pre_run_cell')
2612 self.events.trigger('pre_run_cell')
2614
2613
2615 # If any of our input transformation (input_transformer_manager or
2614 # If any of our input transformation (input_transformer_manager or
2616 # prefilter_manager) raises an exception, we store it in this variable
2615 # prefilter_manager) raises an exception, we store it in this variable
2617 # so that we can display the error after logging the input and storing
2616 # so that we can display the error after logging the input and storing
2618 # it in the history.
2617 # it in the history.
2619 preprocessing_exc_tuple = None
2618 preprocessing_exc_tuple = None
2620 try:
2619 try:
2621 # Static input transformations
2620 # Static input transformations
2622 cell = self.input_transformer_manager.transform_cell(raw_cell)
2621 cell = self.input_transformer_manager.transform_cell(raw_cell)
2623 except SyntaxError:
2622 except SyntaxError:
2624 preprocessing_exc_tuple = sys.exc_info()
2623 preprocessing_exc_tuple = sys.exc_info()
2625 cell = raw_cell # cell has to exist so it can be stored/logged
2624 cell = raw_cell # cell has to exist so it can be stored/logged
2626 else:
2625 else:
2627 if len(cell.splitlines()) == 1:
2626 if len(cell.splitlines()) == 1:
2628 # Dynamic transformations - only applied for single line commands
2627 # Dynamic transformations - only applied for single line commands
2629 with self.builtin_trap:
2628 with self.builtin_trap:
2630 try:
2629 try:
2631 # use prefilter_lines to handle trailing newlines
2630 # use prefilter_lines to handle trailing newlines
2632 # restore trailing newline for ast.parse
2631 # restore trailing newline for ast.parse
2633 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2632 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2634 except Exception:
2633 except Exception:
2635 # don't allow prefilter errors to crash IPython
2634 # don't allow prefilter errors to crash IPython
2636 preprocessing_exc_tuple = sys.exc_info()
2635 preprocessing_exc_tuple = sys.exc_info()
2637
2636
2638 # Store raw and processed history
2637 # Store raw and processed history
2639 if store_history:
2638 if store_history:
2640 self.history_manager.store_inputs(self.execution_count,
2639 self.history_manager.store_inputs(self.execution_count,
2641 cell, raw_cell)
2640 cell, raw_cell)
2642 if not silent:
2641 if not silent:
2643 self.logger.log(cell, raw_cell)
2642 self.logger.log(cell, raw_cell)
2644
2643
2645 # Display the exception if input processing failed.
2644 # Display the exception if input processing failed.
2646 if preprocessing_exc_tuple is not None:
2645 if preprocessing_exc_tuple is not None:
2647 self.showtraceback(preprocessing_exc_tuple)
2646 self.showtraceback(preprocessing_exc_tuple)
2648 if store_history:
2647 if store_history:
2649 self.execution_count += 1
2648 self.execution_count += 1
2650 return error_before_exec(preprocessing_exc_tuple[2])
2649 return error_before_exec(preprocessing_exc_tuple[2])
2651
2650
2652 # Our own compiler remembers the __future__ environment. If we want to
2651 # Our own compiler remembers the __future__ environment. If we want to
2653 # run code with a separate __future__ environment, use the default
2652 # run code with a separate __future__ environment, use the default
2654 # compiler
2653 # compiler
2655 compiler = self.compile if shell_futures else CachingCompiler()
2654 compiler = self.compile if shell_futures else CachingCompiler()
2656
2655
2657 with self.builtin_trap:
2656 with self.builtin_trap:
2658 cell_name = self.compile.cache(cell, self.execution_count)
2657 cell_name = self.compile.cache(cell, self.execution_count)
2659
2658
2660 with self.display_trap:
2659 with self.display_trap:
2661 # Compile to bytecode
2660 # Compile to bytecode
2662 try:
2661 try:
2663 code_ast = compiler.ast_parse(cell, filename=cell_name)
2662 code_ast = compiler.ast_parse(cell, filename=cell_name)
2664 except self.custom_exceptions as e:
2663 except self.custom_exceptions as e:
2665 etype, value, tb = sys.exc_info()
2664 etype, value, tb = sys.exc_info()
2666 self.CustomTB(etype, value, tb)
2665 self.CustomTB(etype, value, tb)
2667 return error_before_exec(e)
2666 return error_before_exec(e)
2668 except IndentationError as e:
2667 except IndentationError as e:
2669 self.showindentationerror()
2668 self.showindentationerror()
2670 if store_history:
2669 if store_history:
2671 self.execution_count += 1
2670 self.execution_count += 1
2672 return error_before_exec(e)
2671 return error_before_exec(e)
2673 except (OverflowError, SyntaxError, ValueError, TypeError,
2672 except (OverflowError, SyntaxError, ValueError, TypeError,
2674 MemoryError) as e:
2673 MemoryError) as e:
2675 self.showsyntaxerror()
2674 self.showsyntaxerror()
2676 if store_history:
2675 if store_history:
2677 self.execution_count += 1
2676 self.execution_count += 1
2678 return error_before_exec(e)
2677 return error_before_exec(e)
2679
2678
2680 # Apply AST transformations
2679 # Apply AST transformations
2681 try:
2680 try:
2682 code_ast = self.transform_ast(code_ast)
2681 code_ast = self.transform_ast(code_ast)
2683 except InputRejected as e:
2682 except InputRejected as e:
2684 self.showtraceback()
2683 self.showtraceback()
2685 if store_history:
2684 if store_history:
2686 self.execution_count += 1
2685 self.execution_count += 1
2687 return error_before_exec(e)
2686 return error_before_exec(e)
2688
2687
2689 # Give the displayhook a reference to our ExecutionResult so it
2688 # Give the displayhook a reference to our ExecutionResult so it
2690 # can fill in the output value.
2689 # can fill in the output value.
2691 self.displayhook.exec_result = result
2690 self.displayhook.exec_result = result
2692
2691
2693 # Execute the user code
2692 # Execute the user code
2694 interactivity = "none" if silent else self.ast_node_interactivity
2693 interactivity = "none" if silent else self.ast_node_interactivity
2695 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2694 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2696 interactivity=interactivity, compiler=compiler, result=result)
2695 interactivity=interactivity, compiler=compiler, result=result)
2697
2696
2698 self.last_execution_succeeded = not has_raised
2697 self.last_execution_succeeded = not has_raised
2699
2698
2700 # Reset this so later displayed values do not modify the
2699 # Reset this so later displayed values do not modify the
2701 # ExecutionResult
2700 # ExecutionResult
2702 self.displayhook.exec_result = None
2701 self.displayhook.exec_result = None
2703
2702
2704 self.events.trigger('post_execute')
2703 self.events.trigger('post_execute')
2705 if not silent:
2704 if not silent:
2706 self.events.trigger('post_run_cell')
2705 self.events.trigger('post_run_cell')
2707
2706
2708 if store_history:
2707 if store_history:
2709 # Write output to the database. Does nothing unless
2708 # Write output to the database. Does nothing unless
2710 # history output logging is enabled.
2709 # history output logging is enabled.
2711 self.history_manager.store_output(self.execution_count)
2710 self.history_manager.store_output(self.execution_count)
2712 # Each cell is a *single* input, regardless of how many lines it has
2711 # Each cell is a *single* input, regardless of how many lines it has
2713 self.execution_count += 1
2712 self.execution_count += 1
2714
2713
2715 return result
2714 return result
2716
2715
2717 def transform_ast(self, node):
2716 def transform_ast(self, node):
2718 """Apply the AST transformations from self.ast_transformers
2717 """Apply the AST transformations from self.ast_transformers
2719
2718
2720 Parameters
2719 Parameters
2721 ----------
2720 ----------
2722 node : ast.Node
2721 node : ast.Node
2723 The root node to be transformed. Typically called with the ast.Module
2722 The root node to be transformed. Typically called with the ast.Module
2724 produced by parsing user input.
2723 produced by parsing user input.
2725
2724
2726 Returns
2725 Returns
2727 -------
2726 -------
2728 An ast.Node corresponding to the node it was called with. Note that it
2727 An ast.Node corresponding to the node it was called with. Note that it
2729 may also modify the passed object, so don't rely on references to the
2728 may also modify the passed object, so don't rely on references to the
2730 original AST.
2729 original AST.
2731 """
2730 """
2732 for transformer in self.ast_transformers:
2731 for transformer in self.ast_transformers:
2733 try:
2732 try:
2734 node = transformer.visit(node)
2733 node = transformer.visit(node)
2735 except InputRejected:
2734 except InputRejected:
2736 # User-supplied AST transformers can reject an input by raising
2735 # User-supplied AST transformers can reject an input by raising
2737 # an InputRejected. Short-circuit in this case so that we
2736 # an InputRejected. Short-circuit in this case so that we
2738 # don't unregister the transform.
2737 # don't unregister the transform.
2739 raise
2738 raise
2740 except Exception:
2739 except Exception:
2741 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2740 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2742 self.ast_transformers.remove(transformer)
2741 self.ast_transformers.remove(transformer)
2743
2742
2744 if self.ast_transformers:
2743 if self.ast_transformers:
2745 ast.fix_missing_locations(node)
2744 ast.fix_missing_locations(node)
2746 return node
2745 return node
2747
2746
2748
2747
2749 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2748 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2750 compiler=compile, result=None):
2749 compiler=compile, result=None):
2751 """Run a sequence of AST nodes. The execution mode depends on the
2750 """Run a sequence of AST nodes. The execution mode depends on the
2752 interactivity parameter.
2751 interactivity parameter.
2753
2752
2754 Parameters
2753 Parameters
2755 ----------
2754 ----------
2756 nodelist : list
2755 nodelist : list
2757 A sequence of AST nodes to run.
2756 A sequence of AST nodes to run.
2758 cell_name : str
2757 cell_name : str
2759 Will be passed to the compiler as the filename of the cell. Typically
2758 Will be passed to the compiler as the filename of the cell. Typically
2760 the value returned by ip.compile.cache(cell).
2759 the value returned by ip.compile.cache(cell).
2761 interactivity : str
2760 interactivity : str
2762 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2761 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2763 run interactively (displaying output from expressions). 'last_expr'
2762 run interactively (displaying output from expressions). 'last_expr'
2764 will run the last node interactively only if it is an expression (i.e.
2763 will run the last node interactively only if it is an expression (i.e.
2765 expressions in loops or other blocks are not displayed. Other values
2764 expressions in loops or other blocks are not displayed. Other values
2766 for this parameter will raise a ValueError.
2765 for this parameter will raise a ValueError.
2767 compiler : callable
2766 compiler : callable
2768 A function with the same interface as the built-in compile(), to turn
2767 A function with the same interface as the built-in compile(), to turn
2769 the AST nodes into code objects. Default is the built-in compile().
2768 the AST nodes into code objects. Default is the built-in compile().
2770 result : ExecutionResult, optional
2769 result : ExecutionResult, optional
2771 An object to store exceptions that occur during execution.
2770 An object to store exceptions that occur during execution.
2772
2771
2773 Returns
2772 Returns
2774 -------
2773 -------
2775 True if an exception occurred while running code, False if it finished
2774 True if an exception occurred while running code, False if it finished
2776 running.
2775 running.
2777 """
2776 """
2778 if not nodelist:
2777 if not nodelist:
2779 return
2778 return
2780
2779
2781 if interactivity == 'last_expr':
2780 if interactivity == 'last_expr':
2782 if isinstance(nodelist[-1], ast.Expr):
2781 if isinstance(nodelist[-1], ast.Expr):
2783 interactivity = "last"
2782 interactivity = "last"
2784 else:
2783 else:
2785 interactivity = "none"
2784 interactivity = "none"
2786
2785
2787 if interactivity == 'none':
2786 if interactivity == 'none':
2788 to_run_exec, to_run_interactive = nodelist, []
2787 to_run_exec, to_run_interactive = nodelist, []
2789 elif interactivity == 'last':
2788 elif interactivity == 'last':
2790 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2789 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2791 elif interactivity == 'all':
2790 elif interactivity == 'all':
2792 to_run_exec, to_run_interactive = [], nodelist
2791 to_run_exec, to_run_interactive = [], nodelist
2793 else:
2792 else:
2794 raise ValueError("Interactivity was %r" % interactivity)
2793 raise ValueError("Interactivity was %r" % interactivity)
2795
2794
2796 try:
2795 try:
2797 for i, node in enumerate(to_run_exec):
2796 for i, node in enumerate(to_run_exec):
2798 mod = ast.Module([node])
2797 mod = ast.Module([node])
2799 code = compiler(mod, cell_name, "exec")
2798 code = compiler(mod, cell_name, "exec")
2800 if self.run_code(code, result):
2799 if self.run_code(code, result):
2801 return True
2800 return True
2802
2801
2803 for i, node in enumerate(to_run_interactive):
2802 for i, node in enumerate(to_run_interactive):
2804 mod = ast.Interactive([node])
2803 mod = ast.Interactive([node])
2805 code = compiler(mod, cell_name, "single")
2804 code = compiler(mod, cell_name, "single")
2806 if self.run_code(code, result):
2805 if self.run_code(code, result):
2807 return True
2806 return True
2808
2807
2809 # Flush softspace
2808 # Flush softspace
2810 if softspace(sys.stdout, 0):
2809 if softspace(sys.stdout, 0):
2811 print()
2810 print()
2812
2811
2813 except:
2812 except:
2814 # It's possible to have exceptions raised here, typically by
2813 # It's possible to have exceptions raised here, typically by
2815 # compilation of odd code (such as a naked 'return' outside a
2814 # compilation of odd code (such as a naked 'return' outside a
2816 # function) that did parse but isn't valid. Typically the exception
2815 # function) that did parse but isn't valid. Typically the exception
2817 # is a SyntaxError, but it's safest just to catch anything and show
2816 # is a SyntaxError, but it's safest just to catch anything and show
2818 # the user a traceback.
2817 # the user a traceback.
2819
2818
2820 # We do only one try/except outside the loop to minimize the impact
2819 # We do only one try/except outside the loop to minimize the impact
2821 # on runtime, and also because if any node in the node list is
2820 # on runtime, and also because if any node in the node list is
2822 # broken, we should stop execution completely.
2821 # broken, we should stop execution completely.
2823 if result:
2822 if result:
2824 result.error_before_exec = sys.exc_info()[1]
2823 result.error_before_exec = sys.exc_info()[1]
2825 self.showtraceback()
2824 self.showtraceback()
2826 return True
2825 return True
2827
2826
2828 return False
2827 return False
2829
2828
2830 def run_code(self, code_obj, result=None):
2829 def run_code(self, code_obj, result=None):
2831 """Execute a code object.
2830 """Execute a code object.
2832
2831
2833 When an exception occurs, self.showtraceback() is called to display a
2832 When an exception occurs, self.showtraceback() is called to display a
2834 traceback.
2833 traceback.
2835
2834
2836 Parameters
2835 Parameters
2837 ----------
2836 ----------
2838 code_obj : code object
2837 code_obj : code object
2839 A compiled code object, to be executed
2838 A compiled code object, to be executed
2840 result : ExecutionResult, optional
2839 result : ExecutionResult, optional
2841 An object to store exceptions that occur during execution.
2840 An object to store exceptions that occur during execution.
2842
2841
2843 Returns
2842 Returns
2844 -------
2843 -------
2845 False : successful execution.
2844 False : successful execution.
2846 True : an error occurred.
2845 True : an error occurred.
2847 """
2846 """
2848 # Set our own excepthook in case the user code tries to call it
2847 # Set our own excepthook in case the user code tries to call it
2849 # directly, so that the IPython crash handler doesn't get triggered
2848 # directly, so that the IPython crash handler doesn't get triggered
2850 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2849 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2851
2850
2852 # we save the original sys.excepthook in the instance, in case config
2851 # we save the original sys.excepthook in the instance, in case config
2853 # code (such as magics) needs access to it.
2852 # code (such as magics) needs access to it.
2854 self.sys_excepthook = old_excepthook
2853 self.sys_excepthook = old_excepthook
2855 outflag = 1 # happens in more places, so it's easier as default
2854 outflag = 1 # happens in more places, so it's easier as default
2856 try:
2855 try:
2857 try:
2856 try:
2858 self.hooks.pre_run_code_hook()
2857 self.hooks.pre_run_code_hook()
2859 #rprint('Running code', repr(code_obj)) # dbg
2858 #rprint('Running code', repr(code_obj)) # dbg
2860 exec(code_obj, self.user_global_ns, self.user_ns)
2859 exec(code_obj, self.user_global_ns, self.user_ns)
2861 finally:
2860 finally:
2862 # Reset our crash handler in place
2861 # Reset our crash handler in place
2863 sys.excepthook = old_excepthook
2862 sys.excepthook = old_excepthook
2864 except SystemExit as e:
2863 except SystemExit as e:
2865 if result is not None:
2864 if result is not None:
2866 result.error_in_exec = e
2865 result.error_in_exec = e
2867 self.showtraceback(exception_only=True)
2866 self.showtraceback(exception_only=True)
2868 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2867 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2869 except self.custom_exceptions:
2868 except self.custom_exceptions:
2870 etype, value, tb = sys.exc_info()
2869 etype, value, tb = sys.exc_info()
2871 if result is not None:
2870 if result is not None:
2872 result.error_in_exec = value
2871 result.error_in_exec = value
2873 self.CustomTB(etype, value, tb)
2872 self.CustomTB(etype, value, tb)
2874 except:
2873 except:
2875 if result is not None:
2874 if result is not None:
2876 result.error_in_exec = sys.exc_info()[1]
2875 result.error_in_exec = sys.exc_info()[1]
2877 self.showtraceback()
2876 self.showtraceback()
2878 else:
2877 else:
2879 outflag = 0
2878 outflag = 0
2880 return outflag
2879 return outflag
2881
2880
2882 # For backwards compatibility
2881 # For backwards compatibility
2883 runcode = run_code
2882 runcode = run_code
2884
2883
2885 #-------------------------------------------------------------------------
2884 #-------------------------------------------------------------------------
2886 # Things related to GUI support and pylab
2885 # Things related to GUI support and pylab
2887 #-------------------------------------------------------------------------
2886 #-------------------------------------------------------------------------
2888
2887
2889 active_eventloop = None
2888 active_eventloop = None
2890
2889
2891 def enable_gui(self, gui=None):
2890 def enable_gui(self, gui=None):
2892 raise NotImplementedError('Implement enable_gui in a subclass')
2891 raise NotImplementedError('Implement enable_gui in a subclass')
2893
2892
2894 def enable_matplotlib(self, gui=None):
2893 def enable_matplotlib(self, gui=None):
2895 """Enable interactive matplotlib and inline figure support.
2894 """Enable interactive matplotlib and inline figure support.
2896
2895
2897 This takes the following steps:
2896 This takes the following steps:
2898
2897
2899 1. select the appropriate eventloop and matplotlib backend
2898 1. select the appropriate eventloop and matplotlib backend
2900 2. set up matplotlib for interactive use with that backend
2899 2. set up matplotlib for interactive use with that backend
2901 3. configure formatters for inline figure display
2900 3. configure formatters for inline figure display
2902 4. enable the selected gui eventloop
2901 4. enable the selected gui eventloop
2903
2902
2904 Parameters
2903 Parameters
2905 ----------
2904 ----------
2906 gui : optional, string
2905 gui : optional, string
2907 If given, dictates the choice of matplotlib GUI backend to use
2906 If given, dictates the choice of matplotlib GUI backend to use
2908 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2907 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2909 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2908 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2910 matplotlib (as dictated by the matplotlib build-time options plus the
2909 matplotlib (as dictated by the matplotlib build-time options plus the
2911 user's matplotlibrc configuration file). Note that not all backends
2910 user's matplotlibrc configuration file). Note that not all backends
2912 make sense in all contexts, for example a terminal ipython can't
2911 make sense in all contexts, for example a terminal ipython can't
2913 display figures inline.
2912 display figures inline.
2914 """
2913 """
2915 from IPython.core import pylabtools as pt
2914 from IPython.core import pylabtools as pt
2916 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2915 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2917
2916
2918 if gui != 'inline':
2917 if gui != 'inline':
2919 # If we have our first gui selection, store it
2918 # If we have our first gui selection, store it
2920 if self.pylab_gui_select is None:
2919 if self.pylab_gui_select is None:
2921 self.pylab_gui_select = gui
2920 self.pylab_gui_select = gui
2922 # Otherwise if they are different
2921 # Otherwise if they are different
2923 elif gui != self.pylab_gui_select:
2922 elif gui != self.pylab_gui_select:
2924 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2923 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2925 ' Using %s instead.' % (gui, self.pylab_gui_select))
2924 ' Using %s instead.' % (gui, self.pylab_gui_select))
2926 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2925 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2927
2926
2928 pt.activate_matplotlib(backend)
2927 pt.activate_matplotlib(backend)
2929 pt.configure_inline_support(self, backend)
2928 pt.configure_inline_support(self, backend)
2930
2929
2931 # Now we must activate the gui pylab wants to use, and fix %run to take
2930 # Now we must activate the gui pylab wants to use, and fix %run to take
2932 # plot updates into account
2931 # plot updates into account
2933 self.enable_gui(gui)
2932 self.enable_gui(gui)
2934 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2933 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2935 pt.mpl_runner(self.safe_execfile)
2934 pt.mpl_runner(self.safe_execfile)
2936
2935
2937 return gui, backend
2936 return gui, backend
2938
2937
2939 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2938 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2940 """Activate pylab support at runtime.
2939 """Activate pylab support at runtime.
2941
2940
2942 This turns on support for matplotlib, preloads into the interactive
2941 This turns on support for matplotlib, preloads into the interactive
2943 namespace all of numpy and pylab, and configures IPython to correctly
2942 namespace all of numpy and pylab, and configures IPython to correctly
2944 interact with the GUI event loop. The GUI backend to be used can be
2943 interact with the GUI event loop. The GUI backend to be used can be
2945 optionally selected with the optional ``gui`` argument.
2944 optionally selected with the optional ``gui`` argument.
2946
2945
2947 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2946 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2948
2947
2949 Parameters
2948 Parameters
2950 ----------
2949 ----------
2951 gui : optional, string
2950 gui : optional, string
2952 If given, dictates the choice of matplotlib GUI backend to use
2951 If given, dictates the choice of matplotlib GUI backend to use
2953 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2952 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2954 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2953 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2955 matplotlib (as dictated by the matplotlib build-time options plus the
2954 matplotlib (as dictated by the matplotlib build-time options plus the
2956 user's matplotlibrc configuration file). Note that not all backends
2955 user's matplotlibrc configuration file). Note that not all backends
2957 make sense in all contexts, for example a terminal ipython can't
2956 make sense in all contexts, for example a terminal ipython can't
2958 display figures inline.
2957 display figures inline.
2959 import_all : optional, bool, default: True
2958 import_all : optional, bool, default: True
2960 Whether to do `from numpy import *` and `from pylab import *`
2959 Whether to do `from numpy import *` and `from pylab import *`
2961 in addition to module imports.
2960 in addition to module imports.
2962 welcome_message : deprecated
2961 welcome_message : deprecated
2963 This argument is ignored, no welcome message will be displayed.
2962 This argument is ignored, no welcome message will be displayed.
2964 """
2963 """
2965 from IPython.core.pylabtools import import_pylab
2964 from IPython.core.pylabtools import import_pylab
2966
2965
2967 gui, backend = self.enable_matplotlib(gui)
2966 gui, backend = self.enable_matplotlib(gui)
2968
2967
2969 # We want to prevent the loading of pylab to pollute the user's
2968 # We want to prevent the loading of pylab to pollute the user's
2970 # namespace as shown by the %who* magics, so we execute the activation
2969 # namespace as shown by the %who* magics, so we execute the activation
2971 # code in an empty namespace, and we update *both* user_ns and
2970 # code in an empty namespace, and we update *both* user_ns and
2972 # user_ns_hidden with this information.
2971 # user_ns_hidden with this information.
2973 ns = {}
2972 ns = {}
2974 import_pylab(ns, import_all)
2973 import_pylab(ns, import_all)
2975 # warn about clobbered names
2974 # warn about clobbered names
2976 ignored = {"__builtins__"}
2975 ignored = {"__builtins__"}
2977 both = set(ns).intersection(self.user_ns).difference(ignored)
2976 both = set(ns).intersection(self.user_ns).difference(ignored)
2978 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2977 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2979 self.user_ns.update(ns)
2978 self.user_ns.update(ns)
2980 self.user_ns_hidden.update(ns)
2979 self.user_ns_hidden.update(ns)
2981 return gui, backend, clobbered
2980 return gui, backend, clobbered
2982
2981
2983 #-------------------------------------------------------------------------
2982 #-------------------------------------------------------------------------
2984 # Utilities
2983 # Utilities
2985 #-------------------------------------------------------------------------
2984 #-------------------------------------------------------------------------
2986
2985
2987 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2986 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2988 """Expand python variables in a string.
2987 """Expand python variables in a string.
2989
2988
2990 The depth argument indicates how many frames above the caller should
2989 The depth argument indicates how many frames above the caller should
2991 be walked to look for the local namespace where to expand variables.
2990 be walked to look for the local namespace where to expand variables.
2992
2991
2993 The global namespace for expansion is always the user's interactive
2992 The global namespace for expansion is always the user's interactive
2994 namespace.
2993 namespace.
2995 """
2994 """
2996 ns = self.user_ns.copy()
2995 ns = self.user_ns.copy()
2997 try:
2996 try:
2998 frame = sys._getframe(depth+1)
2997 frame = sys._getframe(depth+1)
2999 except ValueError:
2998 except ValueError:
3000 # This is thrown if there aren't that many frames on the stack,
2999 # This is thrown if there aren't that many frames on the stack,
3001 # e.g. if a script called run_line_magic() directly.
3000 # e.g. if a script called run_line_magic() directly.
3002 pass
3001 pass
3003 else:
3002 else:
3004 ns.update(frame.f_locals)
3003 ns.update(frame.f_locals)
3005
3004
3006 try:
3005 try:
3007 # We have to use .vformat() here, because 'self' is a valid and common
3006 # We have to use .vformat() here, because 'self' is a valid and common
3008 # name, and expanding **ns for .format() would make it collide with
3007 # name, and expanding **ns for .format() would make it collide with
3009 # the 'self' argument of the method.
3008 # the 'self' argument of the method.
3010 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3009 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3011 except Exception:
3010 except Exception:
3012 # if formatter couldn't format, just let it go untransformed
3011 # if formatter couldn't format, just let it go untransformed
3013 pass
3012 pass
3014 return cmd
3013 return cmd
3015
3014
3016 def mktempfile(self, data=None, prefix='ipython_edit_'):
3015 def mktempfile(self, data=None, prefix='ipython_edit_'):
3017 """Make a new tempfile and return its filename.
3016 """Make a new tempfile and return its filename.
3018
3017
3019 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3018 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3020 but it registers the created filename internally so ipython cleans it up
3019 but it registers the created filename internally so ipython cleans it up
3021 at exit time.
3020 at exit time.
3022
3021
3023 Optional inputs:
3022 Optional inputs:
3024
3023
3025 - data(None): if data is given, it gets written out to the temp file
3024 - data(None): if data is given, it gets written out to the temp file
3026 immediately, and the file is closed again."""
3025 immediately, and the file is closed again."""
3027
3026
3028 dirname = tempfile.mkdtemp(prefix=prefix)
3027 dirname = tempfile.mkdtemp(prefix=prefix)
3029 self.tempdirs.append(dirname)
3028 self.tempdirs.append(dirname)
3030
3029
3031 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3030 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3032 os.close(handle) # On Windows, there can only be one open handle on a file
3031 os.close(handle) # On Windows, there can only be one open handle on a file
3033 self.tempfiles.append(filename)
3032 self.tempfiles.append(filename)
3034
3033
3035 if data:
3034 if data:
3036 tmp_file = open(filename,'w')
3035 tmp_file = open(filename,'w')
3037 tmp_file.write(data)
3036 tmp_file.write(data)
3038 tmp_file.close()
3037 tmp_file.close()
3039 return filename
3038 return filename
3040
3039
3041 @undoc
3040 @undoc
3042 def write(self,data):
3041 def write(self,data):
3043 """DEPRECATED: Write a string to the default output"""
3042 """DEPRECATED: Write a string to the default output"""
3044 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3043 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3045 DeprecationWarning, stacklevel=2)
3044 DeprecationWarning, stacklevel=2)
3046 sys.stdout.write(data)
3045 sys.stdout.write(data)
3047
3046
3048 @undoc
3047 @undoc
3049 def write_err(self,data):
3048 def write_err(self,data):
3050 """DEPRECATED: Write a string to the default error output"""
3049 """DEPRECATED: Write a string to the default error output"""
3051 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3050 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3052 DeprecationWarning, stacklevel=2)
3051 DeprecationWarning, stacklevel=2)
3053 sys.stderr.write(data)
3052 sys.stderr.write(data)
3054
3053
3055 def ask_yes_no(self, prompt, default=None, interrupt=None):
3054 def ask_yes_no(self, prompt, default=None, interrupt=None):
3056 if self.quiet:
3055 if self.quiet:
3057 return True
3056 return True
3058 return ask_yes_no(prompt,default,interrupt)
3057 return ask_yes_no(prompt,default,interrupt)
3059
3058
3060 def show_usage(self):
3059 def show_usage(self):
3061 """Show a usage message"""
3060 """Show a usage message"""
3062 page.page(IPython.core.usage.interactive_usage)
3061 page.page(IPython.core.usage.interactive_usage)
3063
3062
3064 def extract_input_lines(self, range_str, raw=False):
3063 def extract_input_lines(self, range_str, raw=False):
3065 """Return as a string a set of input history slices.
3064 """Return as a string a set of input history slices.
3066
3065
3067 Parameters
3066 Parameters
3068 ----------
3067 ----------
3069 range_str : string
3068 range_str : string
3070 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3069 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3071 since this function is for use by magic functions which get their
3070 since this function is for use by magic functions which get their
3072 arguments as strings. The number before the / is the session
3071 arguments as strings. The number before the / is the session
3073 number: ~n goes n back from the current session.
3072 number: ~n goes n back from the current session.
3074
3073
3075 raw : bool, optional
3074 raw : bool, optional
3076 By default, the processed input is used. If this is true, the raw
3075 By default, the processed input is used. If this is true, the raw
3077 input history is used instead.
3076 input history is used instead.
3078
3077
3079 Notes
3078 Notes
3080 -----
3079 -----
3081
3080
3082 Slices can be described with two notations:
3081 Slices can be described with two notations:
3083
3082
3084 * ``N:M`` -> standard python form, means including items N...(M-1).
3083 * ``N:M`` -> standard python form, means including items N...(M-1).
3085 * ``N-M`` -> include items N..M (closed endpoint).
3084 * ``N-M`` -> include items N..M (closed endpoint).
3086 """
3085 """
3087 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3086 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3088 return "\n".join(x for _, _, x in lines)
3087 return "\n".join(x for _, _, x in lines)
3089
3088
3090 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3089 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3091 """Get a code string from history, file, url, or a string or macro.
3090 """Get a code string from history, file, url, or a string or macro.
3092
3091
3093 This is mainly used by magic functions.
3092 This is mainly used by magic functions.
3094
3093
3095 Parameters
3094 Parameters
3096 ----------
3095 ----------
3097
3096
3098 target : str
3097 target : str
3099
3098
3100 A string specifying code to retrieve. This will be tried respectively
3099 A string specifying code to retrieve. This will be tried respectively
3101 as: ranges of input history (see %history for syntax), url,
3100 as: ranges of input history (see %history for syntax), url,
3102 corresponding .py file, filename, or an expression evaluating to a
3101 corresponding .py file, filename, or an expression evaluating to a
3103 string or Macro in the user namespace.
3102 string or Macro in the user namespace.
3104
3103
3105 raw : bool
3104 raw : bool
3106 If true (default), retrieve raw history. Has no effect on the other
3105 If true (default), retrieve raw history. Has no effect on the other
3107 retrieval mechanisms.
3106 retrieval mechanisms.
3108
3107
3109 py_only : bool (default False)
3108 py_only : bool (default False)
3110 Only try to fetch python code, do not try alternative methods to decode file
3109 Only try to fetch python code, do not try alternative methods to decode file
3111 if unicode fails.
3110 if unicode fails.
3112
3111
3113 Returns
3112 Returns
3114 -------
3113 -------
3115 A string of code.
3114 A string of code.
3116
3115
3117 ValueError is raised if nothing is found, and TypeError if it evaluates
3116 ValueError is raised if nothing is found, and TypeError if it evaluates
3118 to an object of another type. In each case, .args[0] is a printable
3117 to an object of another type. In each case, .args[0] is a printable
3119 message.
3118 message.
3120 """
3119 """
3121 code = self.extract_input_lines(target, raw=raw) # Grab history
3120 code = self.extract_input_lines(target, raw=raw) # Grab history
3122 if code:
3121 if code:
3123 return code
3122 return code
3124 try:
3123 try:
3125 if target.startswith(('http://', 'https://')):
3124 if target.startswith(('http://', 'https://')):
3126 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3125 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3127 except UnicodeDecodeError:
3126 except UnicodeDecodeError:
3128 if not py_only :
3127 if not py_only :
3129 # Deferred import
3128 # Deferred import
3130 try:
3129 try:
3131 from urllib.request import urlopen # Py3
3130 from urllib.request import urlopen # Py3
3132 except ImportError:
3131 except ImportError:
3133 from urllib import urlopen
3132 from urllib import urlopen
3134 response = urlopen(target)
3133 response = urlopen(target)
3135 return response.read().decode('latin1')
3134 return response.read().decode('latin1')
3136 raise ValueError(("'%s' seem to be unreadable.") % target)
3135 raise ValueError(("'%s' seem to be unreadable.") % target)
3137
3136
3138 potential_target = [target]
3137 potential_target = [target]
3139 try :
3138 try :
3140 potential_target.insert(0,get_py_filename(target))
3139 potential_target.insert(0,get_py_filename(target))
3141 except IOError:
3140 except IOError:
3142 pass
3141 pass
3143
3142
3144 for tgt in potential_target :
3143 for tgt in potential_target :
3145 if os.path.isfile(tgt): # Read file
3144 if os.path.isfile(tgt): # Read file
3146 try :
3145 try :
3147 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3146 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3148 except UnicodeDecodeError :
3147 except UnicodeDecodeError :
3149 if not py_only :
3148 if not py_only :
3150 with io_open(tgt,'r', encoding='latin1') as f :
3149 with io_open(tgt,'r', encoding='latin1') as f :
3151 return f.read()
3150 return f.read()
3152 raise ValueError(("'%s' seem to be unreadable.") % target)
3151 raise ValueError(("'%s' seem to be unreadable.") % target)
3153 elif os.path.isdir(os.path.expanduser(tgt)):
3152 elif os.path.isdir(os.path.expanduser(tgt)):
3154 raise ValueError("'%s' is a directory, not a regular file." % target)
3153 raise ValueError("'%s' is a directory, not a regular file." % target)
3155
3154
3156 if search_ns:
3155 if search_ns:
3157 # Inspect namespace to load object source
3156 # Inspect namespace to load object source
3158 object_info = self.object_inspect(target, detail_level=1)
3157 object_info = self.object_inspect(target, detail_level=1)
3159 if object_info['found'] and object_info['source']:
3158 if object_info['found'] and object_info['source']:
3160 return object_info['source']
3159 return object_info['source']
3161
3160
3162 try: # User namespace
3161 try: # User namespace
3163 codeobj = eval(target, self.user_ns)
3162 codeobj = eval(target, self.user_ns)
3164 except Exception:
3163 except Exception:
3165 raise ValueError(("'%s' was not found in history, as a file, url, "
3164 raise ValueError(("'%s' was not found in history, as a file, url, "
3166 "nor in the user namespace.") % target)
3165 "nor in the user namespace.") % target)
3167
3166
3168 if isinstance(codeobj, string_types):
3167 if isinstance(codeobj, string_types):
3169 return codeobj
3168 return codeobj
3170 elif isinstance(codeobj, Macro):
3169 elif isinstance(codeobj, Macro):
3171 return codeobj.value
3170 return codeobj.value
3172
3171
3173 raise TypeError("%s is neither a string nor a macro." % target,
3172 raise TypeError("%s is neither a string nor a macro." % target,
3174 codeobj)
3173 codeobj)
3175
3174
3176 #-------------------------------------------------------------------------
3175 #-------------------------------------------------------------------------
3177 # Things related to IPython exiting
3176 # Things related to IPython exiting
3178 #-------------------------------------------------------------------------
3177 #-------------------------------------------------------------------------
3179 def atexit_operations(self):
3178 def atexit_operations(self):
3180 """This will be executed at the time of exit.
3179 """This will be executed at the time of exit.
3181
3180
3182 Cleanup operations and saving of persistent data that is done
3181 Cleanup operations and saving of persistent data that is done
3183 unconditionally by IPython should be performed here.
3182 unconditionally by IPython should be performed here.
3184
3183
3185 For things that may depend on startup flags or platform specifics (such
3184 For things that may depend on startup flags or platform specifics (such
3186 as having readline or not), register a separate atexit function in the
3185 as having readline or not), register a separate atexit function in the
3187 code that has the appropriate information, rather than trying to
3186 code that has the appropriate information, rather than trying to
3188 clutter
3187 clutter
3189 """
3188 """
3190 # Close the history session (this stores the end time and line count)
3189 # Close the history session (this stores the end time and line count)
3191 # this must be *before* the tempfile cleanup, in case of temporary
3190 # this must be *before* the tempfile cleanup, in case of temporary
3192 # history db
3191 # history db
3193 self.history_manager.end_session()
3192 self.history_manager.end_session()
3194
3193
3195 # Cleanup all tempfiles and folders left around
3194 # Cleanup all tempfiles and folders left around
3196 for tfile in self.tempfiles:
3195 for tfile in self.tempfiles:
3197 try:
3196 try:
3198 os.unlink(tfile)
3197 os.unlink(tfile)
3199 except OSError:
3198 except OSError:
3200 pass
3199 pass
3201
3200
3202 for tdir in self.tempdirs:
3201 for tdir in self.tempdirs:
3203 try:
3202 try:
3204 os.rmdir(tdir)
3203 os.rmdir(tdir)
3205 except OSError:
3204 except OSError:
3206 pass
3205 pass
3207
3206
3208 # Clear all user namespaces to release all references cleanly.
3207 # Clear all user namespaces to release all references cleanly.
3209 self.reset(new_session=False)
3208 self.reset(new_session=False)
3210
3209
3211 # Run user hooks
3210 # Run user hooks
3212 self.hooks.shutdown_hook()
3211 self.hooks.shutdown_hook()
3213
3212
3214 def cleanup(self):
3213 def cleanup(self):
3215 self.restore_sys_module_state()
3214 self.restore_sys_module_state()
3216
3215
3217
3216
3218 # Overridden in terminal subclass to change prompts
3217 # Overridden in terminal subclass to change prompts
3219 def switch_doctest_mode(self, mode):
3218 def switch_doctest_mode(self, mode):
3220 pass
3219 pass
3221
3220
3222
3221
3223 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3222 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3224 """An abstract base class for InteractiveShell."""
3223 """An abstract base class for InteractiveShell."""
3225
3224
3226 InteractiveShellABC.register(InteractiveShell)
3225 InteractiveShellABC.register(InteractiveShell)
@@ -1,221 +1,220 b''
1 """Logger class for IPython's logging facilities.
1 """Logger class for IPython's logging facilities.
2 """
2 """
3 from __future__ import print_function
4
3
5 #*****************************************************************************
4 #*****************************************************************************
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
6 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 #
7 #
9 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
10 #*****************************************************************************
12
11
13 #****************************************************************************
12 #****************************************************************************
14 # Modules and globals
13 # Modules and globals
15
14
16 # Python standard modules
15 # Python standard modules
17 import glob
16 import glob
18 import io
17 import io
19 import os
18 import os
20 import time
19 import time
21
20
22 from IPython.utils.py3compat import str_to_unicode
21 from IPython.utils.py3compat import str_to_unicode
23
22
24 #****************************************************************************
23 #****************************************************************************
25 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
24 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
26 # ipython and does input cache management. Finish cleanup later...
25 # ipython and does input cache management. Finish cleanup later...
27
26
28 class Logger(object):
27 class Logger(object):
29 """A Logfile class with different policies for file creation"""
28 """A Logfile class with different policies for file creation"""
30
29
31 def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
30 def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
32 logmode='over'):
31 logmode='over'):
33
32
34 # this is the full ipython instance, we need some attributes from it
33 # this is the full ipython instance, we need some attributes from it
35 # which won't exist until later. What a mess, clean up later...
34 # which won't exist until later. What a mess, clean up later...
36 self.home_dir = home_dir
35 self.home_dir = home_dir
37
36
38 self.logfname = logfname
37 self.logfname = logfname
39 self.loghead = loghead
38 self.loghead = loghead
40 self.logmode = logmode
39 self.logmode = logmode
41 self.logfile = None
40 self.logfile = None
42
41
43 # Whether to log raw or processed input
42 # Whether to log raw or processed input
44 self.log_raw_input = False
43 self.log_raw_input = False
45
44
46 # whether to also log output
45 # whether to also log output
47 self.log_output = False
46 self.log_output = False
48
47
49 # whether to put timestamps before each log entry
48 # whether to put timestamps before each log entry
50 self.timestamp = False
49 self.timestamp = False
51
50
52 # activity control flags
51 # activity control flags
53 self.log_active = False
52 self.log_active = False
54
53
55 # logmode is a validated property
54 # logmode is a validated property
56 def _set_mode(self,mode):
55 def _set_mode(self,mode):
57 if mode not in ['append','backup','global','over','rotate']:
56 if mode not in ['append','backup','global','over','rotate']:
58 raise ValueError('invalid log mode %s given' % mode)
57 raise ValueError('invalid log mode %s given' % mode)
59 self._logmode = mode
58 self._logmode = mode
60
59
61 def _get_mode(self):
60 def _get_mode(self):
62 return self._logmode
61 return self._logmode
63
62
64 logmode = property(_get_mode,_set_mode)
63 logmode = property(_get_mode,_set_mode)
65
64
66 def logstart(self, logfname=None, loghead=None, logmode=None,
65 def logstart(self, logfname=None, loghead=None, logmode=None,
67 log_output=False, timestamp=False, log_raw_input=False):
66 log_output=False, timestamp=False, log_raw_input=False):
68 """Generate a new log-file with a default header.
67 """Generate a new log-file with a default header.
69
68
70 Raises RuntimeError if the log has already been started"""
69 Raises RuntimeError if the log has already been started"""
71
70
72 if self.logfile is not None:
71 if self.logfile is not None:
73 raise RuntimeError('Log file is already active: %s' %
72 raise RuntimeError('Log file is already active: %s' %
74 self.logfname)
73 self.logfname)
75
74
76 # The parameters can override constructor defaults
75 # The parameters can override constructor defaults
77 if logfname is not None: self.logfname = logfname
76 if logfname is not None: self.logfname = logfname
78 if loghead is not None: self.loghead = loghead
77 if loghead is not None: self.loghead = loghead
79 if logmode is not None: self.logmode = logmode
78 if logmode is not None: self.logmode = logmode
80
79
81 # Parameters not part of the constructor
80 # Parameters not part of the constructor
82 self.timestamp = timestamp
81 self.timestamp = timestamp
83 self.log_output = log_output
82 self.log_output = log_output
84 self.log_raw_input = log_raw_input
83 self.log_raw_input = log_raw_input
85
84
86 # init depending on the log mode requested
85 # init depending on the log mode requested
87 isfile = os.path.isfile
86 isfile = os.path.isfile
88 logmode = self.logmode
87 logmode = self.logmode
89
88
90 if logmode == 'append':
89 if logmode == 'append':
91 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
90 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
92
91
93 elif logmode == 'backup':
92 elif logmode == 'backup':
94 if isfile(self.logfname):
93 if isfile(self.logfname):
95 backup_logname = self.logfname+'~'
94 backup_logname = self.logfname+'~'
96 # Manually remove any old backup, since os.rename may fail
95 # Manually remove any old backup, since os.rename may fail
97 # under Windows.
96 # under Windows.
98 if isfile(backup_logname):
97 if isfile(backup_logname):
99 os.remove(backup_logname)
98 os.remove(backup_logname)
100 os.rename(self.logfname,backup_logname)
99 os.rename(self.logfname,backup_logname)
101 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
100 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
102
101
103 elif logmode == 'global':
102 elif logmode == 'global':
104 self.logfname = os.path.join(self.home_dir,self.logfname)
103 self.logfname = os.path.join(self.home_dir,self.logfname)
105 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
104 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
106
105
107 elif logmode == 'over':
106 elif logmode == 'over':
108 if isfile(self.logfname):
107 if isfile(self.logfname):
109 os.remove(self.logfname)
108 os.remove(self.logfname)
110 self.logfile = io.open(self.logfname,'w', encoding='utf-8')
109 self.logfile = io.open(self.logfname,'w', encoding='utf-8')
111
110
112 elif logmode == 'rotate':
111 elif logmode == 'rotate':
113 if isfile(self.logfname):
112 if isfile(self.logfname):
114 if isfile(self.logfname+'.001~'):
113 if isfile(self.logfname+'.001~'):
115 old = glob.glob(self.logfname+'.*~')
114 old = glob.glob(self.logfname+'.*~')
116 old.sort()
115 old.sort()
117 old.reverse()
116 old.reverse()
118 for f in old:
117 for f in old:
119 root, ext = os.path.splitext(f)
118 root, ext = os.path.splitext(f)
120 num = int(ext[1:-1])+1
119 num = int(ext[1:-1])+1
121 os.rename(f, root+'.'+repr(num).zfill(3)+'~')
120 os.rename(f, root+'.'+repr(num).zfill(3)+'~')
122 os.rename(self.logfname, self.logfname+'.001~')
121 os.rename(self.logfname, self.logfname+'.001~')
123 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
122 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
124
123
125 if logmode != 'append':
124 if logmode != 'append':
126 self.logfile.write(self.loghead)
125 self.logfile.write(self.loghead)
127
126
128 self.logfile.flush()
127 self.logfile.flush()
129 self.log_active = True
128 self.log_active = True
130
129
131 def switch_log(self,val):
130 def switch_log(self,val):
132 """Switch logging on/off. val should be ONLY a boolean."""
131 """Switch logging on/off. val should be ONLY a boolean."""
133
132
134 if val not in [False,True,0,1]:
133 if val not in [False,True,0,1]:
135 raise ValueError('Call switch_log ONLY with a boolean argument, '
134 raise ValueError('Call switch_log ONLY with a boolean argument, '
136 'not with: %s' % val)
135 'not with: %s' % val)
137
136
138 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
139
138
140 if self.logfile is None:
139 if self.logfile is None:
141 print("""
140 print("""
142 Logging hasn't been started yet (use logstart for that).
141 Logging hasn't been started yet (use logstart for that).
143
142
144 %logon/%logoff are for temporarily starting and stopping logging for a logfile
143 %logon/%logoff are for temporarily starting and stopping logging for a logfile
145 which already exists. But you must first start the logging process with
144 which already exists. But you must first start the logging process with
146 %logstart (optionally giving a logfile name).""")
145 %logstart (optionally giving a logfile name).""")
147
146
148 else:
147 else:
149 if self.log_active == val:
148 if self.log_active == val:
150 print('Logging is already',label[val])
149 print('Logging is already',label[val])
151 else:
150 else:
152 print('Switching logging',label[val])
151 print('Switching logging',label[val])
153 self.log_active = not self.log_active
152 self.log_active = not self.log_active
154 self.log_active_out = self.log_active
153 self.log_active_out = self.log_active
155
154
156 def logstate(self):
155 def logstate(self):
157 """Print a status message about the logger."""
156 """Print a status message about the logger."""
158 if self.logfile is None:
157 if self.logfile is None:
159 print('Logging has not been activated.')
158 print('Logging has not been activated.')
160 else:
159 else:
161 state = self.log_active and 'active' or 'temporarily suspended'
160 state = self.log_active and 'active' or 'temporarily suspended'
162 print('Filename :', self.logfname)
161 print('Filename :', self.logfname)
163 print('Mode :', self.logmode)
162 print('Mode :', self.logmode)
164 print('Output logging :', self.log_output)
163 print('Output logging :', self.log_output)
165 print('Raw input log :', self.log_raw_input)
164 print('Raw input log :', self.log_raw_input)
166 print('Timestamping :', self.timestamp)
165 print('Timestamping :', self.timestamp)
167 print('State :', state)
166 print('State :', state)
168
167
169 def log(self, line_mod, line_ori):
168 def log(self, line_mod, line_ori):
170 """Write the sources to a log.
169 """Write the sources to a log.
171
170
172 Inputs:
171 Inputs:
173
172
174 - line_mod: possibly modified input, such as the transformations made
173 - line_mod: possibly modified input, such as the transformations made
175 by input prefilters or input handlers of various kinds. This should
174 by input prefilters or input handlers of various kinds. This should
176 always be valid Python.
175 always be valid Python.
177
176
178 - line_ori: unmodified input line from the user. This is not
177 - line_ori: unmodified input line from the user. This is not
179 necessarily valid Python.
178 necessarily valid Python.
180 """
179 """
181
180
182 # Write the log line, but decide which one according to the
181 # Write the log line, but decide which one according to the
183 # log_raw_input flag, set when the log is started.
182 # log_raw_input flag, set when the log is started.
184 if self.log_raw_input:
183 if self.log_raw_input:
185 self.log_write(line_ori)
184 self.log_write(line_ori)
186 else:
185 else:
187 self.log_write(line_mod)
186 self.log_write(line_mod)
188
187
189 def log_write(self, data, kind='input'):
188 def log_write(self, data, kind='input'):
190 """Write data to the log file, if active"""
189 """Write data to the log file, if active"""
191
190
192 #print 'data: %r' % data # dbg
191 #print 'data: %r' % data # dbg
193 if self.log_active and data:
192 if self.log_active and data:
194 write = self.logfile.write
193 write = self.logfile.write
195 if kind=='input':
194 if kind=='input':
196 if self.timestamp:
195 if self.timestamp:
197 write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
196 write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
198 time.localtime())))
197 time.localtime())))
199 write(data)
198 write(data)
200 elif kind=='output' and self.log_output:
199 elif kind=='output' and self.log_output:
201 odata = u'\n'.join([u'#[Out]# %s' % s
200 odata = u'\n'.join([u'#[Out]# %s' % s
202 for s in data.splitlines()])
201 for s in data.splitlines()])
203 write(u'%s\n' % odata)
202 write(u'%s\n' % odata)
204 self.logfile.flush()
203 self.logfile.flush()
205
204
206 def logstop(self):
205 def logstop(self):
207 """Fully stop logging and close log file.
206 """Fully stop logging and close log file.
208
207
209 In order to start logging again, a new logstart() call needs to be
208 In order to start logging again, a new logstart() call needs to be
210 made, possibly (though not necessarily) with a new filename, mode and
209 made, possibly (though not necessarily) with a new filename, mode and
211 other options."""
210 other options."""
212
211
213 if self.logfile is not None:
212 if self.logfile is not None:
214 self.logfile.close()
213 self.logfile.close()
215 self.logfile = None
214 self.logfile = None
216 else:
215 else:
217 print("Logging hadn't been started.")
216 print("Logging hadn't been started.")
218 self.log_active = False
217 self.log_active = False
219
218
220 # For backwards compatibility, in case anyone was using this.
219 # For backwards compatibility, in case anyone was using this.
221 close_log = logstop
220 close_log = logstop
@@ -1,680 +1,679 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4 from __future__ import print_function
5
4
6 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
9 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
10
9
11 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
14
13
15 import os
14 import os
16 import re
15 import re
17 import sys
16 import sys
18 import types
17 import types
19 from getopt import getopt, GetoptError
18 from getopt import getopt, GetoptError
20
19
21 from traitlets.config.configurable import Configurable
20 from traitlets.config.configurable import Configurable
22 from IPython.core import oinspect
21 from IPython.core import oinspect
23 from IPython.core.error import UsageError
22 from IPython.core.error import UsageError
24 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
23 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
25 from decorator import decorator
24 from decorator import decorator
26 from IPython.utils.ipstruct import Struct
25 from IPython.utils.ipstruct import Struct
27 from IPython.utils.process import arg_split
26 from IPython.utils.process import arg_split
28 from IPython.utils.py3compat import string_types, iteritems
27 from IPython.utils.py3compat import string_types, iteritems
29 from IPython.utils.text import dedent
28 from IPython.utils.text import dedent
30 from traitlets import Bool, Dict, Instance, observe
29 from traitlets import Bool, Dict, Instance, observe
31 from logging import error
30 from logging import error
32
31
33 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
34 # Globals
33 # Globals
35 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
36
35
37 # A dict we'll use for each class that has magics, used as temporary storage to
36 # A dict we'll use for each class that has magics, used as temporary storage to
38 # pass information between the @line/cell_magic method decorators and the
37 # pass information between the @line/cell_magic method decorators and the
39 # @magics_class class decorator, because the method decorators have no
38 # @magics_class class decorator, because the method decorators have no
40 # access to the class when they run. See for more details:
39 # access to the class when they run. See for more details:
41 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
40 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
42
41
43 magics = dict(line={}, cell={})
42 magics = dict(line={}, cell={})
44
43
45 magic_kinds = ('line', 'cell')
44 magic_kinds = ('line', 'cell')
46 magic_spec = ('line', 'cell', 'line_cell')
45 magic_spec = ('line', 'cell', 'line_cell')
47 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
46 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
48
47
49 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
50 # Utility classes and functions
49 # Utility classes and functions
51 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
52
51
53 class Bunch: pass
52 class Bunch: pass
54
53
55
54
56 def on_off(tag):
55 def on_off(tag):
57 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 return ['OFF','ON'][tag]
57 return ['OFF','ON'][tag]
59
58
60
59
61 def compress_dhist(dh):
60 def compress_dhist(dh):
62 """Compress a directory history into a new one with at most 20 entries.
61 """Compress a directory history into a new one with at most 20 entries.
63
62
64 Return a new list made from the first and last 10 elements of dhist after
63 Return a new list made from the first and last 10 elements of dhist after
65 removal of duplicates.
64 removal of duplicates.
66 """
65 """
67 head, tail = dh[:-10], dh[-10:]
66 head, tail = dh[:-10], dh[-10:]
68
67
69 newhead = []
68 newhead = []
70 done = set()
69 done = set()
71 for h in head:
70 for h in head:
72 if h in done:
71 if h in done:
73 continue
72 continue
74 newhead.append(h)
73 newhead.append(h)
75 done.add(h)
74 done.add(h)
76
75
77 return newhead + tail
76 return newhead + tail
78
77
79
78
80 def needs_local_scope(func):
79 def needs_local_scope(func):
81 """Decorator to mark magic functions which need to local scope to run."""
80 """Decorator to mark magic functions which need to local scope to run."""
82 func.needs_local_scope = True
81 func.needs_local_scope = True
83 return func
82 return func
84
83
85 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
86 # Class and method decorators for registering magics
85 # Class and method decorators for registering magics
87 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
88
87
89 def magics_class(cls):
88 def magics_class(cls):
90 """Class decorator for all subclasses of the main Magics class.
89 """Class decorator for all subclasses of the main Magics class.
91
90
92 Any class that subclasses Magics *must* also apply this decorator, to
91 Any class that subclasses Magics *must* also apply this decorator, to
93 ensure that all the methods that have been decorated as line/cell magics
92 ensure that all the methods that have been decorated as line/cell magics
94 get correctly registered in the class instance. This is necessary because
93 get correctly registered in the class instance. This is necessary because
95 when method decorators run, the class does not exist yet, so they
94 when method decorators run, the class does not exist yet, so they
96 temporarily store their information into a module global. Application of
95 temporarily store their information into a module global. Application of
97 this class decorator copies that global data to the class instance and
96 this class decorator copies that global data to the class instance and
98 clears the global.
97 clears the global.
99
98
100 Obviously, this mechanism is not thread-safe, which means that the
99 Obviously, this mechanism is not thread-safe, which means that the
101 *creation* of subclasses of Magic should only be done in a single-thread
100 *creation* of subclasses of Magic should only be done in a single-thread
102 context. Instantiation of the classes has no restrictions. Given that
101 context. Instantiation of the classes has no restrictions. Given that
103 these classes are typically created at IPython startup time and before user
102 these classes are typically created at IPython startup time and before user
104 application code becomes active, in practice this should not pose any
103 application code becomes active, in practice this should not pose any
105 problems.
104 problems.
106 """
105 """
107 cls.registered = True
106 cls.registered = True
108 cls.magics = dict(line = magics['line'],
107 cls.magics = dict(line = magics['line'],
109 cell = magics['cell'])
108 cell = magics['cell'])
110 magics['line'] = {}
109 magics['line'] = {}
111 magics['cell'] = {}
110 magics['cell'] = {}
112 return cls
111 return cls
113
112
114
113
115 def record_magic(dct, magic_kind, magic_name, func):
114 def record_magic(dct, magic_kind, magic_name, func):
116 """Utility function to store a function as a magic of a specific kind.
115 """Utility function to store a function as a magic of a specific kind.
117
116
118 Parameters
117 Parameters
119 ----------
118 ----------
120 dct : dict
119 dct : dict
121 A dictionary with 'line' and 'cell' subdicts.
120 A dictionary with 'line' and 'cell' subdicts.
122
121
123 magic_kind : str
122 magic_kind : str
124 Kind of magic to be stored.
123 Kind of magic to be stored.
125
124
126 magic_name : str
125 magic_name : str
127 Key to store the magic as.
126 Key to store the magic as.
128
127
129 func : function
128 func : function
130 Callable object to store.
129 Callable object to store.
131 """
130 """
132 if magic_kind == 'line_cell':
131 if magic_kind == 'line_cell':
133 dct['line'][magic_name] = dct['cell'][magic_name] = func
132 dct['line'][magic_name] = dct['cell'][magic_name] = func
134 else:
133 else:
135 dct[magic_kind][magic_name] = func
134 dct[magic_kind][magic_name] = func
136
135
137
136
138 def validate_type(magic_kind):
137 def validate_type(magic_kind):
139 """Ensure that the given magic_kind is valid.
138 """Ensure that the given magic_kind is valid.
140
139
141 Check that the given magic_kind is one of the accepted spec types (stored
140 Check that the given magic_kind is one of the accepted spec types (stored
142 in the global `magic_spec`), raise ValueError otherwise.
141 in the global `magic_spec`), raise ValueError otherwise.
143 """
142 """
144 if magic_kind not in magic_spec:
143 if magic_kind not in magic_spec:
145 raise ValueError('magic_kind must be one of %s, %s given' %
144 raise ValueError('magic_kind must be one of %s, %s given' %
146 magic_kinds, magic_kind)
145 magic_kinds, magic_kind)
147
146
148
147
149 # The docstrings for the decorator below will be fairly similar for the two
148 # The docstrings for the decorator below will be fairly similar for the two
150 # types (method and function), so we generate them here once and reuse the
149 # types (method and function), so we generate them here once and reuse the
151 # templates below.
150 # templates below.
152 _docstring_template = \
151 _docstring_template = \
153 """Decorate the given {0} as {1} magic.
152 """Decorate the given {0} as {1} magic.
154
153
155 The decorator can be used with or without arguments, as follows.
154 The decorator can be used with or without arguments, as follows.
156
155
157 i) without arguments: it will create a {1} magic named as the {0} being
156 i) without arguments: it will create a {1} magic named as the {0} being
158 decorated::
157 decorated::
159
158
160 @deco
159 @deco
161 def foo(...)
160 def foo(...)
162
161
163 will create a {1} magic named `foo`.
162 will create a {1} magic named `foo`.
164
163
165 ii) with one string argument: which will be used as the actual name of the
164 ii) with one string argument: which will be used as the actual name of the
166 resulting magic::
165 resulting magic::
167
166
168 @deco('bar')
167 @deco('bar')
169 def foo(...)
168 def foo(...)
170
169
171 will create a {1} magic named `bar`.
170 will create a {1} magic named `bar`.
172 """
171 """
173
172
174 # These two are decorator factories. While they are conceptually very similar,
173 # These two are decorator factories. While they are conceptually very similar,
175 # there are enough differences in the details that it's simpler to have them
174 # there are enough differences in the details that it's simpler to have them
176 # written as completely standalone functions rather than trying to share code
175 # written as completely standalone functions rather than trying to share code
177 # and make a single one with convoluted logic.
176 # and make a single one with convoluted logic.
178
177
179 def _method_magic_marker(magic_kind):
178 def _method_magic_marker(magic_kind):
180 """Decorator factory for methods in Magics subclasses.
179 """Decorator factory for methods in Magics subclasses.
181 """
180 """
182
181
183 validate_type(magic_kind)
182 validate_type(magic_kind)
184
183
185 # This is a closure to capture the magic_kind. We could also use a class,
184 # This is a closure to capture the magic_kind. We could also use a class,
186 # but it's overkill for just that one bit of state.
185 # but it's overkill for just that one bit of state.
187 def magic_deco(arg):
186 def magic_deco(arg):
188 call = lambda f, *a, **k: f(*a, **k)
187 call = lambda f, *a, **k: f(*a, **k)
189
188
190 if callable(arg):
189 if callable(arg):
191 # "Naked" decorator call (just @foo, no args)
190 # "Naked" decorator call (just @foo, no args)
192 func = arg
191 func = arg
193 name = func.__name__
192 name = func.__name__
194 retval = decorator(call, func)
193 retval = decorator(call, func)
195 record_magic(magics, magic_kind, name, name)
194 record_magic(magics, magic_kind, name, name)
196 elif isinstance(arg, string_types):
195 elif isinstance(arg, string_types):
197 # Decorator called with arguments (@foo('bar'))
196 # Decorator called with arguments (@foo('bar'))
198 name = arg
197 name = arg
199 def mark(func, *a, **kw):
198 def mark(func, *a, **kw):
200 record_magic(magics, magic_kind, name, func.__name__)
199 record_magic(magics, magic_kind, name, func.__name__)
201 return decorator(call, func)
200 return decorator(call, func)
202 retval = mark
201 retval = mark
203 else:
202 else:
204 raise TypeError("Decorator can only be called with "
203 raise TypeError("Decorator can only be called with "
205 "string or function")
204 "string or function")
206 return retval
205 return retval
207
206
208 # Ensure the resulting decorator has a usable docstring
207 # Ensure the resulting decorator has a usable docstring
209 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
210 return magic_deco
209 return magic_deco
211
210
212
211
213 def _function_magic_marker(magic_kind):
212 def _function_magic_marker(magic_kind):
214 """Decorator factory for standalone functions.
213 """Decorator factory for standalone functions.
215 """
214 """
216 validate_type(magic_kind)
215 validate_type(magic_kind)
217
216
218 # This is a closure to capture the magic_kind. We could also use a class,
217 # This is a closure to capture the magic_kind. We could also use a class,
219 # but it's overkill for just that one bit of state.
218 # but it's overkill for just that one bit of state.
220 def magic_deco(arg):
219 def magic_deco(arg):
221 call = lambda f, *a, **k: f(*a, **k)
220 call = lambda f, *a, **k: f(*a, **k)
222
221
223 # Find get_ipython() in the caller's namespace
222 # Find get_ipython() in the caller's namespace
224 caller = sys._getframe(1)
223 caller = sys._getframe(1)
225 for ns in ['f_locals', 'f_globals', 'f_builtins']:
224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
226 get_ipython = getattr(caller, ns).get('get_ipython')
225 get_ipython = getattr(caller, ns).get('get_ipython')
227 if get_ipython is not None:
226 if get_ipython is not None:
228 break
227 break
229 else:
228 else:
230 raise NameError('Decorator can only run in context where '
229 raise NameError('Decorator can only run in context where '
231 '`get_ipython` exists')
230 '`get_ipython` exists')
232
231
233 ip = get_ipython()
232 ip = get_ipython()
234
233
235 if callable(arg):
234 if callable(arg):
236 # "Naked" decorator call (just @foo, no args)
235 # "Naked" decorator call (just @foo, no args)
237 func = arg
236 func = arg
238 name = func.__name__
237 name = func.__name__
239 ip.register_magic_function(func, magic_kind, name)
238 ip.register_magic_function(func, magic_kind, name)
240 retval = decorator(call, func)
239 retval = decorator(call, func)
241 elif isinstance(arg, string_types):
240 elif isinstance(arg, string_types):
242 # Decorator called with arguments (@foo('bar'))
241 # Decorator called with arguments (@foo('bar'))
243 name = arg
242 name = arg
244 def mark(func, *a, **kw):
243 def mark(func, *a, **kw):
245 ip.register_magic_function(func, magic_kind, name)
244 ip.register_magic_function(func, magic_kind, name)
246 return decorator(call, func)
245 return decorator(call, func)
247 retval = mark
246 retval = mark
248 else:
247 else:
249 raise TypeError("Decorator can only be called with "
248 raise TypeError("Decorator can only be called with "
250 "string or function")
249 "string or function")
251 return retval
250 return retval
252
251
253 # Ensure the resulting decorator has a usable docstring
252 # Ensure the resulting decorator has a usable docstring
254 ds = _docstring_template.format('function', magic_kind)
253 ds = _docstring_template.format('function', magic_kind)
255
254
256 ds += dedent("""
255 ds += dedent("""
257 Note: this decorator can only be used in a context where IPython is already
256 Note: this decorator can only be used in a context where IPython is already
258 active, so that the `get_ipython()` call succeeds. You can therefore use
257 active, so that the `get_ipython()` call succeeds. You can therefore use
259 it in your startup files loaded after IPython initializes, but *not* in the
258 it in your startup files loaded after IPython initializes, but *not* in the
260 IPython configuration file itself, which is executed before IPython is
259 IPython configuration file itself, which is executed before IPython is
261 fully up and running. Any file located in the `startup` subdirectory of
260 fully up and running. Any file located in the `startup` subdirectory of
262 your configuration profile will be OK in this sense.
261 your configuration profile will be OK in this sense.
263 """)
262 """)
264
263
265 magic_deco.__doc__ = ds
264 magic_deco.__doc__ = ds
266 return magic_deco
265 return magic_deco
267
266
268
267
269 # Create the actual decorators for public use
268 # Create the actual decorators for public use
270
269
271 # These three are used to decorate methods in class definitions
270 # These three are used to decorate methods in class definitions
272 line_magic = _method_magic_marker('line')
271 line_magic = _method_magic_marker('line')
273 cell_magic = _method_magic_marker('cell')
272 cell_magic = _method_magic_marker('cell')
274 line_cell_magic = _method_magic_marker('line_cell')
273 line_cell_magic = _method_magic_marker('line_cell')
275
274
276 # These three decorate standalone functions and perform the decoration
275 # These three decorate standalone functions and perform the decoration
277 # immediately. They can only run where get_ipython() works
276 # immediately. They can only run where get_ipython() works
278 register_line_magic = _function_magic_marker('line')
277 register_line_magic = _function_magic_marker('line')
279 register_cell_magic = _function_magic_marker('cell')
278 register_cell_magic = _function_magic_marker('cell')
280 register_line_cell_magic = _function_magic_marker('line_cell')
279 register_line_cell_magic = _function_magic_marker('line_cell')
281
280
282 #-----------------------------------------------------------------------------
281 #-----------------------------------------------------------------------------
283 # Core Magic classes
282 # Core Magic classes
284 #-----------------------------------------------------------------------------
283 #-----------------------------------------------------------------------------
285
284
286 class MagicsManager(Configurable):
285 class MagicsManager(Configurable):
287 """Object that handles all magic-related functionality for IPython.
286 """Object that handles all magic-related functionality for IPython.
288 """
287 """
289 # Non-configurable class attributes
288 # Non-configurable class attributes
290
289
291 # A two-level dict, first keyed by magic type, then by magic function, and
290 # A two-level dict, first keyed by magic type, then by magic function, and
292 # holding the actual callable object as value. This is the dict used for
291 # holding the actual callable object as value. This is the dict used for
293 # magic function dispatch
292 # magic function dispatch
294 magics = Dict()
293 magics = Dict()
295
294
296 # A registry of the original objects that we've been given holding magics.
295 # A registry of the original objects that we've been given holding magics.
297 registry = Dict()
296 registry = Dict()
298
297
299 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
298 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
300
299
301 auto_magic = Bool(True, help=
300 auto_magic = Bool(True, help=
302 "Automatically call line magics without requiring explicit % prefix"
301 "Automatically call line magics without requiring explicit % prefix"
303 ).tag(config=True)
302 ).tag(config=True)
304 @observe('auto_magic')
303 @observe('auto_magic')
305 def _auto_magic_changed(self, change):
304 def _auto_magic_changed(self, change):
306 self.shell.automagic = change['new']
305 self.shell.automagic = change['new']
307
306
308 _auto_status = [
307 _auto_status = [
309 'Automagic is OFF, % prefix IS needed for line magics.',
308 'Automagic is OFF, % prefix IS needed for line magics.',
310 'Automagic is ON, % prefix IS NOT needed for line magics.']
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
311
310
312 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
311 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
313
312
314 def __init__(self, shell=None, config=None, user_magics=None, **traits):
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
315
314
316 super(MagicsManager, self).__init__(shell=shell, config=config,
315 super(MagicsManager, self).__init__(shell=shell, config=config,
317 user_magics=user_magics, **traits)
316 user_magics=user_magics, **traits)
318 self.magics = dict(line={}, cell={})
317 self.magics = dict(line={}, cell={})
319 # Let's add the user_magics to the registry for uniformity, so *all*
318 # Let's add the user_magics to the registry for uniformity, so *all*
320 # registered magic containers can be found there.
319 # registered magic containers can be found there.
321 self.registry[user_magics.__class__.__name__] = user_magics
320 self.registry[user_magics.__class__.__name__] = user_magics
322
321
323 def auto_status(self):
322 def auto_status(self):
324 """Return descriptive string with automagic status."""
323 """Return descriptive string with automagic status."""
325 return self._auto_status[self.auto_magic]
324 return self._auto_status[self.auto_magic]
326
325
327 def lsmagic(self):
326 def lsmagic(self):
328 """Return a dict of currently available magic functions.
327 """Return a dict of currently available magic functions.
329
328
330 The return dict has the keys 'line' and 'cell', corresponding to the
329 The return dict has the keys 'line' and 'cell', corresponding to the
331 two types of magics we support. Each value is a list of names.
330 two types of magics we support. Each value is a list of names.
332 """
331 """
333 return self.magics
332 return self.magics
334
333
335 def lsmagic_docs(self, brief=False, missing=''):
334 def lsmagic_docs(self, brief=False, missing=''):
336 """Return dict of documentation of magic functions.
335 """Return dict of documentation of magic functions.
337
336
338 The return dict has the keys 'line' and 'cell', corresponding to the
337 The return dict has the keys 'line' and 'cell', corresponding to the
339 two types of magics we support. Each value is a dict keyed by magic
338 two types of magics we support. Each value is a dict keyed by magic
340 name whose value is the function docstring. If a docstring is
339 name whose value is the function docstring. If a docstring is
341 unavailable, the value of `missing` is used instead.
340 unavailable, the value of `missing` is used instead.
342
341
343 If brief is True, only the first line of each docstring will be returned.
342 If brief is True, only the first line of each docstring will be returned.
344 """
343 """
345 docs = {}
344 docs = {}
346 for m_type in self.magics:
345 for m_type in self.magics:
347 m_docs = {}
346 m_docs = {}
348 for m_name, m_func in iteritems(self.magics[m_type]):
347 for m_name, m_func in iteritems(self.magics[m_type]):
349 if m_func.__doc__:
348 if m_func.__doc__:
350 if brief:
349 if brief:
351 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
350 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
352 else:
351 else:
353 m_docs[m_name] = m_func.__doc__.rstrip()
352 m_docs[m_name] = m_func.__doc__.rstrip()
354 else:
353 else:
355 m_docs[m_name] = missing
354 m_docs[m_name] = missing
356 docs[m_type] = m_docs
355 docs[m_type] = m_docs
357 return docs
356 return docs
358
357
359 def register(self, *magic_objects):
358 def register(self, *magic_objects):
360 """Register one or more instances of Magics.
359 """Register one or more instances of Magics.
361
360
362 Take one or more classes or instances of classes that subclass the main
361 Take one or more classes or instances of classes that subclass the main
363 `core.Magic` class, and register them with IPython to use the magic
362 `core.Magic` class, and register them with IPython to use the magic
364 functions they provide. The registration process will then ensure that
363 functions they provide. The registration process will then ensure that
365 any methods that have decorated to provide line and/or cell magics will
364 any methods that have decorated to provide line and/or cell magics will
366 be recognized with the `%x`/`%%x` syntax as a line/cell magic
365 be recognized with the `%x`/`%%x` syntax as a line/cell magic
367 respectively.
366 respectively.
368
367
369 If classes are given, they will be instantiated with the default
368 If classes are given, they will be instantiated with the default
370 constructor. If your classes need a custom constructor, you should
369 constructor. If your classes need a custom constructor, you should
371 instanitate them first and pass the instance.
370 instanitate them first and pass the instance.
372
371
373 The provided arguments can be an arbitrary mix of classes and instances.
372 The provided arguments can be an arbitrary mix of classes and instances.
374
373
375 Parameters
374 Parameters
376 ----------
375 ----------
377 magic_objects : one or more classes or instances
376 magic_objects : one or more classes or instances
378 """
377 """
379 # Start by validating them to ensure they have all had their magic
378 # Start by validating them to ensure they have all had their magic
380 # methods registered at the instance level
379 # methods registered at the instance level
381 for m in magic_objects:
380 for m in magic_objects:
382 if not m.registered:
381 if not m.registered:
383 raise ValueError("Class of magics %r was constructed without "
382 raise ValueError("Class of magics %r was constructed without "
384 "the @register_magics class decorator")
383 "the @register_magics class decorator")
385 if isinstance(m, type):
384 if isinstance(m, type):
386 # If we're given an uninstantiated class
385 # If we're given an uninstantiated class
387 m = m(shell=self.shell)
386 m = m(shell=self.shell)
388
387
389 # Now that we have an instance, we can register it and update the
388 # Now that we have an instance, we can register it and update the
390 # table of callables
389 # table of callables
391 self.registry[m.__class__.__name__] = m
390 self.registry[m.__class__.__name__] = m
392 for mtype in magic_kinds:
391 for mtype in magic_kinds:
393 self.magics[mtype].update(m.magics[mtype])
392 self.magics[mtype].update(m.magics[mtype])
394
393
395 def register_function(self, func, magic_kind='line', magic_name=None):
394 def register_function(self, func, magic_kind='line', magic_name=None):
396 """Expose a standalone function as magic function for IPython.
395 """Expose a standalone function as magic function for IPython.
397
396
398 This will create an IPython magic (line, cell or both) from a
397 This will create an IPython magic (line, cell or both) from a
399 standalone function. The functions should have the following
398 standalone function. The functions should have the following
400 signatures:
399 signatures:
401
400
402 * For line magics: `def f(line)`
401 * For line magics: `def f(line)`
403 * For cell magics: `def f(line, cell)`
402 * For cell magics: `def f(line, cell)`
404 * For a function that does both: `def f(line, cell=None)`
403 * For a function that does both: `def f(line, cell=None)`
405
404
406 In the latter case, the function will be called with `cell==None` when
405 In the latter case, the function will be called with `cell==None` when
407 invoked as `%f`, and with cell as a string when invoked as `%%f`.
406 invoked as `%f`, and with cell as a string when invoked as `%%f`.
408
407
409 Parameters
408 Parameters
410 ----------
409 ----------
411 func : callable
410 func : callable
412 Function to be registered as a magic.
411 Function to be registered as a magic.
413
412
414 magic_kind : str
413 magic_kind : str
415 Kind of magic, one of 'line', 'cell' or 'line_cell'
414 Kind of magic, one of 'line', 'cell' or 'line_cell'
416
415
417 magic_name : optional str
416 magic_name : optional str
418 If given, the name the magic will have in the IPython namespace. By
417 If given, the name the magic will have in the IPython namespace. By
419 default, the name of the function itself is used.
418 default, the name of the function itself is used.
420 """
419 """
421
420
422 # Create the new method in the user_magics and register it in the
421 # Create the new method in the user_magics and register it in the
423 # global table
422 # global table
424 validate_type(magic_kind)
423 validate_type(magic_kind)
425 magic_name = func.__name__ if magic_name is None else magic_name
424 magic_name = func.__name__ if magic_name is None else magic_name
426 setattr(self.user_magics, magic_name, func)
425 setattr(self.user_magics, magic_name, func)
427 record_magic(self.magics, magic_kind, magic_name, func)
426 record_magic(self.magics, magic_kind, magic_name, func)
428
427
429 def register_alias(self, alias_name, magic_name, magic_kind='line'):
428 def register_alias(self, alias_name, magic_name, magic_kind='line'):
430 """Register an alias to a magic function.
429 """Register an alias to a magic function.
431
430
432 The alias is an instance of :class:`MagicAlias`, which holds the
431 The alias is an instance of :class:`MagicAlias`, which holds the
433 name and kind of the magic it should call. Binding is done at
432 name and kind of the magic it should call. Binding is done at
434 call time, so if the underlying magic function is changed the alias
433 call time, so if the underlying magic function is changed the alias
435 will call the new function.
434 will call the new function.
436
435
437 Parameters
436 Parameters
438 ----------
437 ----------
439 alias_name : str
438 alias_name : str
440 The name of the magic to be registered.
439 The name of the magic to be registered.
441
440
442 magic_name : str
441 magic_name : str
443 The name of an existing magic.
442 The name of an existing magic.
444
443
445 magic_kind : str
444 magic_kind : str
446 Kind of magic, one of 'line' or 'cell'
445 Kind of magic, one of 'line' or 'cell'
447 """
446 """
448
447
449 # `validate_type` is too permissive, as it allows 'line_cell'
448 # `validate_type` is too permissive, as it allows 'line_cell'
450 # which we do not handle.
449 # which we do not handle.
451 if magic_kind not in magic_kinds:
450 if magic_kind not in magic_kinds:
452 raise ValueError('magic_kind must be one of %s, %s given' %
451 raise ValueError('magic_kind must be one of %s, %s given' %
453 magic_kinds, magic_kind)
452 magic_kinds, magic_kind)
454
453
455 alias = MagicAlias(self.shell, magic_name, magic_kind)
454 alias = MagicAlias(self.shell, magic_name, magic_kind)
456 setattr(self.user_magics, alias_name, alias)
455 setattr(self.user_magics, alias_name, alias)
457 record_magic(self.magics, magic_kind, alias_name, alias)
456 record_magic(self.magics, magic_kind, alias_name, alias)
458
457
459 # Key base class that provides the central functionality for magics.
458 # Key base class that provides the central functionality for magics.
460
459
461
460
462 class Magics(Configurable):
461 class Magics(Configurable):
463 """Base class for implementing magic functions.
462 """Base class for implementing magic functions.
464
463
465 Shell functions which can be reached as %function_name. All magic
464 Shell functions which can be reached as %function_name. All magic
466 functions should accept a string, which they can parse for their own
465 functions should accept a string, which they can parse for their own
467 needs. This can make some functions easier to type, eg `%cd ../`
466 needs. This can make some functions easier to type, eg `%cd ../`
468 vs. `%cd("../")`
467 vs. `%cd("../")`
469
468
470 Classes providing magic functions need to subclass this class, and they
469 Classes providing magic functions need to subclass this class, and they
471 MUST:
470 MUST:
472
471
473 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
472 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
474 individual methods as magic functions, AND
473 individual methods as magic functions, AND
475
474
476 - Use the class decorator `@magics_class` to ensure that the magic
475 - Use the class decorator `@magics_class` to ensure that the magic
477 methods are properly registered at the instance level upon instance
476 methods are properly registered at the instance level upon instance
478 initialization.
477 initialization.
479
478
480 See :mod:`magic_functions` for examples of actual implementation classes.
479 See :mod:`magic_functions` for examples of actual implementation classes.
481 """
480 """
482 # Dict holding all command-line options for each magic.
481 # Dict holding all command-line options for each magic.
483 options_table = None
482 options_table = None
484 # Dict for the mapping of magic names to methods, set by class decorator
483 # Dict for the mapping of magic names to methods, set by class decorator
485 magics = None
484 magics = None
486 # Flag to check that the class decorator was properly applied
485 # Flag to check that the class decorator was properly applied
487 registered = False
486 registered = False
488 # Instance of IPython shell
487 # Instance of IPython shell
489 shell = None
488 shell = None
490
489
491 def __init__(self, shell=None, **kwargs):
490 def __init__(self, shell=None, **kwargs):
492 if not(self.__class__.registered):
491 if not(self.__class__.registered):
493 raise ValueError('Magics subclass without registration - '
492 raise ValueError('Magics subclass without registration - '
494 'did you forget to apply @magics_class?')
493 'did you forget to apply @magics_class?')
495 if shell is not None:
494 if shell is not None:
496 if hasattr(shell, 'configurables'):
495 if hasattr(shell, 'configurables'):
497 shell.configurables.append(self)
496 shell.configurables.append(self)
498 if hasattr(shell, 'config'):
497 if hasattr(shell, 'config'):
499 kwargs.setdefault('parent', shell)
498 kwargs.setdefault('parent', shell)
500
499
501 self.shell = shell
500 self.shell = shell
502 self.options_table = {}
501 self.options_table = {}
503 # The method decorators are run when the instance doesn't exist yet, so
502 # The method decorators are run when the instance doesn't exist yet, so
504 # they can only record the names of the methods they are supposed to
503 # they can only record the names of the methods they are supposed to
505 # grab. Only now, that the instance exists, can we create the proper
504 # grab. Only now, that the instance exists, can we create the proper
506 # mapping to bound methods. So we read the info off the original names
505 # mapping to bound methods. So we read the info off the original names
507 # table and replace each method name by the actual bound method.
506 # table and replace each method name by the actual bound method.
508 # But we mustn't clobber the *class* mapping, in case of multiple instances.
507 # But we mustn't clobber the *class* mapping, in case of multiple instances.
509 class_magics = self.magics
508 class_magics = self.magics
510 self.magics = {}
509 self.magics = {}
511 for mtype in magic_kinds:
510 for mtype in magic_kinds:
512 tab = self.magics[mtype] = {}
511 tab = self.magics[mtype] = {}
513 cls_tab = class_magics[mtype]
512 cls_tab = class_magics[mtype]
514 for magic_name, meth_name in iteritems(cls_tab):
513 for magic_name, meth_name in iteritems(cls_tab):
515 if isinstance(meth_name, string_types):
514 if isinstance(meth_name, string_types):
516 # it's a method name, grab it
515 # it's a method name, grab it
517 tab[magic_name] = getattr(self, meth_name)
516 tab[magic_name] = getattr(self, meth_name)
518 else:
517 else:
519 # it's the real thing
518 # it's the real thing
520 tab[magic_name] = meth_name
519 tab[magic_name] = meth_name
521 # Configurable **needs** to be initiated at the end or the config
520 # Configurable **needs** to be initiated at the end or the config
522 # magics get screwed up.
521 # magics get screwed up.
523 super(Magics, self).__init__(**kwargs)
522 super(Magics, self).__init__(**kwargs)
524
523
525 def arg_err(self,func):
524 def arg_err(self,func):
526 """Print docstring if incorrect arguments were passed"""
525 """Print docstring if incorrect arguments were passed"""
527 print('Error in arguments:')
526 print('Error in arguments:')
528 print(oinspect.getdoc(func))
527 print(oinspect.getdoc(func))
529
528
530 def format_latex(self, strng):
529 def format_latex(self, strng):
531 """Format a string for latex inclusion."""
530 """Format a string for latex inclusion."""
532
531
533 # Characters that need to be escaped for latex:
532 # Characters that need to be escaped for latex:
534 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
533 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
535 # Magic command names as headers:
534 # Magic command names as headers:
536 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
535 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
537 re.MULTILINE)
536 re.MULTILINE)
538 # Magic commands
537 # Magic commands
539 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
538 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
540 re.MULTILINE)
539 re.MULTILINE)
541 # Paragraph continue
540 # Paragraph continue
542 par_re = re.compile(r'\\$',re.MULTILINE)
541 par_re = re.compile(r'\\$',re.MULTILINE)
543
542
544 # The "\n" symbol
543 # The "\n" symbol
545 newline_re = re.compile(r'\\n')
544 newline_re = re.compile(r'\\n')
546
545
547 # Now build the string for output:
546 # Now build the string for output:
548 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
547 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
549 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
548 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
550 strng)
549 strng)
551 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
550 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
552 strng = par_re.sub(r'\\\\',strng)
551 strng = par_re.sub(r'\\\\',strng)
553 strng = escape_re.sub(r'\\\1',strng)
552 strng = escape_re.sub(r'\\\1',strng)
554 strng = newline_re.sub(r'\\textbackslash{}n',strng)
553 strng = newline_re.sub(r'\\textbackslash{}n',strng)
555 return strng
554 return strng
556
555
557 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
556 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
558 """Parse options passed to an argument string.
557 """Parse options passed to an argument string.
559
558
560 The interface is similar to that of :func:`getopt.getopt`, but it
559 The interface is similar to that of :func:`getopt.getopt`, but it
561 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
560 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
562 and the stripped argument string still as a string.
561 and the stripped argument string still as a string.
563
562
564 arg_str is quoted as a true sys.argv vector by using shlex.split.
563 arg_str is quoted as a true sys.argv vector by using shlex.split.
565 This allows us to easily expand variables, glob files, quote
564 This allows us to easily expand variables, glob files, quote
566 arguments, etc.
565 arguments, etc.
567
566
568 Parameters
567 Parameters
569 ----------
568 ----------
570
569
571 arg_str : str
570 arg_str : str
572 The arguments to parse.
571 The arguments to parse.
573
572
574 opt_str : str
573 opt_str : str
575 The options specification.
574 The options specification.
576
575
577 mode : str, default 'string'
576 mode : str, default 'string'
578 If given as 'list', the argument string is returned as a list (split
577 If given as 'list', the argument string is returned as a list (split
579 on whitespace) instead of a string.
578 on whitespace) instead of a string.
580
579
581 list_all : bool, default False
580 list_all : bool, default False
582 Put all option values in lists. Normally only options
581 Put all option values in lists. Normally only options
583 appearing more than once are put in a list.
582 appearing more than once are put in a list.
584
583
585 posix : bool, default True
584 posix : bool, default True
586 Whether to split the input line in POSIX mode or not, as per the
585 Whether to split the input line in POSIX mode or not, as per the
587 conventions outlined in the :mod:`shlex` module from the standard
586 conventions outlined in the :mod:`shlex` module from the standard
588 library.
587 library.
589 """
588 """
590
589
591 # inject default options at the beginning of the input line
590 # inject default options at the beginning of the input line
592 caller = sys._getframe(1).f_code.co_name
591 caller = sys._getframe(1).f_code.co_name
593 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
592 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
594
593
595 mode = kw.get('mode','string')
594 mode = kw.get('mode','string')
596 if mode not in ['string','list']:
595 if mode not in ['string','list']:
597 raise ValueError('incorrect mode given: %s' % mode)
596 raise ValueError('incorrect mode given: %s' % mode)
598 # Get options
597 # Get options
599 list_all = kw.get('list_all',0)
598 list_all = kw.get('list_all',0)
600 posix = kw.get('posix', os.name == 'posix')
599 posix = kw.get('posix', os.name == 'posix')
601 strict = kw.get('strict', True)
600 strict = kw.get('strict', True)
602
601
603 # Check if we have more than one argument to warrant extra processing:
602 # Check if we have more than one argument to warrant extra processing:
604 odict = {} # Dictionary with options
603 odict = {} # Dictionary with options
605 args = arg_str.split()
604 args = arg_str.split()
606 if len(args) >= 1:
605 if len(args) >= 1:
607 # If the list of inputs only has 0 or 1 thing in it, there's no
606 # If the list of inputs only has 0 or 1 thing in it, there's no
608 # need to look for options
607 # need to look for options
609 argv = arg_split(arg_str, posix, strict)
608 argv = arg_split(arg_str, posix, strict)
610 # Do regular option processing
609 # Do regular option processing
611 try:
610 try:
612 opts,args = getopt(argv, opt_str, long_opts)
611 opts,args = getopt(argv, opt_str, long_opts)
613 except GetoptError as e:
612 except GetoptError as e:
614 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
613 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
615 " ".join(long_opts)))
614 " ".join(long_opts)))
616 for o,a in opts:
615 for o,a in opts:
617 if o.startswith('--'):
616 if o.startswith('--'):
618 o = o[2:]
617 o = o[2:]
619 else:
618 else:
620 o = o[1:]
619 o = o[1:]
621 try:
620 try:
622 odict[o].append(a)
621 odict[o].append(a)
623 except AttributeError:
622 except AttributeError:
624 odict[o] = [odict[o],a]
623 odict[o] = [odict[o],a]
625 except KeyError:
624 except KeyError:
626 if list_all:
625 if list_all:
627 odict[o] = [a]
626 odict[o] = [a]
628 else:
627 else:
629 odict[o] = a
628 odict[o] = a
630
629
631 # Prepare opts,args for return
630 # Prepare opts,args for return
632 opts = Struct(odict)
631 opts = Struct(odict)
633 if mode == 'string':
632 if mode == 'string':
634 args = ' '.join(args)
633 args = ' '.join(args)
635
634
636 return opts,args
635 return opts,args
637
636
638 def default_option(self, fn, optstr):
637 def default_option(self, fn, optstr):
639 """Make an entry in the options_table for fn, with value optstr"""
638 """Make an entry in the options_table for fn, with value optstr"""
640
639
641 if fn not in self.lsmagic():
640 if fn not in self.lsmagic():
642 error("%s is not a magic function" % fn)
641 error("%s is not a magic function" % fn)
643 self.options_table[fn] = optstr
642 self.options_table[fn] = optstr
644
643
645
644
646 class MagicAlias(object):
645 class MagicAlias(object):
647 """An alias to another magic function.
646 """An alias to another magic function.
648
647
649 An alias is determined by its magic name and magic kind. Lookup
648 An alias is determined by its magic name and magic kind. Lookup
650 is done at call time, so if the underlying magic changes the alias
649 is done at call time, so if the underlying magic changes the alias
651 will call the new function.
650 will call the new function.
652
651
653 Use the :meth:`MagicsManager.register_alias` method or the
652 Use the :meth:`MagicsManager.register_alias` method or the
654 `%alias_magic` magic function to create and register a new alias.
653 `%alias_magic` magic function to create and register a new alias.
655 """
654 """
656 def __init__(self, shell, magic_name, magic_kind):
655 def __init__(self, shell, magic_name, magic_kind):
657 self.shell = shell
656 self.shell = shell
658 self.magic_name = magic_name
657 self.magic_name = magic_name
659 self.magic_kind = magic_kind
658 self.magic_kind = magic_kind
660
659
661 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
660 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
662 self.__doc__ = "Alias for `%s`." % self.pretty_target
661 self.__doc__ = "Alias for `%s`." % self.pretty_target
663
662
664 self._in_call = False
663 self._in_call = False
665
664
666 def __call__(self, *args, **kwargs):
665 def __call__(self, *args, **kwargs):
667 """Call the magic alias."""
666 """Call the magic alias."""
668 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
667 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
669 if fn is None:
668 if fn is None:
670 raise UsageError("Magic `%s` not found." % self.pretty_target)
669 raise UsageError("Magic `%s` not found." % self.pretty_target)
671
670
672 # Protect against infinite recursion.
671 # Protect against infinite recursion.
673 if self._in_call:
672 if self._in_call:
674 raise UsageError("Infinite recursion detected; "
673 raise UsageError("Infinite recursion detected; "
675 "magic aliases cannot call themselves.")
674 "magic aliases cannot call themselves.")
676 self._in_call = True
675 self._in_call = True
677 try:
676 try:
678 return fn(*args, **kwargs)
677 return fn(*args, **kwargs)
679 finally:
678 finally:
680 self._in_call = False
679 self._in_call = False
@@ -1,130 +1,128 b''
1 """Implementation of magic functions that control various automatic behaviors.
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 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
7 #
5 #
8 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
9 #
7 #
10 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
12
10
13 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
14 # Imports
12 # Imports
15 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
16
14
17 # Our own packages
15 # Our own packages
18 from IPython.core.magic import Bunch, Magics, magics_class, line_magic
16 from IPython.core.magic import Bunch, Magics, magics_class, line_magic
19 from IPython.testing.skipdoctest import skip_doctest
17 from IPython.testing.skipdoctest import skip_doctest
20 from logging import error
18 from logging import error
21
19
22 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
23 # Magic implementation classes
21 # Magic implementation classes
24 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
25
23
26 @magics_class
24 @magics_class
27 class AutoMagics(Magics):
25 class AutoMagics(Magics):
28 """Magics that control various autoX behaviors."""
26 """Magics that control various autoX behaviors."""
29
27
30 def __init__(self, shell):
28 def __init__(self, shell):
31 super(AutoMagics, self).__init__(shell)
29 super(AutoMagics, self).__init__(shell)
32 # namespace for holding state we may need
30 # namespace for holding state we may need
33 self._magic_state = Bunch()
31 self._magic_state = Bunch()
34
32
35 @line_magic
33 @line_magic
36 def automagic(self, parameter_s=''):
34 def automagic(self, parameter_s=''):
37 """Make magic functions callable without having to type the initial %.
35 """Make magic functions callable without having to type the initial %.
38
36
39 Without argumentsl toggles on/off (when off, you must call it as
37 Without argumentsl toggles on/off (when off, you must call it as
40 %automagic, of course). With arguments it sets the value, and you can
38 %automagic, of course). With arguments it sets the value, and you can
41 use any of (case insensitive):
39 use any of (case insensitive):
42
40
43 - on, 1, True: to activate
41 - on, 1, True: to activate
44
42
45 - off, 0, False: to deactivate.
43 - off, 0, False: to deactivate.
46
44
47 Note that magic functions have lowest priority, so if there's a
45 Note that magic functions have lowest priority, so if there's a
48 variable whose name collides with that of a magic fn, automagic won't
46 variable whose name collides with that of a magic fn, automagic won't
49 work for that function (you get the variable instead). However, if you
47 work for that function (you get the variable instead). However, if you
50 delete the variable (del var), the previously shadowed magic function
48 delete the variable (del var), the previously shadowed magic function
51 becomes visible to automagic again."""
49 becomes visible to automagic again."""
52
50
53 arg = parameter_s.lower()
51 arg = parameter_s.lower()
54 mman = self.shell.magics_manager
52 mman = self.shell.magics_manager
55 if arg in ('on', '1', 'true'):
53 if arg in ('on', '1', 'true'):
56 val = True
54 val = True
57 elif arg in ('off', '0', 'false'):
55 elif arg in ('off', '0', 'false'):
58 val = False
56 val = False
59 else:
57 else:
60 val = not mman.auto_magic
58 val = not mman.auto_magic
61 mman.auto_magic = val
59 mman.auto_magic = val
62 print('\n' + self.shell.magics_manager.auto_status())
60 print('\n' + self.shell.magics_manager.auto_status())
63
61
64 @skip_doctest
62 @skip_doctest
65 @line_magic
63 @line_magic
66 def autocall(self, parameter_s=''):
64 def autocall(self, parameter_s=''):
67 """Make functions callable without having to type parentheses.
65 """Make functions callable without having to type parentheses.
68
66
69 Usage:
67 Usage:
70
68
71 %autocall [mode]
69 %autocall [mode]
72
70
73 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
71 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
74 value is toggled on and off (remembering the previous state).
72 value is toggled on and off (remembering the previous state).
75
73
76 In more detail, these values mean:
74 In more detail, these values mean:
77
75
78 0 -> fully disabled
76 0 -> fully disabled
79
77
80 1 -> active, but do not apply if there are no arguments on the line.
78 1 -> active, but do not apply if there are no arguments on the line.
81
79
82 In this mode, you get::
80 In this mode, you get::
83
81
84 In [1]: callable
82 In [1]: callable
85 Out[1]: <built-in function callable>
83 Out[1]: <built-in function callable>
86
84
87 In [2]: callable 'hello'
85 In [2]: callable 'hello'
88 ------> callable('hello')
86 ------> callable('hello')
89 Out[2]: False
87 Out[2]: False
90
88
91 2 -> Active always. Even if no arguments are present, the callable
89 2 -> Active always. Even if no arguments are present, the callable
92 object is called::
90 object is called::
93
91
94 In [2]: float
92 In [2]: float
95 ------> float()
93 ------> float()
96 Out[2]: 0.0
94 Out[2]: 0.0
97
95
98 Note that even with autocall off, you can still use '/' at the start of
96 Note that even with autocall off, you can still use '/' at the start of
99 a line to treat the first argument on the command line as a function
97 a line to treat the first argument on the command line as a function
100 and add parentheses to it::
98 and add parentheses to it::
101
99
102 In [8]: /str 43
100 In [8]: /str 43
103 ------> str(43)
101 ------> str(43)
104 Out[8]: '43'
102 Out[8]: '43'
105
103
106 # all-random (note for auto-testing)
104 # all-random (note for auto-testing)
107 """
105 """
108
106
109 if parameter_s:
107 if parameter_s:
110 arg = int(parameter_s)
108 arg = int(parameter_s)
111 else:
109 else:
112 arg = 'toggle'
110 arg = 'toggle'
113
111
114 if not arg in (0, 1, 2, 'toggle'):
112 if not arg in (0, 1, 2, 'toggle'):
115 error('Valid modes: (0->Off, 1->Smart, 2->Full')
113 error('Valid modes: (0->Off, 1->Smart, 2->Full')
116 return
114 return
117
115
118 if arg in (0, 1, 2):
116 if arg in (0, 1, 2):
119 self.shell.autocall = arg
117 self.shell.autocall = arg
120 else: # toggle
118 else: # toggle
121 if self.shell.autocall:
119 if self.shell.autocall:
122 self._magic_state.autocall_save = self.shell.autocall
120 self._magic_state.autocall_save = self.shell.autocall
123 self.shell.autocall = 0
121 self.shell.autocall = 0
124 else:
122 else:
125 try:
123 try:
126 self.shell.autocall = self._magic_state.autocall_save
124 self.shell.autocall = self._magic_state.autocall_save
127 except AttributeError:
125 except AttributeError:
128 self.shell.autocall = self._magic_state.autocall_save = 1
126 self.shell.autocall = self._magic_state.autocall_save = 1
129
127
130 print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
128 print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
@@ -1,583 +1,581 b''
1 """Implementation of basic magic functions."""
1 """Implementation of basic magic functions."""
2
2
3 from __future__ import print_function
4 from __future__ import absolute_import
5
3
6 import argparse
4 import argparse
7 import io
5 import io
8 import sys
6 import sys
9 from pprint import pformat
7 from pprint import pformat
10
8
11 from IPython.core import magic_arguments, page
9 from IPython.core import magic_arguments, page
12 from IPython.core.error import UsageError
10 from IPython.core.error import UsageError
13 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
11 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
14 from IPython.utils.text import format_screen, dedent, indent
12 from IPython.utils.text import format_screen, dedent, indent
15 from IPython.testing.skipdoctest import skip_doctest
13 from IPython.testing.skipdoctest import skip_doctest
16 from IPython.utils.ipstruct import Struct
14 from IPython.utils.ipstruct import Struct
17 from IPython.utils.py3compat import unicode_type
15 from IPython.utils.py3compat import unicode_type
18 from warnings import warn
16 from warnings import warn
19 from logging import error
17 from logging import error
20
18
21
19
22 class MagicsDisplay(object):
20 class MagicsDisplay(object):
23 def __init__(self, magics_manager):
21 def __init__(self, magics_manager):
24 self.magics_manager = magics_manager
22 self.magics_manager = magics_manager
25
23
26 def _lsmagic(self):
24 def _lsmagic(self):
27 """The main implementation of the %lsmagic"""
25 """The main implementation of the %lsmagic"""
28 mesc = magic_escapes['line']
26 mesc = magic_escapes['line']
29 cesc = magic_escapes['cell']
27 cesc = magic_escapes['cell']
30 mman = self.magics_manager
28 mman = self.magics_manager
31 magics = mman.lsmagic()
29 magics = mman.lsmagic()
32 out = ['Available line magics:',
30 out = ['Available line magics:',
33 mesc + (' '+mesc).join(sorted(magics['line'])),
31 mesc + (' '+mesc).join(sorted(magics['line'])),
34 '',
32 '',
35 'Available cell magics:',
33 'Available cell magics:',
36 cesc + (' '+cesc).join(sorted(magics['cell'])),
34 cesc + (' '+cesc).join(sorted(magics['cell'])),
37 '',
35 '',
38 mman.auto_status()]
36 mman.auto_status()]
39 return '\n'.join(out)
37 return '\n'.join(out)
40
38
41 def _repr_pretty_(self, p, cycle):
39 def _repr_pretty_(self, p, cycle):
42 p.text(self._lsmagic())
40 p.text(self._lsmagic())
43
41
44 def __str__(self):
42 def __str__(self):
45 return self._lsmagic()
43 return self._lsmagic()
46
44
47 def _jsonable(self):
45 def _jsonable(self):
48 """turn magics dict into jsonable dict of the same structure
46 """turn magics dict into jsonable dict of the same structure
49
47
50 replaces object instances with their class names as strings
48 replaces object instances with their class names as strings
51 """
49 """
52 magic_dict = {}
50 magic_dict = {}
53 mman = self.magics_manager
51 mman = self.magics_manager
54 magics = mman.lsmagic()
52 magics = mman.lsmagic()
55 for key, subdict in magics.items():
53 for key, subdict in magics.items():
56 d = {}
54 d = {}
57 magic_dict[key] = d
55 magic_dict[key] = d
58 for name, obj in subdict.items():
56 for name, obj in subdict.items():
59 try:
57 try:
60 classname = obj.__self__.__class__.__name__
58 classname = obj.__self__.__class__.__name__
61 except AttributeError:
59 except AttributeError:
62 classname = 'Other'
60 classname = 'Other'
63
61
64 d[name] = classname
62 d[name] = classname
65 return magic_dict
63 return magic_dict
66
64
67 def _repr_json_(self):
65 def _repr_json_(self):
68 return self._jsonable()
66 return self._jsonable()
69
67
70
68
71 @magics_class
69 @magics_class
72 class BasicMagics(Magics):
70 class BasicMagics(Magics):
73 """Magics that provide central IPython functionality.
71 """Magics that provide central IPython functionality.
74
72
75 These are various magics that don't fit into specific categories but that
73 These are various magics that don't fit into specific categories but that
76 are all part of the base 'IPython experience'."""
74 are all part of the base 'IPython experience'."""
77
75
78 @magic_arguments.magic_arguments()
76 @magic_arguments.magic_arguments()
79 @magic_arguments.argument(
77 @magic_arguments.argument(
80 '-l', '--line', action='store_true',
78 '-l', '--line', action='store_true',
81 help="""Create a line magic alias."""
79 help="""Create a line magic alias."""
82 )
80 )
83 @magic_arguments.argument(
81 @magic_arguments.argument(
84 '-c', '--cell', action='store_true',
82 '-c', '--cell', action='store_true',
85 help="""Create a cell magic alias."""
83 help="""Create a cell magic alias."""
86 )
84 )
87 @magic_arguments.argument(
85 @magic_arguments.argument(
88 'name',
86 'name',
89 help="""Name of the magic to be created."""
87 help="""Name of the magic to be created."""
90 )
88 )
91 @magic_arguments.argument(
89 @magic_arguments.argument(
92 'target',
90 'target',
93 help="""Name of the existing line or cell magic."""
91 help="""Name of the existing line or cell magic."""
94 )
92 )
95 @line_magic
93 @line_magic
96 def alias_magic(self, line=''):
94 def alias_magic(self, line=''):
97 """Create an alias for an existing line or cell magic.
95 """Create an alias for an existing line or cell magic.
98
96
99 Examples
97 Examples
100 --------
98 --------
101 ::
99 ::
102
100
103 In [1]: %alias_magic t timeit
101 In [1]: %alias_magic t timeit
104 Created `%t` as an alias for `%timeit`.
102 Created `%t` as an alias for `%timeit`.
105 Created `%%t` as an alias for `%%timeit`.
103 Created `%%t` as an alias for `%%timeit`.
106
104
107 In [2]: %t -n1 pass
105 In [2]: %t -n1 pass
108 1 loops, best of 3: 954 ns per loop
106 1 loops, best of 3: 954 ns per loop
109
107
110 In [3]: %%t -n1
108 In [3]: %%t -n1
111 ...: pass
109 ...: pass
112 ...:
110 ...:
113 1 loops, best of 3: 954 ns per loop
111 1 loops, best of 3: 954 ns per loop
114
112
115 In [4]: %alias_magic --cell whereami pwd
113 In [4]: %alias_magic --cell whereami pwd
116 UsageError: Cell magic function `%%pwd` not found.
114 UsageError: Cell magic function `%%pwd` not found.
117 In [5]: %alias_magic --line whereami pwd
115 In [5]: %alias_magic --line whereami pwd
118 Created `%whereami` as an alias for `%pwd`.
116 Created `%whereami` as an alias for `%pwd`.
119
117
120 In [6]: %whereami
118 In [6]: %whereami
121 Out[6]: u'/home/testuser'
119 Out[6]: u'/home/testuser'
122 """
120 """
123 args = magic_arguments.parse_argstring(self.alias_magic, line)
121 args = magic_arguments.parse_argstring(self.alias_magic, line)
124 shell = self.shell
122 shell = self.shell
125 mman = self.shell.magics_manager
123 mman = self.shell.magics_manager
126 escs = ''.join(magic_escapes.values())
124 escs = ''.join(magic_escapes.values())
127
125
128 target = args.target.lstrip(escs)
126 target = args.target.lstrip(escs)
129 name = args.name.lstrip(escs)
127 name = args.name.lstrip(escs)
130
128
131 # Find the requested magics.
129 # Find the requested magics.
132 m_line = shell.find_magic(target, 'line')
130 m_line = shell.find_magic(target, 'line')
133 m_cell = shell.find_magic(target, 'cell')
131 m_cell = shell.find_magic(target, 'cell')
134 if args.line and m_line is None:
132 if args.line and m_line is None:
135 raise UsageError('Line magic function `%s%s` not found.' %
133 raise UsageError('Line magic function `%s%s` not found.' %
136 (magic_escapes['line'], target))
134 (magic_escapes['line'], target))
137 if args.cell and m_cell is None:
135 if args.cell and m_cell is None:
138 raise UsageError('Cell magic function `%s%s` not found.' %
136 raise UsageError('Cell magic function `%s%s` not found.' %
139 (magic_escapes['cell'], target))
137 (magic_escapes['cell'], target))
140
138
141 # If --line and --cell are not specified, default to the ones
139 # If --line and --cell are not specified, default to the ones
142 # that are available.
140 # that are available.
143 if not args.line and not args.cell:
141 if not args.line and not args.cell:
144 if not m_line and not m_cell:
142 if not m_line and not m_cell:
145 raise UsageError(
143 raise UsageError(
146 'No line or cell magic with name `%s` found.' % target
144 'No line or cell magic with name `%s` found.' % target
147 )
145 )
148 args.line = bool(m_line)
146 args.line = bool(m_line)
149 args.cell = bool(m_cell)
147 args.cell = bool(m_cell)
150
148
151 if args.line:
149 if args.line:
152 mman.register_alias(name, target, 'line')
150 mman.register_alias(name, target, 'line')
153 print('Created `%s%s` as an alias for `%s%s`.' % (
151 print('Created `%s%s` as an alias for `%s%s`.' % (
154 magic_escapes['line'], name,
152 magic_escapes['line'], name,
155 magic_escapes['line'], target))
153 magic_escapes['line'], target))
156
154
157 if args.cell:
155 if args.cell:
158 mman.register_alias(name, target, 'cell')
156 mman.register_alias(name, target, 'cell')
159 print('Created `%s%s` as an alias for `%s%s`.' % (
157 print('Created `%s%s` as an alias for `%s%s`.' % (
160 magic_escapes['cell'], name,
158 magic_escapes['cell'], name,
161 magic_escapes['cell'], target))
159 magic_escapes['cell'], target))
162
160
163 @line_magic
161 @line_magic
164 def lsmagic(self, parameter_s=''):
162 def lsmagic(self, parameter_s=''):
165 """List currently available magic functions."""
163 """List currently available magic functions."""
166 return MagicsDisplay(self.shell.magics_manager)
164 return MagicsDisplay(self.shell.magics_manager)
167
165
168 def _magic_docs(self, brief=False, rest=False):
166 def _magic_docs(self, brief=False, rest=False):
169 """Return docstrings from magic functions."""
167 """Return docstrings from magic functions."""
170 mman = self.shell.magics_manager
168 mman = self.shell.magics_manager
171 docs = mman.lsmagic_docs(brief, missing='No documentation')
169 docs = mman.lsmagic_docs(brief, missing='No documentation')
172
170
173 if rest:
171 if rest:
174 format_string = '**%s%s**::\n\n%s\n\n'
172 format_string = '**%s%s**::\n\n%s\n\n'
175 else:
173 else:
176 format_string = '%s%s:\n%s\n'
174 format_string = '%s%s:\n%s\n'
177
175
178 return ''.join(
176 return ''.join(
179 [format_string % (magic_escapes['line'], fname,
177 [format_string % (magic_escapes['line'], fname,
180 indent(dedent(fndoc)))
178 indent(dedent(fndoc)))
181 for fname, fndoc in sorted(docs['line'].items())]
179 for fname, fndoc in sorted(docs['line'].items())]
182 +
180 +
183 [format_string % (magic_escapes['cell'], fname,
181 [format_string % (magic_escapes['cell'], fname,
184 indent(dedent(fndoc)))
182 indent(dedent(fndoc)))
185 for fname, fndoc in sorted(docs['cell'].items())]
183 for fname, fndoc in sorted(docs['cell'].items())]
186 )
184 )
187
185
188 @line_magic
186 @line_magic
189 def magic(self, parameter_s=''):
187 def magic(self, parameter_s=''):
190 """Print information about the magic function system.
188 """Print information about the magic function system.
191
189
192 Supported formats: -latex, -brief, -rest
190 Supported formats: -latex, -brief, -rest
193 """
191 """
194
192
195 mode = ''
193 mode = ''
196 try:
194 try:
197 mode = parameter_s.split()[0][1:]
195 mode = parameter_s.split()[0][1:]
198 except IndexError:
196 except IndexError:
199 pass
197 pass
200
198
201 brief = (mode == 'brief')
199 brief = (mode == 'brief')
202 rest = (mode == 'rest')
200 rest = (mode == 'rest')
203 magic_docs = self._magic_docs(brief, rest)
201 magic_docs = self._magic_docs(brief, rest)
204
202
205 if mode == 'latex':
203 if mode == 'latex':
206 print(self.format_latex(magic_docs))
204 print(self.format_latex(magic_docs))
207 return
205 return
208 else:
206 else:
209 magic_docs = format_screen(magic_docs)
207 magic_docs = format_screen(magic_docs)
210
208
211 out = ["""
209 out = ["""
212 IPython's 'magic' functions
210 IPython's 'magic' functions
213 ===========================
211 ===========================
214
212
215 The magic function system provides a series of functions which allow you to
213 The magic function system provides a series of functions which allow you to
216 control the behavior of IPython itself, plus a lot of system-type
214 control the behavior of IPython itself, plus a lot of system-type
217 features. There are two kinds of magics, line-oriented and cell-oriented.
215 features. There are two kinds of magics, line-oriented and cell-oriented.
218
216
219 Line magics are prefixed with the % character and work much like OS
217 Line magics are prefixed with the % character and work much like OS
220 command-line calls: they get as an argument the rest of the line, where
218 command-line calls: they get as an argument the rest of the line, where
221 arguments are passed without parentheses or quotes. For example, this will
219 arguments are passed without parentheses or quotes. For example, this will
222 time the given statement::
220 time the given statement::
223
221
224 %timeit range(1000)
222 %timeit range(1000)
225
223
226 Cell magics are prefixed with a double %%, and they are functions that get as
224 Cell magics are prefixed with a double %%, and they are functions that get as
227 an argument not only the rest of the line, but also the lines below it in a
225 an argument not only the rest of the line, but also the lines below it in a
228 separate argument. These magics are called with two arguments: the rest of the
226 separate argument. These magics are called with two arguments: the rest of the
229 call line and the body of the cell, consisting of the lines below the first.
227 call line and the body of the cell, consisting of the lines below the first.
230 For example::
228 For example::
231
229
232 %%timeit x = numpy.random.randn((100, 100))
230 %%timeit x = numpy.random.randn((100, 100))
233 numpy.linalg.svd(x)
231 numpy.linalg.svd(x)
234
232
235 will time the execution of the numpy svd routine, running the assignment of x
233 will time the execution of the numpy svd routine, running the assignment of x
236 as part of the setup phase, which is not timed.
234 as part of the setup phase, which is not timed.
237
235
238 In a line-oriented client (the terminal or Qt console IPython), starting a new
236 In a line-oriented client (the terminal or Qt console IPython), starting a new
239 input with %% will automatically enter cell mode, and IPython will continue
237 input with %% will automatically enter cell mode, and IPython will continue
240 reading input until a blank line is given. In the notebook, simply type the
238 reading input until a blank line is given. In the notebook, simply type the
241 whole cell as one entity, but keep in mind that the %% escape can only be at
239 whole cell as one entity, but keep in mind that the %% escape can only be at
242 the very start of the cell.
240 the very start of the cell.
243
241
244 NOTE: If you have 'automagic' enabled (via the command line option or with the
242 NOTE: If you have 'automagic' enabled (via the command line option or with the
245 %automagic function), you don't need to type in the % explicitly for line
243 %automagic function), you don't need to type in the % explicitly for line
246 magics; cell magics always require an explicit '%%' escape. By default,
244 magics; cell magics always require an explicit '%%' escape. By default,
247 IPython ships with automagic on, so you should only rarely need the % escape.
245 IPython ships with automagic on, so you should only rarely need the % escape.
248
246
249 Example: typing '%cd mydir' (without the quotes) changes your working directory
247 Example: typing '%cd mydir' (without the quotes) changes your working directory
250 to 'mydir', if it exists.
248 to 'mydir', if it exists.
251
249
252 For a list of the available magic functions, use %lsmagic. For a description
250 For a list of the available magic functions, use %lsmagic. For a description
253 of any of them, type %magic_name?, e.g. '%cd?'.
251 of any of them, type %magic_name?, e.g. '%cd?'.
254
252
255 Currently the magic system has the following functions:""",
253 Currently the magic system has the following functions:""",
256 magic_docs,
254 magic_docs,
257 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
255 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
258 str(self.lsmagic()),
256 str(self.lsmagic()),
259 ]
257 ]
260 page.page('\n'.join(out))
258 page.page('\n'.join(out))
261
259
262
260
263 @line_magic
261 @line_magic
264 def page(self, parameter_s=''):
262 def page(self, parameter_s=''):
265 """Pretty print the object and display it through a pager.
263 """Pretty print the object and display it through a pager.
266
264
267 %page [options] OBJECT
265 %page [options] OBJECT
268
266
269 If no object is given, use _ (last output).
267 If no object is given, use _ (last output).
270
268
271 Options:
269 Options:
272
270
273 -r: page str(object), don't pretty-print it."""
271 -r: page str(object), don't pretty-print it."""
274
272
275 # After a function contributed by Olivier Aubert, slightly modified.
273 # After a function contributed by Olivier Aubert, slightly modified.
276
274
277 # Process options/args
275 # Process options/args
278 opts, args = self.parse_options(parameter_s, 'r')
276 opts, args = self.parse_options(parameter_s, 'r')
279 raw = 'r' in opts
277 raw = 'r' in opts
280
278
281 oname = args and args or '_'
279 oname = args and args or '_'
282 info = self.shell._ofind(oname)
280 info = self.shell._ofind(oname)
283 if info['found']:
281 if info['found']:
284 txt = (raw and str or pformat)( info['obj'] )
282 txt = (raw and str or pformat)( info['obj'] )
285 page.page(txt)
283 page.page(txt)
286 else:
284 else:
287 print('Object `%s` not found' % oname)
285 print('Object `%s` not found' % oname)
288
286
289 @line_magic
287 @line_magic
290 def profile(self, parameter_s=''):
288 def profile(self, parameter_s=''):
291 """Print your currently active IPython profile.
289 """Print your currently active IPython profile.
292
290
293 See Also
291 See Also
294 --------
292 --------
295 prun : run code using the Python profiler
293 prun : run code using the Python profiler
296 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
294 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
297 """
295 """
298 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
296 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
299 from IPython.core.application import BaseIPythonApplication
297 from IPython.core.application import BaseIPythonApplication
300 if BaseIPythonApplication.initialized():
298 if BaseIPythonApplication.initialized():
301 print(BaseIPythonApplication.instance().profile)
299 print(BaseIPythonApplication.instance().profile)
302 else:
300 else:
303 error("profile is an application-level value, but you don't appear to be in an IPython application")
301 error("profile is an application-level value, but you don't appear to be in an IPython application")
304
302
305 @line_magic
303 @line_magic
306 def pprint(self, parameter_s=''):
304 def pprint(self, parameter_s=''):
307 """Toggle pretty printing on/off."""
305 """Toggle pretty printing on/off."""
308 ptformatter = self.shell.display_formatter.formatters['text/plain']
306 ptformatter = self.shell.display_formatter.formatters['text/plain']
309 ptformatter.pprint = bool(1 - ptformatter.pprint)
307 ptformatter.pprint = bool(1 - ptformatter.pprint)
310 print('Pretty printing has been turned',
308 print('Pretty printing has been turned',
311 ['OFF','ON'][ptformatter.pprint])
309 ['OFF','ON'][ptformatter.pprint])
312
310
313 @line_magic
311 @line_magic
314 def colors(self, parameter_s=''):
312 def colors(self, parameter_s=''):
315 """Switch color scheme for prompts, info system and exception handlers.
313 """Switch color scheme for prompts, info system and exception handlers.
316
314
317 Currently implemented schemes: NoColor, Linux, LightBG.
315 Currently implemented schemes: NoColor, Linux, LightBG.
318
316
319 Color scheme names are not case-sensitive.
317 Color scheme names are not case-sensitive.
320
318
321 Examples
319 Examples
322 --------
320 --------
323 To get a plain black and white terminal::
321 To get a plain black and white terminal::
324
322
325 %colors nocolor
323 %colors nocolor
326 """
324 """
327 def color_switch_err(name):
325 def color_switch_err(name):
328 warn('Error changing %s color schemes.\n%s' %
326 warn('Error changing %s color schemes.\n%s' %
329 (name, sys.exc_info()[1]), stacklevel=2)
327 (name, sys.exc_info()[1]), stacklevel=2)
330
328
331
329
332 new_scheme = parameter_s.strip()
330 new_scheme = parameter_s.strip()
333 if not new_scheme:
331 if not new_scheme:
334 raise UsageError(
332 raise UsageError(
335 "%colors: you must specify a color scheme. See '%colors?'")
333 "%colors: you must specify a color scheme. See '%colors?'")
336 # local shortcut
334 # local shortcut
337 shell = self.shell
335 shell = self.shell
338
336
339 # Set shell colour scheme
337 # Set shell colour scheme
340 try:
338 try:
341 shell.colors = new_scheme
339 shell.colors = new_scheme
342 shell.refresh_style()
340 shell.refresh_style()
343 except:
341 except:
344 color_switch_err('shell')
342 color_switch_err('shell')
345
343
346 # Set exception colors
344 # Set exception colors
347 try:
345 try:
348 shell.InteractiveTB.set_colors(scheme = new_scheme)
346 shell.InteractiveTB.set_colors(scheme = new_scheme)
349 shell.SyntaxTB.set_colors(scheme = new_scheme)
347 shell.SyntaxTB.set_colors(scheme = new_scheme)
350 except:
348 except:
351 color_switch_err('exception')
349 color_switch_err('exception')
352
350
353 # Set info (for 'object?') colors
351 # Set info (for 'object?') colors
354 if shell.color_info:
352 if shell.color_info:
355 try:
353 try:
356 shell.inspector.set_active_scheme(new_scheme)
354 shell.inspector.set_active_scheme(new_scheme)
357 except:
355 except:
358 color_switch_err('object inspector')
356 color_switch_err('object inspector')
359 else:
357 else:
360 shell.inspector.set_active_scheme('NoColor')
358 shell.inspector.set_active_scheme('NoColor')
361
359
362 @line_magic
360 @line_magic
363 def xmode(self, parameter_s=''):
361 def xmode(self, parameter_s=''):
364 """Switch modes for the exception handlers.
362 """Switch modes for the exception handlers.
365
363
366 Valid modes: Plain, Context and Verbose.
364 Valid modes: Plain, Context and Verbose.
367
365
368 If called without arguments, acts as a toggle."""
366 If called without arguments, acts as a toggle."""
369
367
370 def xmode_switch_err(name):
368 def xmode_switch_err(name):
371 warn('Error changing %s exception modes.\n%s' %
369 warn('Error changing %s exception modes.\n%s' %
372 (name,sys.exc_info()[1]))
370 (name,sys.exc_info()[1]))
373
371
374 shell = self.shell
372 shell = self.shell
375 new_mode = parameter_s.strip().capitalize()
373 new_mode = parameter_s.strip().capitalize()
376 try:
374 try:
377 shell.InteractiveTB.set_mode(mode=new_mode)
375 shell.InteractiveTB.set_mode(mode=new_mode)
378 print('Exception reporting mode:',shell.InteractiveTB.mode)
376 print('Exception reporting mode:',shell.InteractiveTB.mode)
379 except:
377 except:
380 xmode_switch_err('user')
378 xmode_switch_err('user')
381
379
382 @line_magic
380 @line_magic
383 def quickref(self,arg):
381 def quickref(self,arg):
384 """ Show a quick reference sheet """
382 """ Show a quick reference sheet """
385 from IPython.core.usage import quick_reference
383 from IPython.core.usage import quick_reference
386 qr = quick_reference + self._magic_docs(brief=True)
384 qr = quick_reference + self._magic_docs(brief=True)
387 page.page(qr)
385 page.page(qr)
388
386
389 @line_magic
387 @line_magic
390 def doctest_mode(self, parameter_s=''):
388 def doctest_mode(self, parameter_s=''):
391 """Toggle doctest mode on and off.
389 """Toggle doctest mode on and off.
392
390
393 This mode is intended to make IPython behave as much as possible like a
391 This mode is intended to make IPython behave as much as possible like a
394 plain Python shell, from the perspective of how its prompts, exceptions
392 plain Python shell, from the perspective of how its prompts, exceptions
395 and output look. This makes it easy to copy and paste parts of a
393 and output look. This makes it easy to copy and paste parts of a
396 session into doctests. It does so by:
394 session into doctests. It does so by:
397
395
398 - Changing the prompts to the classic ``>>>`` ones.
396 - Changing the prompts to the classic ``>>>`` ones.
399 - Changing the exception reporting mode to 'Plain'.
397 - Changing the exception reporting mode to 'Plain'.
400 - Disabling pretty-printing of output.
398 - Disabling pretty-printing of output.
401
399
402 Note that IPython also supports the pasting of code snippets that have
400 Note that IPython also supports the pasting of code snippets that have
403 leading '>>>' and '...' prompts in them. This means that you can paste
401 leading '>>>' and '...' prompts in them. This means that you can paste
404 doctests from files or docstrings (even if they have leading
402 doctests from files or docstrings (even if they have leading
405 whitespace), and the code will execute correctly. You can then use
403 whitespace), and the code will execute correctly. You can then use
406 '%history -t' to see the translated history; this will give you the
404 '%history -t' to see the translated history; this will give you the
407 input after removal of all the leading prompts and whitespace, which
405 input after removal of all the leading prompts and whitespace, which
408 can be pasted back into an editor.
406 can be pasted back into an editor.
409
407
410 With these features, you can switch into this mode easily whenever you
408 With these features, you can switch into this mode easily whenever you
411 need to do testing and changes to doctests, without having to leave
409 need to do testing and changes to doctests, without having to leave
412 your existing IPython session.
410 your existing IPython session.
413 """
411 """
414
412
415 # Shorthands
413 # Shorthands
416 shell = self.shell
414 shell = self.shell
417 meta = shell.meta
415 meta = shell.meta
418 disp_formatter = self.shell.display_formatter
416 disp_formatter = self.shell.display_formatter
419 ptformatter = disp_formatter.formatters['text/plain']
417 ptformatter = disp_formatter.formatters['text/plain']
420 # dstore is a data store kept in the instance metadata bag to track any
418 # dstore is a data store kept in the instance metadata bag to track any
421 # changes we make, so we can undo them later.
419 # changes we make, so we can undo them later.
422 dstore = meta.setdefault('doctest_mode',Struct())
420 dstore = meta.setdefault('doctest_mode',Struct())
423 save_dstore = dstore.setdefault
421 save_dstore = dstore.setdefault
424
422
425 # save a few values we'll need to recover later
423 # save a few values we'll need to recover later
426 mode = save_dstore('mode',False)
424 mode = save_dstore('mode',False)
427 save_dstore('rc_pprint',ptformatter.pprint)
425 save_dstore('rc_pprint',ptformatter.pprint)
428 save_dstore('xmode',shell.InteractiveTB.mode)
426 save_dstore('xmode',shell.InteractiveTB.mode)
429 save_dstore('rc_separate_out',shell.separate_out)
427 save_dstore('rc_separate_out',shell.separate_out)
430 save_dstore('rc_separate_out2',shell.separate_out2)
428 save_dstore('rc_separate_out2',shell.separate_out2)
431 save_dstore('rc_separate_in',shell.separate_in)
429 save_dstore('rc_separate_in',shell.separate_in)
432 save_dstore('rc_active_types',disp_formatter.active_types)
430 save_dstore('rc_active_types',disp_formatter.active_types)
433
431
434 if not mode:
432 if not mode:
435 # turn on
433 # turn on
436
434
437 # Prompt separators like plain python
435 # Prompt separators like plain python
438 shell.separate_in = ''
436 shell.separate_in = ''
439 shell.separate_out = ''
437 shell.separate_out = ''
440 shell.separate_out2 = ''
438 shell.separate_out2 = ''
441
439
442
440
443 ptformatter.pprint = False
441 ptformatter.pprint = False
444 disp_formatter.active_types = ['text/plain']
442 disp_formatter.active_types = ['text/plain']
445
443
446 shell.magic('xmode Plain')
444 shell.magic('xmode Plain')
447 else:
445 else:
448 # turn off
446 # turn off
449 shell.separate_in = dstore.rc_separate_in
447 shell.separate_in = dstore.rc_separate_in
450
448
451 shell.separate_out = dstore.rc_separate_out
449 shell.separate_out = dstore.rc_separate_out
452 shell.separate_out2 = dstore.rc_separate_out2
450 shell.separate_out2 = dstore.rc_separate_out2
453
451
454 ptformatter.pprint = dstore.rc_pprint
452 ptformatter.pprint = dstore.rc_pprint
455 disp_formatter.active_types = dstore.rc_active_types
453 disp_formatter.active_types = dstore.rc_active_types
456
454
457 shell.magic('xmode ' + dstore.xmode)
455 shell.magic('xmode ' + dstore.xmode)
458
456
459 # mode here is the state before we switch; switch_doctest_mode takes
457 # mode here is the state before we switch; switch_doctest_mode takes
460 # the mode we're switching to.
458 # the mode we're switching to.
461 shell.switch_doctest_mode(not mode)
459 shell.switch_doctest_mode(not mode)
462
460
463 # Store new mode and inform
461 # Store new mode and inform
464 dstore.mode = bool(not mode)
462 dstore.mode = bool(not mode)
465 mode_label = ['OFF','ON'][dstore.mode]
463 mode_label = ['OFF','ON'][dstore.mode]
466 print('Doctest mode is:', mode_label)
464 print('Doctest mode is:', mode_label)
467
465
468 @line_magic
466 @line_magic
469 def gui(self, parameter_s=''):
467 def gui(self, parameter_s=''):
470 """Enable or disable IPython GUI event loop integration.
468 """Enable or disable IPython GUI event loop integration.
471
469
472 %gui [GUINAME]
470 %gui [GUINAME]
473
471
474 This magic replaces IPython's threaded shells that were activated
472 This magic replaces IPython's threaded shells that were activated
475 using the (pylab/wthread/etc.) command line flags. GUI toolkits
473 using the (pylab/wthread/etc.) command line flags. GUI toolkits
476 can now be enabled at runtime and keyboard
474 can now be enabled at runtime and keyboard
477 interrupts should work without any problems. The following toolkits
475 interrupts should work without any problems. The following toolkits
478 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
476 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
479
477
480 %gui wx # enable wxPython event loop integration
478 %gui wx # enable wxPython event loop integration
481 %gui qt4|qt # enable PyQt4 event loop integration
479 %gui qt4|qt # enable PyQt4 event loop integration
482 %gui qt5 # enable PyQt5 event loop integration
480 %gui qt5 # enable PyQt5 event loop integration
483 %gui gtk # enable PyGTK event loop integration
481 %gui gtk # enable PyGTK event loop integration
484 %gui gtk3 # enable Gtk3 event loop integration
482 %gui gtk3 # enable Gtk3 event loop integration
485 %gui tk # enable Tk event loop integration
483 %gui tk # enable Tk event loop integration
486 %gui osx # enable Cocoa event loop integration
484 %gui osx # enable Cocoa event loop integration
487 # (requires %matplotlib 1.1)
485 # (requires %matplotlib 1.1)
488 %gui # disable all event loop integration
486 %gui # disable all event loop integration
489
487
490 WARNING: after any of these has been called you can simply create
488 WARNING: after any of these has been called you can simply create
491 an application object, but DO NOT start the event loop yourself, as
489 an application object, but DO NOT start the event loop yourself, as
492 we have already handled that.
490 we have already handled that.
493 """
491 """
494 opts, arg = self.parse_options(parameter_s, '')
492 opts, arg = self.parse_options(parameter_s, '')
495 if arg=='': arg = None
493 if arg=='': arg = None
496 try:
494 try:
497 return self.shell.enable_gui(arg)
495 return self.shell.enable_gui(arg)
498 except Exception as e:
496 except Exception as e:
499 # print simple error message, rather than traceback if we can't
497 # print simple error message, rather than traceback if we can't
500 # hook up the GUI
498 # hook up the GUI
501 error(str(e))
499 error(str(e))
502
500
503 @skip_doctest
501 @skip_doctest
504 @line_magic
502 @line_magic
505 def precision(self, s=''):
503 def precision(self, s=''):
506 """Set floating point precision for pretty printing.
504 """Set floating point precision for pretty printing.
507
505
508 Can set either integer precision or a format string.
506 Can set either integer precision or a format string.
509
507
510 If numpy has been imported and precision is an int,
508 If numpy has been imported and precision is an int,
511 numpy display precision will also be set, via ``numpy.set_printoptions``.
509 numpy display precision will also be set, via ``numpy.set_printoptions``.
512
510
513 If no argument is given, defaults will be restored.
511 If no argument is given, defaults will be restored.
514
512
515 Examples
513 Examples
516 --------
514 --------
517 ::
515 ::
518
516
519 In [1]: from math import pi
517 In [1]: from math import pi
520
518
521 In [2]: %precision 3
519 In [2]: %precision 3
522 Out[2]: u'%.3f'
520 Out[2]: u'%.3f'
523
521
524 In [3]: pi
522 In [3]: pi
525 Out[3]: 3.142
523 Out[3]: 3.142
526
524
527 In [4]: %precision %i
525 In [4]: %precision %i
528 Out[4]: u'%i'
526 Out[4]: u'%i'
529
527
530 In [5]: pi
528 In [5]: pi
531 Out[5]: 3
529 Out[5]: 3
532
530
533 In [6]: %precision %e
531 In [6]: %precision %e
534 Out[6]: u'%e'
532 Out[6]: u'%e'
535
533
536 In [7]: pi**10
534 In [7]: pi**10
537 Out[7]: 9.364805e+04
535 Out[7]: 9.364805e+04
538
536
539 In [8]: %precision
537 In [8]: %precision
540 Out[8]: u'%r'
538 Out[8]: u'%r'
541
539
542 In [9]: pi**10
540 In [9]: pi**10
543 Out[9]: 93648.047476082982
541 Out[9]: 93648.047476082982
544 """
542 """
545 ptformatter = self.shell.display_formatter.formatters['text/plain']
543 ptformatter = self.shell.display_formatter.formatters['text/plain']
546 ptformatter.float_precision = s
544 ptformatter.float_precision = s
547 return ptformatter.float_format
545 return ptformatter.float_format
548
546
549 @magic_arguments.magic_arguments()
547 @magic_arguments.magic_arguments()
550 @magic_arguments.argument(
548 @magic_arguments.argument(
551 '-e', '--export', action='store_true', default=False,
549 '-e', '--export', action='store_true', default=False,
552 help=argparse.SUPPRESS
550 help=argparse.SUPPRESS
553 )
551 )
554 @magic_arguments.argument(
552 @magic_arguments.argument(
555 'filename', type=unicode_type,
553 'filename', type=unicode_type,
556 help='Notebook name or filename'
554 help='Notebook name or filename'
557 )
555 )
558 @line_magic
556 @line_magic
559 def notebook(self, s):
557 def notebook(self, s):
560 """Export and convert IPython notebooks.
558 """Export and convert IPython notebooks.
561
559
562 This function can export the current IPython history to a notebook file.
560 This function can export the current IPython history to a notebook file.
563 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
561 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
564
562
565 The -e or --export flag is deprecated in IPython 5.2, and will be
563 The -e or --export flag is deprecated in IPython 5.2, and will be
566 removed in the future.
564 removed in the future.
567 """
565 """
568 args = magic_arguments.parse_argstring(self.notebook, s)
566 args = magic_arguments.parse_argstring(self.notebook, s)
569
567
570 from nbformat import write, v4
568 from nbformat import write, v4
571
569
572 cells = []
570 cells = []
573 hist = list(self.shell.history_manager.get_range())
571 hist = list(self.shell.history_manager.get_range())
574 if(len(hist)<=1):
572 if(len(hist)<=1):
575 raise ValueError('History is empty, cannot export')
573 raise ValueError('History is empty, cannot export')
576 for session, execution_count, source in hist[:-1]:
574 for session, execution_count, source in hist[:-1]:
577 cells.append(v4.new_code_cell(
575 cells.append(v4.new_code_cell(
578 execution_count=execution_count,
576 execution_count=execution_count,
579 source=source
577 source=source
580 ))
578 ))
581 nb = v4.new_notebook(cells=cells)
579 nb = v4.new_notebook(cells=cells)
582 with io.open(args.filename, 'w', encoding='utf-8') as f:
580 with io.open(args.filename, 'w', encoding='utf-8') as f:
583 write(nb, f, version=4)
581 write(nb, f, version=4)
@@ -1,746 +1,744 b''
1 """Implementation of code management magic functions.
1 """Implementation of code management magic functions.
2 """
2 """
3 from __future__ import print_function
4 from __future__ import absolute_import
5 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
6 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
7 #
5 #
8 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
9 #
7 #
10 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
12
10
13 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
14 # Imports
12 # Imports
15 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
16
14
17 # Stdlib
15 # Stdlib
18 import inspect
16 import inspect
19 import io
17 import io
20 import os
18 import os
21 import re
19 import re
22 import sys
20 import sys
23 import ast
21 import ast
24 from itertools import chain
22 from itertools import chain
25
23
26 # Our own packages
24 # Our own packages
27 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
25 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
28 from IPython.core.macro import Macro
26 from IPython.core.macro import Macro
29 from IPython.core.magic import Magics, magics_class, line_magic
27 from IPython.core.magic import Magics, magics_class, line_magic
30 from IPython.core.oinspect import find_file, find_source_lines
28 from IPython.core.oinspect import find_file, find_source_lines
31 from IPython.testing.skipdoctest import skip_doctest
29 from IPython.testing.skipdoctest import skip_doctest
32 from IPython.utils import py3compat
30 from IPython.utils import py3compat
33 from IPython.utils.py3compat import string_types
31 from IPython.utils.py3compat import string_types
34 from IPython.utils.contexts import preserve_keys
32 from IPython.utils.contexts import preserve_keys
35 from IPython.utils.path import get_py_filename
33 from IPython.utils.path import get_py_filename
36 from warnings import warn
34 from warnings import warn
37 from logging import error
35 from logging import error
38 from IPython.utils.text import get_text_list
36 from IPython.utils.text import get_text_list
39
37
40 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
41 # Magic implementation classes
39 # Magic implementation classes
42 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
43
41
44 # Used for exception handling in magic_edit
42 # Used for exception handling in magic_edit
45 class MacroToEdit(ValueError): pass
43 class MacroToEdit(ValueError): pass
46
44
47 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
45 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
48
46
49 # To match, e.g. 8-10 1:5 :10 3-
47 # To match, e.g. 8-10 1:5 :10 3-
50 range_re = re.compile(r"""
48 range_re = re.compile(r"""
51 (?P<start>\d+)?
49 (?P<start>\d+)?
52 ((?P<sep>[\-:])
50 ((?P<sep>[\-:])
53 (?P<end>\d+)?)?
51 (?P<end>\d+)?)?
54 $""", re.VERBOSE)
52 $""", re.VERBOSE)
55
53
56
54
57 def extract_code_ranges(ranges_str):
55 def extract_code_ranges(ranges_str):
58 """Turn a string of range for %%load into 2-tuples of (start, stop)
56 """Turn a string of range for %%load into 2-tuples of (start, stop)
59 ready to use as a slice of the content splitted by lines.
57 ready to use as a slice of the content splitted by lines.
60
58
61 Examples
59 Examples
62 --------
60 --------
63 list(extract_input_ranges("5-10 2"))
61 list(extract_input_ranges("5-10 2"))
64 [(4, 10), (1, 2)]
62 [(4, 10), (1, 2)]
65 """
63 """
66 for range_str in ranges_str.split():
64 for range_str in ranges_str.split():
67 rmatch = range_re.match(range_str)
65 rmatch = range_re.match(range_str)
68 if not rmatch:
66 if not rmatch:
69 continue
67 continue
70 sep = rmatch.group("sep")
68 sep = rmatch.group("sep")
71 start = rmatch.group("start")
69 start = rmatch.group("start")
72 end = rmatch.group("end")
70 end = rmatch.group("end")
73
71
74 if sep == '-':
72 if sep == '-':
75 start = int(start) - 1 if start else None
73 start = int(start) - 1 if start else None
76 end = int(end) if end else None
74 end = int(end) if end else None
77 elif sep == ':':
75 elif sep == ':':
78 start = int(start) - 1 if start else None
76 start = int(start) - 1 if start else None
79 end = int(end) - 1 if end else None
77 end = int(end) - 1 if end else None
80 else:
78 else:
81 end = int(start)
79 end = int(start)
82 start = int(start) - 1
80 start = int(start) - 1
83 yield (start, end)
81 yield (start, end)
84
82
85
83
86 @skip_doctest
84 @skip_doctest
87 def extract_symbols(code, symbols):
85 def extract_symbols(code, symbols):
88 """
86 """
89 Return a tuple (blocks, not_found)
87 Return a tuple (blocks, not_found)
90 where ``blocks`` is a list of code fragments
88 where ``blocks`` is a list of code fragments
91 for each symbol parsed from code, and ``not_found`` are
89 for each symbol parsed from code, and ``not_found`` are
92 symbols not found in the code.
90 symbols not found in the code.
93
91
94 For example::
92 For example::
95
93
96 >>> code = '''a = 10
94 >>> code = '''a = 10
97
95
98 def b(): return 42
96 def b(): return 42
99
97
100 class A: pass'''
98 class A: pass'''
101
99
102 >>> extract_symbols(code, 'A,b,z')
100 >>> extract_symbols(code, 'A,b,z')
103 (["class A: pass", "def b(): return 42"], ['z'])
101 (["class A: pass", "def b(): return 42"], ['z'])
104 """
102 """
105 symbols = symbols.split(',')
103 symbols = symbols.split(',')
106
104
107 # this will raise SyntaxError if code isn't valid Python
105 # this will raise SyntaxError if code isn't valid Python
108 py_code = ast.parse(code)
106 py_code = ast.parse(code)
109
107
110 marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
108 marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
111 code = code.split('\n')
109 code = code.split('\n')
112
110
113 symbols_lines = {}
111 symbols_lines = {}
114
112
115 # we already know the start_lineno of each symbol (marks).
113 # we already know the start_lineno of each symbol (marks).
116 # To find each end_lineno, we traverse in reverse order until each
114 # To find each end_lineno, we traverse in reverse order until each
117 # non-blank line
115 # non-blank line
118 end = len(code)
116 end = len(code)
119 for name, start in reversed(marks):
117 for name, start in reversed(marks):
120 while not code[end - 1].strip():
118 while not code[end - 1].strip():
121 end -= 1
119 end -= 1
122 if name:
120 if name:
123 symbols_lines[name] = (start - 1, end)
121 symbols_lines[name] = (start - 1, end)
124 end = start - 1
122 end = start - 1
125
123
126 # Now symbols_lines is a map
124 # Now symbols_lines is a map
127 # {'symbol_name': (start_lineno, end_lineno), ...}
125 # {'symbol_name': (start_lineno, end_lineno), ...}
128
126
129 # fill a list with chunks of codes for each requested symbol
127 # fill a list with chunks of codes for each requested symbol
130 blocks = []
128 blocks = []
131 not_found = []
129 not_found = []
132 for symbol in symbols:
130 for symbol in symbols:
133 if symbol in symbols_lines:
131 if symbol in symbols_lines:
134 start, end = symbols_lines[symbol]
132 start, end = symbols_lines[symbol]
135 blocks.append('\n'.join(code[start:end]) + '\n')
133 blocks.append('\n'.join(code[start:end]) + '\n')
136 else:
134 else:
137 not_found.append(symbol)
135 not_found.append(symbol)
138
136
139 return blocks, not_found
137 return blocks, not_found
140
138
141 def strip_initial_indent(lines):
139 def strip_initial_indent(lines):
142 """For %load, strip indent from lines until finding an unindented line.
140 """For %load, strip indent from lines until finding an unindented line.
143
141
144 https://github.com/ipython/ipython/issues/9775
142 https://github.com/ipython/ipython/issues/9775
145 """
143 """
146 indent_re = re.compile(r'\s+')
144 indent_re = re.compile(r'\s+')
147
145
148 it = iter(lines)
146 it = iter(lines)
149 first_line = next(it)
147 first_line = next(it)
150 indent_match = indent_re.match(first_line)
148 indent_match = indent_re.match(first_line)
151
149
152 if indent_match:
150 if indent_match:
153 # First line was indented
151 # First line was indented
154 indent = indent_match.group()
152 indent = indent_match.group()
155 yield first_line[len(indent):]
153 yield first_line[len(indent):]
156
154
157 for line in it:
155 for line in it:
158 if line.startswith(indent):
156 if line.startswith(indent):
159 yield line[len(indent):]
157 yield line[len(indent):]
160 else:
158 else:
161 # Less indented than the first line - stop dedenting
159 # Less indented than the first line - stop dedenting
162 yield line
160 yield line
163 break
161 break
164 else:
162 else:
165 yield first_line
163 yield first_line
166
164
167 # Pass the remaining lines through without dedenting
165 # Pass the remaining lines through without dedenting
168 for line in it:
166 for line in it:
169 yield line
167 yield line
170
168
171
169
172 class InteractivelyDefined(Exception):
170 class InteractivelyDefined(Exception):
173 """Exception for interactively defined variable in magic_edit"""
171 """Exception for interactively defined variable in magic_edit"""
174 def __init__(self, index):
172 def __init__(self, index):
175 self.index = index
173 self.index = index
176
174
177
175
178 @magics_class
176 @magics_class
179 class CodeMagics(Magics):
177 class CodeMagics(Magics):
180 """Magics related to code management (loading, saving, editing, ...)."""
178 """Magics related to code management (loading, saving, editing, ...)."""
181
179
182 def __init__(self, *args, **kwargs):
180 def __init__(self, *args, **kwargs):
183 self._knowntemps = set()
181 self._knowntemps = set()
184 super(CodeMagics, self).__init__(*args, **kwargs)
182 super(CodeMagics, self).__init__(*args, **kwargs)
185
183
186 @line_magic
184 @line_magic
187 def save(self, parameter_s=''):
185 def save(self, parameter_s=''):
188 """Save a set of lines or a macro to a given filename.
186 """Save a set of lines or a macro to a given filename.
189
187
190 Usage:\\
188 Usage:\\
191 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
189 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
192
190
193 Options:
191 Options:
194
192
195 -r: use 'raw' input. By default, the 'processed' history is used,
193 -r: use 'raw' input. By default, the 'processed' history is used,
196 so that magics are loaded in their transformed version to valid
194 so that magics are loaded in their transformed version to valid
197 Python. If this option is given, the raw input as typed as the
195 Python. If this option is given, the raw input as typed as the
198 command line is used instead.
196 command line is used instead.
199
197
200 -f: force overwrite. If file exists, %save will prompt for overwrite
198 -f: force overwrite. If file exists, %save will prompt for overwrite
201 unless -f is given.
199 unless -f is given.
202
200
203 -a: append to the file instead of overwriting it.
201 -a: append to the file instead of overwriting it.
204
202
205 This function uses the same syntax as %history for input ranges,
203 This function uses the same syntax as %history for input ranges,
206 then saves the lines to the filename you specify.
204 then saves the lines to the filename you specify.
207
205
208 It adds a '.py' extension to the file if you don't do so yourself, and
206 It adds a '.py' extension to the file if you don't do so yourself, and
209 it asks for confirmation before overwriting existing files.
207 it asks for confirmation before overwriting existing files.
210
208
211 If `-r` option is used, the default extension is `.ipy`.
209 If `-r` option is used, the default extension is `.ipy`.
212 """
210 """
213
211
214 opts,args = self.parse_options(parameter_s,'fra',mode='list')
212 opts,args = self.parse_options(parameter_s,'fra',mode='list')
215 if not args:
213 if not args:
216 raise UsageError('Missing filename.')
214 raise UsageError('Missing filename.')
217 raw = 'r' in opts
215 raw = 'r' in opts
218 force = 'f' in opts
216 force = 'f' in opts
219 append = 'a' in opts
217 append = 'a' in opts
220 mode = 'a' if append else 'w'
218 mode = 'a' if append else 'w'
221 ext = u'.ipy' if raw else u'.py'
219 ext = u'.ipy' if raw else u'.py'
222 fname, codefrom = args[0], " ".join(args[1:])
220 fname, codefrom = args[0], " ".join(args[1:])
223 if not fname.endswith((u'.py',u'.ipy')):
221 if not fname.endswith((u'.py',u'.ipy')):
224 fname += ext
222 fname += ext
225 file_exists = os.path.isfile(fname)
223 file_exists = os.path.isfile(fname)
226 if file_exists and not force and not append:
224 if file_exists and not force and not append:
227 try:
225 try:
228 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
226 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
229 except StdinNotImplementedError:
227 except StdinNotImplementedError:
230 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
228 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
231 return
229 return
232 if not overwrite :
230 if not overwrite :
233 print('Operation cancelled.')
231 print('Operation cancelled.')
234 return
232 return
235 try:
233 try:
236 cmds = self.shell.find_user_code(codefrom,raw)
234 cmds = self.shell.find_user_code(codefrom,raw)
237 except (TypeError, ValueError) as e:
235 except (TypeError, ValueError) as e:
238 print(e.args[0])
236 print(e.args[0])
239 return
237 return
240 out = py3compat.cast_unicode(cmds)
238 out = py3compat.cast_unicode(cmds)
241 with io.open(fname, mode, encoding="utf-8") as f:
239 with io.open(fname, mode, encoding="utf-8") as f:
242 if not file_exists or not append:
240 if not file_exists or not append:
243 f.write(u"# coding: utf-8\n")
241 f.write(u"# coding: utf-8\n")
244 f.write(out)
242 f.write(out)
245 # make sure we end on a newline
243 # make sure we end on a newline
246 if not out.endswith(u'\n'):
244 if not out.endswith(u'\n'):
247 f.write(u'\n')
245 f.write(u'\n')
248 print('The following commands were written to file `%s`:' % fname)
246 print('The following commands were written to file `%s`:' % fname)
249 print(cmds)
247 print(cmds)
250
248
251 @line_magic
249 @line_magic
252 def pastebin(self, parameter_s=''):
250 def pastebin(self, parameter_s=''):
253 """Upload code to Github's Gist paste bin, returning the URL.
251 """Upload code to Github's Gist paste bin, returning the URL.
254
252
255 Usage:\\
253 Usage:\\
256 %pastebin [-d "Custom description"] 1-7
254 %pastebin [-d "Custom description"] 1-7
257
255
258 The argument can be an input history range, a filename, or the name of a
256 The argument can be an input history range, a filename, or the name of a
259 string or macro.
257 string or macro.
260
258
261 Options:
259 Options:
262
260
263 -d: Pass a custom description for the gist. The default will say
261 -d: Pass a custom description for the gist. The default will say
264 "Pasted from IPython".
262 "Pasted from IPython".
265 """
263 """
266 opts, args = self.parse_options(parameter_s, 'd:')
264 opts, args = self.parse_options(parameter_s, 'd:')
267
265
268 try:
266 try:
269 code = self.shell.find_user_code(args)
267 code = self.shell.find_user_code(args)
270 except (ValueError, TypeError) as e:
268 except (ValueError, TypeError) as e:
271 print(e.args[0])
269 print(e.args[0])
272 return
270 return
273
271
274 # Deferred import
272 # Deferred import
275 try:
273 try:
276 from urllib.request import urlopen # Py 3
274 from urllib.request import urlopen # Py 3
277 except ImportError:
275 except ImportError:
278 from urllib2 import urlopen
276 from urllib2 import urlopen
279 import json
277 import json
280 post_data = json.dumps({
278 post_data = json.dumps({
281 "description": opts.get('d', "Pasted from IPython"),
279 "description": opts.get('d', "Pasted from IPython"),
282 "public": True,
280 "public": True,
283 "files": {
281 "files": {
284 "file1.py": {
282 "file1.py": {
285 "content": code
283 "content": code
286 }
284 }
287 }
285 }
288 }).encode('utf-8')
286 }).encode('utf-8')
289
287
290 response = urlopen("https://api.github.com/gists", post_data)
288 response = urlopen("https://api.github.com/gists", post_data)
291 response_data = json.loads(response.read().decode('utf-8'))
289 response_data = json.loads(response.read().decode('utf-8'))
292 return response_data['html_url']
290 return response_data['html_url']
293
291
294 @line_magic
292 @line_magic
295 def loadpy(self, arg_s):
293 def loadpy(self, arg_s):
296 """Alias of `%load`
294 """Alias of `%load`
297
295
298 `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
296 `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
299 extension. So it has been renamed simply into %load. You can look at
297 extension. So it has been renamed simply into %load. You can look at
300 `%load`'s docstring for more info.
298 `%load`'s docstring for more info.
301 """
299 """
302 self.load(arg_s)
300 self.load(arg_s)
303
301
304 @line_magic
302 @line_magic
305 def load(self, arg_s):
303 def load(self, arg_s):
306 """Load code into the current frontend.
304 """Load code into the current frontend.
307
305
308 Usage:\\
306 Usage:\\
309 %load [options] source
307 %load [options] source
310
308
311 where source can be a filename, URL, input history range, macro, or
309 where source can be a filename, URL, input history range, macro, or
312 element in the user namespace
310 element in the user namespace
313
311
314 Options:
312 Options:
315
313
316 -r <lines>: Specify lines or ranges of lines to load from the source.
314 -r <lines>: Specify lines or ranges of lines to load from the source.
317 Ranges could be specified as x-y (x..y) or in python-style x:y
315 Ranges could be specified as x-y (x..y) or in python-style x:y
318 (x..(y-1)). Both limits x and y can be left blank (meaning the
316 (x..(y-1)). Both limits x and y can be left blank (meaning the
319 beginning and end of the file, respectively).
317 beginning and end of the file, respectively).
320
318
321 -s <symbols>: Specify function or classes to load from python source.
319 -s <symbols>: Specify function or classes to load from python source.
322
320
323 -y : Don't ask confirmation for loading source above 200 000 characters.
321 -y : Don't ask confirmation for loading source above 200 000 characters.
324
322
325 -n : Include the user's namespace when searching for source code.
323 -n : Include the user's namespace when searching for source code.
326
324
327 This magic command can either take a local filename, a URL, an history
325 This magic command can either take a local filename, a URL, an history
328 range (see %history) or a macro as argument, it will prompt for
326 range (see %history) or a macro as argument, it will prompt for
329 confirmation before loading source with more than 200 000 characters, unless
327 confirmation before loading source with more than 200 000 characters, unless
330 -y flag is passed or if the frontend does not support raw_input::
328 -y flag is passed or if the frontend does not support raw_input::
331
329
332 %load myscript.py
330 %load myscript.py
333 %load 7-27
331 %load 7-27
334 %load myMacro
332 %load myMacro
335 %load http://www.example.com/myscript.py
333 %load http://www.example.com/myscript.py
336 %load -r 5-10 myscript.py
334 %load -r 5-10 myscript.py
337 %load -r 10-20,30,40: foo.py
335 %load -r 10-20,30,40: foo.py
338 %load -s MyClass,wonder_function myscript.py
336 %load -s MyClass,wonder_function myscript.py
339 %load -n MyClass
337 %load -n MyClass
340 %load -n my_module.wonder_function
338 %load -n my_module.wonder_function
341 """
339 """
342 opts,args = self.parse_options(arg_s,'yns:r:')
340 opts,args = self.parse_options(arg_s,'yns:r:')
343
341
344 if not args:
342 if not args:
345 raise UsageError('Missing filename, URL, input history range, '
343 raise UsageError('Missing filename, URL, input history range, '
346 'macro, or element in the user namespace.')
344 'macro, or element in the user namespace.')
347
345
348 search_ns = 'n' in opts
346 search_ns = 'n' in opts
349
347
350 contents = self.shell.find_user_code(args, search_ns=search_ns)
348 contents = self.shell.find_user_code(args, search_ns=search_ns)
351
349
352 if 's' in opts:
350 if 's' in opts:
353 try:
351 try:
354 blocks, not_found = extract_symbols(contents, opts['s'])
352 blocks, not_found = extract_symbols(contents, opts['s'])
355 except SyntaxError:
353 except SyntaxError:
356 # non python code
354 # non python code
357 error("Unable to parse the input as valid Python code")
355 error("Unable to parse the input as valid Python code")
358 return
356 return
359
357
360 if len(not_found) == 1:
358 if len(not_found) == 1:
361 warn('The symbol `%s` was not found' % not_found[0])
359 warn('The symbol `%s` was not found' % not_found[0])
362 elif len(not_found) > 1:
360 elif len(not_found) > 1:
363 warn('The symbols %s were not found' % get_text_list(not_found,
361 warn('The symbols %s were not found' % get_text_list(not_found,
364 wrap_item_with='`')
362 wrap_item_with='`')
365 )
363 )
366
364
367 contents = '\n'.join(blocks)
365 contents = '\n'.join(blocks)
368
366
369 if 'r' in opts:
367 if 'r' in opts:
370 ranges = opts['r'].replace(',', ' ')
368 ranges = opts['r'].replace(',', ' ')
371 lines = contents.split('\n')
369 lines = contents.split('\n')
372 slices = extract_code_ranges(ranges)
370 slices = extract_code_ranges(ranges)
373 contents = [lines[slice(*slc)] for slc in slices]
371 contents = [lines[slice(*slc)] for slc in slices]
374 contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
372 contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
375
373
376 l = len(contents)
374 l = len(contents)
377
375
378 # 200 000 is ~ 2500 full 80 caracter lines
376 # 200 000 is ~ 2500 full 80 caracter lines
379 # so in average, more than 5000 lines
377 # so in average, more than 5000 lines
380 if l > 200000 and 'y' not in opts:
378 if l > 200000 and 'y' not in opts:
381 try:
379 try:
382 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
380 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
383 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
381 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
384 except StdinNotImplementedError:
382 except StdinNotImplementedError:
385 #asume yes if raw input not implemented
383 #asume yes if raw input not implemented
386 ans = True
384 ans = True
387
385
388 if ans is False :
386 if ans is False :
389 print('Operation cancelled.')
387 print('Operation cancelled.')
390 return
388 return
391
389
392 contents = "# %load {}\n".format(arg_s) + contents
390 contents = "# %load {}\n".format(arg_s) + contents
393
391
394 self.shell.set_next_input(contents, replace=True)
392 self.shell.set_next_input(contents, replace=True)
395
393
396 @staticmethod
394 @staticmethod
397 def _find_edit_target(shell, args, opts, last_call):
395 def _find_edit_target(shell, args, opts, last_call):
398 """Utility method used by magic_edit to find what to edit."""
396 """Utility method used by magic_edit to find what to edit."""
399
397
400 def make_filename(arg):
398 def make_filename(arg):
401 "Make a filename from the given args"
399 "Make a filename from the given args"
402 try:
400 try:
403 filename = get_py_filename(arg)
401 filename = get_py_filename(arg)
404 except IOError:
402 except IOError:
405 # If it ends with .py but doesn't already exist, assume we want
403 # If it ends with .py but doesn't already exist, assume we want
406 # a new file.
404 # a new file.
407 if arg.endswith('.py'):
405 if arg.endswith('.py'):
408 filename = arg
406 filename = arg
409 else:
407 else:
410 filename = None
408 filename = None
411 return filename
409 return filename
412
410
413 # Set a few locals from the options for convenience:
411 # Set a few locals from the options for convenience:
414 opts_prev = 'p' in opts
412 opts_prev = 'p' in opts
415 opts_raw = 'r' in opts
413 opts_raw = 'r' in opts
416
414
417 # custom exceptions
415 # custom exceptions
418 class DataIsObject(Exception): pass
416 class DataIsObject(Exception): pass
419
417
420 # Default line number value
418 # Default line number value
421 lineno = opts.get('n',None)
419 lineno = opts.get('n',None)
422
420
423 if opts_prev:
421 if opts_prev:
424 args = '_%s' % last_call[0]
422 args = '_%s' % last_call[0]
425 if args not in shell.user_ns:
423 if args not in shell.user_ns:
426 args = last_call[1]
424 args = last_call[1]
427
425
428 # by default this is done with temp files, except when the given
426 # by default this is done with temp files, except when the given
429 # arg is a filename
427 # arg is a filename
430 use_temp = True
428 use_temp = True
431
429
432 data = ''
430 data = ''
433
431
434 # First, see if the arguments should be a filename.
432 # First, see if the arguments should be a filename.
435 filename = make_filename(args)
433 filename = make_filename(args)
436 if filename:
434 if filename:
437 use_temp = False
435 use_temp = False
438 elif args:
436 elif args:
439 # Mode where user specifies ranges of lines, like in %macro.
437 # Mode where user specifies ranges of lines, like in %macro.
440 data = shell.extract_input_lines(args, opts_raw)
438 data = shell.extract_input_lines(args, opts_raw)
441 if not data:
439 if not data:
442 try:
440 try:
443 # Load the parameter given as a variable. If not a string,
441 # Load the parameter given as a variable. If not a string,
444 # process it as an object instead (below)
442 # process it as an object instead (below)
445
443
446 #print '*** args',args,'type',type(args) # dbg
444 #print '*** args',args,'type',type(args) # dbg
447 data = eval(args, shell.user_ns)
445 data = eval(args, shell.user_ns)
448 if not isinstance(data, string_types):
446 if not isinstance(data, string_types):
449 raise DataIsObject
447 raise DataIsObject
450
448
451 except (NameError,SyntaxError):
449 except (NameError,SyntaxError):
452 # given argument is not a variable, try as a filename
450 # given argument is not a variable, try as a filename
453 filename = make_filename(args)
451 filename = make_filename(args)
454 if filename is None:
452 if filename is None:
455 warn("Argument given (%s) can't be found as a variable "
453 warn("Argument given (%s) can't be found as a variable "
456 "or as a filename." % args)
454 "or as a filename." % args)
457 return (None, None, None)
455 return (None, None, None)
458 use_temp = False
456 use_temp = False
459
457
460 except DataIsObject:
458 except DataIsObject:
461 # macros have a special edit function
459 # macros have a special edit function
462 if isinstance(data, Macro):
460 if isinstance(data, Macro):
463 raise MacroToEdit(data)
461 raise MacroToEdit(data)
464
462
465 # For objects, try to edit the file where they are defined
463 # For objects, try to edit the file where they are defined
466 filename = find_file(data)
464 filename = find_file(data)
467 if filename:
465 if filename:
468 if 'fakemodule' in filename.lower() and \
466 if 'fakemodule' in filename.lower() and \
469 inspect.isclass(data):
467 inspect.isclass(data):
470 # class created by %edit? Try to find source
468 # class created by %edit? Try to find source
471 # by looking for method definitions instead, the
469 # by looking for method definitions instead, the
472 # __module__ in those classes is FakeModule.
470 # __module__ in those classes is FakeModule.
473 attrs = [getattr(data, aname) for aname in dir(data)]
471 attrs = [getattr(data, aname) for aname in dir(data)]
474 for attr in attrs:
472 for attr in attrs:
475 if not inspect.ismethod(attr):
473 if not inspect.ismethod(attr):
476 continue
474 continue
477 filename = find_file(attr)
475 filename = find_file(attr)
478 if filename and \
476 if filename and \
479 'fakemodule' not in filename.lower():
477 'fakemodule' not in filename.lower():
480 # change the attribute to be the edit
478 # change the attribute to be the edit
481 # target instead
479 # target instead
482 data = attr
480 data = attr
483 break
481 break
484
482
485 m = ipython_input_pat.match(os.path.basename(filename))
483 m = ipython_input_pat.match(os.path.basename(filename))
486 if m:
484 if m:
487 raise InteractivelyDefined(int(m.groups()[0]))
485 raise InteractivelyDefined(int(m.groups()[0]))
488
486
489 datafile = 1
487 datafile = 1
490 if filename is None:
488 if filename is None:
491 filename = make_filename(args)
489 filename = make_filename(args)
492 datafile = 1
490 datafile = 1
493 if filename is not None:
491 if filename is not None:
494 # only warn about this if we get a real name
492 # only warn about this if we get a real name
495 warn('Could not find file where `%s` is defined.\n'
493 warn('Could not find file where `%s` is defined.\n'
496 'Opening a file named `%s`' % (args, filename))
494 'Opening a file named `%s`' % (args, filename))
497 # Now, make sure we can actually read the source (if it was
495 # Now, make sure we can actually read the source (if it was
498 # in a temp file it's gone by now).
496 # in a temp file it's gone by now).
499 if datafile:
497 if datafile:
500 if lineno is None:
498 if lineno is None:
501 lineno = find_source_lines(data)
499 lineno = find_source_lines(data)
502 if lineno is None:
500 if lineno is None:
503 filename = make_filename(args)
501 filename = make_filename(args)
504 if filename is None:
502 if filename is None:
505 warn('The file where `%s` was defined '
503 warn('The file where `%s` was defined '
506 'cannot be read or found.' % data)
504 'cannot be read or found.' % data)
507 return (None, None, None)
505 return (None, None, None)
508 use_temp = False
506 use_temp = False
509
507
510 if use_temp:
508 if use_temp:
511 filename = shell.mktempfile(data)
509 filename = shell.mktempfile(data)
512 print('IPython will make a temporary file named:',filename)
510 print('IPython will make a temporary file named:',filename)
513
511
514 # use last_call to remember the state of the previous call, but don't
512 # use last_call to remember the state of the previous call, but don't
515 # let it be clobbered by successive '-p' calls.
513 # let it be clobbered by successive '-p' calls.
516 try:
514 try:
517 last_call[0] = shell.displayhook.prompt_count
515 last_call[0] = shell.displayhook.prompt_count
518 if not opts_prev:
516 if not opts_prev:
519 last_call[1] = args
517 last_call[1] = args
520 except:
518 except:
521 pass
519 pass
522
520
523
521
524 return filename, lineno, use_temp
522 return filename, lineno, use_temp
525
523
526 def _edit_macro(self,mname,macro):
524 def _edit_macro(self,mname,macro):
527 """open an editor with the macro data in a file"""
525 """open an editor with the macro data in a file"""
528 filename = self.shell.mktempfile(macro.value)
526 filename = self.shell.mktempfile(macro.value)
529 self.shell.hooks.editor(filename)
527 self.shell.hooks.editor(filename)
530
528
531 # and make a new macro object, to replace the old one
529 # and make a new macro object, to replace the old one
532 with open(filename) as mfile:
530 with open(filename) as mfile:
533 mvalue = mfile.read()
531 mvalue = mfile.read()
534 self.shell.user_ns[mname] = Macro(mvalue)
532 self.shell.user_ns[mname] = Macro(mvalue)
535
533
536 @skip_doctest
534 @skip_doctest
537 @line_magic
535 @line_magic
538 def edit(self, parameter_s='',last_call=['','']):
536 def edit(self, parameter_s='',last_call=['','']):
539 """Bring up an editor and execute the resulting code.
537 """Bring up an editor and execute the resulting code.
540
538
541 Usage:
539 Usage:
542 %edit [options] [args]
540 %edit [options] [args]
543
541
544 %edit runs IPython's editor hook. The default version of this hook is
542 %edit runs IPython's editor hook. The default version of this hook is
545 set to call the editor specified by your $EDITOR environment variable.
543 set to call the editor specified by your $EDITOR environment variable.
546 If this isn't found, it will default to vi under Linux/Unix and to
544 If this isn't found, it will default to vi under Linux/Unix and to
547 notepad under Windows. See the end of this docstring for how to change
545 notepad under Windows. See the end of this docstring for how to change
548 the editor hook.
546 the editor hook.
549
547
550 You can also set the value of this editor via the
548 You can also set the value of this editor via the
551 ``TerminalInteractiveShell.editor`` option in your configuration file.
549 ``TerminalInteractiveShell.editor`` option in your configuration file.
552 This is useful if you wish to use a different editor from your typical
550 This is useful if you wish to use a different editor from your typical
553 default with IPython (and for Windows users who typically don't set
551 default with IPython (and for Windows users who typically don't set
554 environment variables).
552 environment variables).
555
553
556 This command allows you to conveniently edit multi-line code right in
554 This command allows you to conveniently edit multi-line code right in
557 your IPython session.
555 your IPython session.
558
556
559 If called without arguments, %edit opens up an empty editor with a
557 If called without arguments, %edit opens up an empty editor with a
560 temporary file and will execute the contents of this file when you
558 temporary file and will execute the contents of this file when you
561 close it (don't forget to save it!).
559 close it (don't forget to save it!).
562
560
563
561
564 Options:
562 Options:
565
563
566 -n <number>: open the editor at a specified line number. By default,
564 -n <number>: open the editor at a specified line number. By default,
567 the IPython editor hook uses the unix syntax 'editor +N filename', but
565 the IPython editor hook uses the unix syntax 'editor +N filename', but
568 you can configure this by providing your own modified hook if your
566 you can configure this by providing your own modified hook if your
569 favorite editor supports line-number specifications with a different
567 favorite editor supports line-number specifications with a different
570 syntax.
568 syntax.
571
569
572 -p: this will call the editor with the same data as the previous time
570 -p: this will call the editor with the same data as the previous time
573 it was used, regardless of how long ago (in your current session) it
571 it was used, regardless of how long ago (in your current session) it
574 was.
572 was.
575
573
576 -r: use 'raw' input. This option only applies to input taken from the
574 -r: use 'raw' input. This option only applies to input taken from the
577 user's history. By default, the 'processed' history is used, so that
575 user's history. By default, the 'processed' history is used, so that
578 magics are loaded in their transformed version to valid Python. If
576 magics are loaded in their transformed version to valid Python. If
579 this option is given, the raw input as typed as the command line is
577 this option is given, the raw input as typed as the command line is
580 used instead. When you exit the editor, it will be executed by
578 used instead. When you exit the editor, it will be executed by
581 IPython's own processor.
579 IPython's own processor.
582
580
583 -x: do not execute the edited code immediately upon exit. This is
581 -x: do not execute the edited code immediately upon exit. This is
584 mainly useful if you are editing programs which need to be called with
582 mainly useful if you are editing programs which need to be called with
585 command line arguments, which you can then do using %run.
583 command line arguments, which you can then do using %run.
586
584
587
585
588 Arguments:
586 Arguments:
589
587
590 If arguments are given, the following possibilities exist:
588 If arguments are given, the following possibilities exist:
591
589
592 - If the argument is a filename, IPython will load that into the
590 - If the argument is a filename, IPython will load that into the
593 editor. It will execute its contents with execfile() when you exit,
591 editor. It will execute its contents with execfile() when you exit,
594 loading any code in the file into your interactive namespace.
592 loading any code in the file into your interactive namespace.
595
593
596 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
594 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
597 The syntax is the same as in the %history magic.
595 The syntax is the same as in the %history magic.
598
596
599 - If the argument is a string variable, its contents are loaded
597 - If the argument is a string variable, its contents are loaded
600 into the editor. You can thus edit any string which contains
598 into the editor. You can thus edit any string which contains
601 python code (including the result of previous edits).
599 python code (including the result of previous edits).
602
600
603 - If the argument is the name of an object (other than a string),
601 - If the argument is the name of an object (other than a string),
604 IPython will try to locate the file where it was defined and open the
602 IPython will try to locate the file where it was defined and open the
605 editor at the point where it is defined. You can use `%edit function`
603 editor at the point where it is defined. You can use `%edit function`
606 to load an editor exactly at the point where 'function' is defined,
604 to load an editor exactly at the point where 'function' is defined,
607 edit it and have the file be executed automatically.
605 edit it and have the file be executed automatically.
608
606
609 - If the object is a macro (see %macro for details), this opens up your
607 - If the object is a macro (see %macro for details), this opens up your
610 specified editor with a temporary file containing the macro's data.
608 specified editor with a temporary file containing the macro's data.
611 Upon exit, the macro is reloaded with the contents of the file.
609 Upon exit, the macro is reloaded with the contents of the file.
612
610
613 Note: opening at an exact line is only supported under Unix, and some
611 Note: opening at an exact line is only supported under Unix, and some
614 editors (like kedit and gedit up to Gnome 2.8) do not understand the
612 editors (like kedit and gedit up to Gnome 2.8) do not understand the
615 '+NUMBER' parameter necessary for this feature. Good editors like
613 '+NUMBER' parameter necessary for this feature. Good editors like
616 (X)Emacs, vi, jed, pico and joe all do.
614 (X)Emacs, vi, jed, pico and joe all do.
617
615
618 After executing your code, %edit will return as output the code you
616 After executing your code, %edit will return as output the code you
619 typed in the editor (except when it was an existing file). This way
617 typed in the editor (except when it was an existing file). This way
620 you can reload the code in further invocations of %edit as a variable,
618 you can reload the code in further invocations of %edit as a variable,
621 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
619 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
622 the output.
620 the output.
623
621
624 Note that %edit is also available through the alias %ed.
622 Note that %edit is also available through the alias %ed.
625
623
626 This is an example of creating a simple function inside the editor and
624 This is an example of creating a simple function inside the editor and
627 then modifying it. First, start up the editor::
625 then modifying it. First, start up the editor::
628
626
629 In [1]: edit
627 In [1]: edit
630 Editing... done. Executing edited code...
628 Editing... done. Executing edited code...
631 Out[1]: 'def foo():\\n print "foo() was defined in an editing
629 Out[1]: 'def foo():\\n print "foo() was defined in an editing
632 session"\\n'
630 session"\\n'
633
631
634 We can then call the function foo()::
632 We can then call the function foo()::
635
633
636 In [2]: foo()
634 In [2]: foo()
637 foo() was defined in an editing session
635 foo() was defined in an editing session
638
636
639 Now we edit foo. IPython automatically loads the editor with the
637 Now we edit foo. IPython automatically loads the editor with the
640 (temporary) file where foo() was previously defined::
638 (temporary) file where foo() was previously defined::
641
639
642 In [3]: edit foo
640 In [3]: edit foo
643 Editing... done. Executing edited code...
641 Editing... done. Executing edited code...
644
642
645 And if we call foo() again we get the modified version::
643 And if we call foo() again we get the modified version::
646
644
647 In [4]: foo()
645 In [4]: foo()
648 foo() has now been changed!
646 foo() has now been changed!
649
647
650 Here is an example of how to edit a code snippet successive
648 Here is an example of how to edit a code snippet successive
651 times. First we call the editor::
649 times. First we call the editor::
652
650
653 In [5]: edit
651 In [5]: edit
654 Editing... done. Executing edited code...
652 Editing... done. Executing edited code...
655 hello
653 hello
656 Out[5]: "print 'hello'\\n"
654 Out[5]: "print 'hello'\\n"
657
655
658 Now we call it again with the previous output (stored in _)::
656 Now we call it again with the previous output (stored in _)::
659
657
660 In [6]: edit _
658 In [6]: edit _
661 Editing... done. Executing edited code...
659 Editing... done. Executing edited code...
662 hello world
660 hello world
663 Out[6]: "print 'hello world'\\n"
661 Out[6]: "print 'hello world'\\n"
664
662
665 Now we call it with the output #8 (stored in _8, also as Out[8])::
663 Now we call it with the output #8 (stored in _8, also as Out[8])::
666
664
667 In [7]: edit _8
665 In [7]: edit _8
668 Editing... done. Executing edited code...
666 Editing... done. Executing edited code...
669 hello again
667 hello again
670 Out[7]: "print 'hello again'\\n"
668 Out[7]: "print 'hello again'\\n"
671
669
672
670
673 Changing the default editor hook:
671 Changing the default editor hook:
674
672
675 If you wish to write your own editor hook, you can put it in a
673 If you wish to write your own editor hook, you can put it in a
676 configuration file which you load at startup time. The default hook
674 configuration file which you load at startup time. The default hook
677 is defined in the IPython.core.hooks module, and you can use that as a
675 is defined in the IPython.core.hooks module, and you can use that as a
678 starting example for further modifications. That file also has
676 starting example for further modifications. That file also has
679 general instructions on how to set a new hook for use once you've
677 general instructions on how to set a new hook for use once you've
680 defined it."""
678 defined it."""
681 opts,args = self.parse_options(parameter_s,'prxn:')
679 opts,args = self.parse_options(parameter_s,'prxn:')
682
680
683 try:
681 try:
684 filename, lineno, is_temp = self._find_edit_target(self.shell,
682 filename, lineno, is_temp = self._find_edit_target(self.shell,
685 args, opts, last_call)
683 args, opts, last_call)
686 except MacroToEdit as e:
684 except MacroToEdit as e:
687 self._edit_macro(args, e.args[0])
685 self._edit_macro(args, e.args[0])
688 return
686 return
689 except InteractivelyDefined as e:
687 except InteractivelyDefined as e:
690 print("Editing In[%i]" % e.index)
688 print("Editing In[%i]" % e.index)
691 args = str(e.index)
689 args = str(e.index)
692 filename, lineno, is_temp = self._find_edit_target(self.shell,
690 filename, lineno, is_temp = self._find_edit_target(self.shell,
693 args, opts, last_call)
691 args, opts, last_call)
694 if filename is None:
692 if filename is None:
695 # nothing was found, warnings have already been issued,
693 # nothing was found, warnings have already been issued,
696 # just give up.
694 # just give up.
697 return
695 return
698
696
699 if is_temp:
697 if is_temp:
700 self._knowntemps.add(filename)
698 self._knowntemps.add(filename)
701 elif (filename in self._knowntemps):
699 elif (filename in self._knowntemps):
702 is_temp = True
700 is_temp = True
703
701
704
702
705 # do actual editing here
703 # do actual editing here
706 print('Editing...', end=' ')
704 print('Editing...', end=' ')
707 sys.stdout.flush()
705 sys.stdout.flush()
708 try:
706 try:
709 # Quote filenames that may have spaces in them
707 # Quote filenames that may have spaces in them
710 if ' ' in filename:
708 if ' ' in filename:
711 filename = "'%s'" % filename
709 filename = "'%s'" % filename
712 self.shell.hooks.editor(filename,lineno)
710 self.shell.hooks.editor(filename,lineno)
713 except TryNext:
711 except TryNext:
714 warn('Could not open editor')
712 warn('Could not open editor')
715 return
713 return
716
714
717 # XXX TODO: should this be generalized for all string vars?
715 # XXX TODO: should this be generalized for all string vars?
718 # For now, this is special-cased to blocks created by cpaste
716 # For now, this is special-cased to blocks created by cpaste
719 if args.strip() == 'pasted_block':
717 if args.strip() == 'pasted_block':
720 with open(filename, 'r') as f:
718 with open(filename, 'r') as f:
721 self.shell.user_ns['pasted_block'] = f.read()
719 self.shell.user_ns['pasted_block'] = f.read()
722
720
723 if 'x' in opts: # -x prevents actual execution
721 if 'x' in opts: # -x prevents actual execution
724 print()
722 print()
725 else:
723 else:
726 print('done. Executing edited code...')
724 print('done. Executing edited code...')
727 with preserve_keys(self.shell.user_ns, '__file__'):
725 with preserve_keys(self.shell.user_ns, '__file__'):
728 if not is_temp:
726 if not is_temp:
729 self.shell.user_ns['__file__'] = filename
727 self.shell.user_ns['__file__'] = filename
730 if 'r' in opts: # Untranslated IPython code
728 if 'r' in opts: # Untranslated IPython code
731 with open(filename, 'r') as f:
729 with open(filename, 'r') as f:
732 source = f.read()
730 source = f.read()
733 self.shell.run_cell(source, store_history=False)
731 self.shell.run_cell(source, store_history=False)
734 else:
732 else:
735 self.shell.safe_execfile(filename, self.shell.user_ns,
733 self.shell.safe_execfile(filename, self.shell.user_ns,
736 self.shell.user_ns)
734 self.shell.user_ns)
737
735
738 if is_temp:
736 if is_temp:
739 try:
737 try:
740 return open(filename).read()
738 return open(filename).read()
741 except IOError as msg:
739 except IOError as msg:
742 if msg.filename == filename:
740 if msg.filename == filename:
743 warn('File not found. Did you forget to save?')
741 warn('File not found. Did you forget to save?')
744 return
742 return
745 else:
743 else:
746 self.shell.showtraceback()
744 self.shell.showtraceback()
@@ -1,159 +1,157 b''
1 """Implementation of configuration-related magic functions.
1 """Implementation of configuration-related magic functions.
2 """
2 """
3 from __future__ import print_function
4 from __future__ import absolute_import
5 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
6 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
7 #
5 #
8 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
9 #
7 #
10 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
12
10
13 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
14 # Imports
12 # Imports
15 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
16
14
17 # Stdlib
15 # Stdlib
18 import re
16 import re
19
17
20 # Our own packages
18 # Our own packages
21 from IPython.core.error import UsageError
19 from IPython.core.error import UsageError
22 from IPython.core.magic import Magics, magics_class, line_magic
20 from IPython.core.magic import Magics, magics_class, line_magic
23 from logging import error
21 from logging import error
24
22
25 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
26 # Magic implementation classes
24 # Magic implementation classes
27 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
28
26
29 reg = re.compile('^\w+\.\w+$')
27 reg = re.compile('^\w+\.\w+$')
30 @magics_class
28 @magics_class
31 class ConfigMagics(Magics):
29 class ConfigMagics(Magics):
32
30
33 def __init__(self, shell):
31 def __init__(self, shell):
34 super(ConfigMagics, self).__init__(shell)
32 super(ConfigMagics, self).__init__(shell)
35 self.configurables = []
33 self.configurables = []
36
34
37 @line_magic
35 @line_magic
38 def config(self, s):
36 def config(self, s):
39 """configure IPython
37 """configure IPython
40
38
41 %config Class[.trait=value]
39 %config Class[.trait=value]
42
40
43 This magic exposes most of the IPython config system. Any
41 This magic exposes most of the IPython config system. Any
44 Configurable class should be able to be configured with the simple
42 Configurable class should be able to be configured with the simple
45 line::
43 line::
46
44
47 %config Class.trait=value
45 %config Class.trait=value
48
46
49 Where `value` will be resolved in the user's namespace, if it is an
47 Where `value` will be resolved in the user's namespace, if it is an
50 expression or variable name.
48 expression or variable name.
51
49
52 Examples
50 Examples
53 --------
51 --------
54
52
55 To see what classes are available for config, pass no arguments::
53 To see what classes are available for config, pass no arguments::
56
54
57 In [1]: %config
55 In [1]: %config
58 Available objects for config:
56 Available objects for config:
59 TerminalInteractiveShell
57 TerminalInteractiveShell
60 HistoryManager
58 HistoryManager
61 PrefilterManager
59 PrefilterManager
62 AliasManager
60 AliasManager
63 IPCompleter
61 IPCompleter
64 DisplayFormatter
62 DisplayFormatter
65
63
66 To view what is configurable on a given class, just pass the class
64 To view what is configurable on a given class, just pass the class
67 name::
65 name::
68
66
69 In [2]: %config IPCompleter
67 In [2]: %config IPCompleter
70 IPCompleter options
68 IPCompleter options
71 -----------------
69 -----------------
72 IPCompleter.omit__names=<Enum>
70 IPCompleter.omit__names=<Enum>
73 Current: 2
71 Current: 2
74 Choices: (0, 1, 2)
72 Choices: (0, 1, 2)
75 Instruct the completer to omit private method names
73 Instruct the completer to omit private method names
76 Specifically, when completing on ``object.<tab>``.
74 Specifically, when completing on ``object.<tab>``.
77 When 2 [default]: all names that start with '_' will be excluded.
75 When 2 [default]: all names that start with '_' will be excluded.
78 When 1: all 'magic' names (``__foo__``) will be excluded.
76 When 1: all 'magic' names (``__foo__``) will be excluded.
79 When 0: nothing will be excluded.
77 When 0: nothing will be excluded.
80 IPCompleter.merge_completions=<CBool>
78 IPCompleter.merge_completions=<CBool>
81 Current: True
79 Current: True
82 Whether to merge completion results into a single list
80 Whether to merge completion results into a single list
83 If False, only the completion results from the first non-empty
81 If False, only the completion results from the first non-empty
84 completer will be returned.
82 completer will be returned.
85 IPCompleter.limit_to__all__=<CBool>
83 IPCompleter.limit_to__all__=<CBool>
86 Current: False
84 Current: False
87 Instruct the completer to use __all__ for the completion
85 Instruct the completer to use __all__ for the completion
88 Specifically, when completing on ``object.<tab>``.
86 Specifically, when completing on ``object.<tab>``.
89 When True: only those names in obj.__all__ will be included.
87 When True: only those names in obj.__all__ will be included.
90 When False [default]: the __all__ attribute is ignored
88 When False [default]: the __all__ attribute is ignored
91 IPCompleter.greedy=<CBool>
89 IPCompleter.greedy=<CBool>
92 Current: False
90 Current: False
93 Activate greedy completion
91 Activate greedy completion
94 This will enable completion on elements of lists, results of
92 This will enable completion on elements of lists, results of
95 function calls, etc., but can be unsafe because the code is
93 function calls, etc., but can be unsafe because the code is
96 actually evaluated on TAB.
94 actually evaluated on TAB.
97
95
98 but the real use is in setting values::
96 but the real use is in setting values::
99
97
100 In [3]: %config IPCompleter.greedy = True
98 In [3]: %config IPCompleter.greedy = True
101
99
102 and these values are read from the user_ns if they are variables::
100 and these values are read from the user_ns if they are variables::
103
101
104 In [4]: feeling_greedy=False
102 In [4]: feeling_greedy=False
105
103
106 In [5]: %config IPCompleter.greedy = feeling_greedy
104 In [5]: %config IPCompleter.greedy = feeling_greedy
107
105
108 """
106 """
109 from traitlets.config.loader import Config
107 from traitlets.config.loader import Config
110 # some IPython objects are Configurable, but do not yet have
108 # some IPython objects are Configurable, but do not yet have
111 # any configurable traits. Exclude them from the effects of
109 # any configurable traits. Exclude them from the effects of
112 # this magic, as their presence is just noise:
110 # this magic, as their presence is just noise:
113 configurables = [ c for c in self.shell.configurables
111 configurables = [ c for c in self.shell.configurables
114 if c.__class__.class_traits(config=True) ]
112 if c.__class__.class_traits(config=True) ]
115 classnames = [ c.__class__.__name__ for c in configurables ]
113 classnames = [ c.__class__.__name__ for c in configurables ]
116
114
117 line = s.strip()
115 line = s.strip()
118 if not line:
116 if not line:
119 # print available configurable names
117 # print available configurable names
120 print("Available objects for config:")
118 print("Available objects for config:")
121 for name in classnames:
119 for name in classnames:
122 print(" ", name)
120 print(" ", name)
123 return
121 return
124 elif line in classnames:
122 elif line in classnames:
125 # `%config TerminalInteractiveShell` will print trait info for
123 # `%config TerminalInteractiveShell` will print trait info for
126 # TerminalInteractiveShell
124 # TerminalInteractiveShell
127 c = configurables[classnames.index(line)]
125 c = configurables[classnames.index(line)]
128 cls = c.__class__
126 cls = c.__class__
129 help = cls.class_get_help(c)
127 help = cls.class_get_help(c)
130 # strip leading '--' from cl-args:
128 # strip leading '--' from cl-args:
131 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
129 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
132 print(help)
130 print(help)
133 return
131 return
134 elif reg.match(line):
132 elif reg.match(line):
135 cls, attr = line.split('.')
133 cls, attr = line.split('.')
136 return getattr(configurables[classnames.index(cls)],attr)
134 return getattr(configurables[classnames.index(cls)],attr)
137 elif '=' not in line:
135 elif '=' not in line:
138 msg = "Invalid config statement: %r, "\
136 msg = "Invalid config statement: %r, "\
139 "should be `Class.trait = value`."
137 "should be `Class.trait = value`."
140
138
141 ll = line.lower()
139 ll = line.lower()
142 for classname in classnames:
140 for classname in classnames:
143 if ll == classname.lower():
141 if ll == classname.lower():
144 msg = msg + '\nDid you mean %s (note the case)?' % classname
142 msg = msg + '\nDid you mean %s (note the case)?' % classname
145 break
143 break
146
144
147 raise UsageError( msg % line)
145 raise UsageError( msg % line)
148
146
149 # otherwise, assume we are setting configurables.
147 # otherwise, assume we are setting configurables.
150 # leave quotes on args when splitting, because we want
148 # leave quotes on args when splitting, because we want
151 # unquoted args to eval in user_ns
149 # unquoted args to eval in user_ns
152 cfg = Config()
150 cfg = Config()
153 exec("cfg."+line, locals(), self.shell.user_ns)
151 exec("cfg."+line, locals(), self.shell.user_ns)
154
152
155 for configurable in configurables:
153 for configurable in configurables:
156 try:
154 try:
157 configurable.update_config(cfg)
155 configurable.update_config(cfg)
158 except Exception as e:
156 except Exception as e:
159 error(e)
157 error(e)
@@ -1,1370 +1,1368 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions."""
2 """Implementation of execution-related magic functions."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
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 import ast
8 import ast
11 import bdb
9 import bdb
12 import gc
10 import gc
13 import itertools
11 import itertools
14 import os
12 import os
15 import sys
13 import sys
16 import time
14 import time
17 import timeit
15 import timeit
18 import math
16 import math
19 from pdb import Restart
17 from pdb import Restart
20
18
21 # cProfile was added in Python2.5
19 # cProfile was added in Python2.5
22 try:
20 try:
23 import cProfile as profile
21 import cProfile as profile
24 import pstats
22 import pstats
25 except ImportError:
23 except ImportError:
26 # profile isn't bundled by default in Debian for license reasons
24 # profile isn't bundled by default in Debian for license reasons
27 try:
25 try:
28 import profile, pstats
26 import profile, pstats
29 except ImportError:
27 except ImportError:
30 profile = pstats = None
28 profile = pstats = None
31
29
32 from IPython.core import oinspect
30 from IPython.core import oinspect
33 from IPython.core import magic_arguments
31 from IPython.core import magic_arguments
34 from IPython.core import page
32 from IPython.core import page
35 from IPython.core.error import UsageError
33 from IPython.core.error import UsageError
36 from IPython.core.macro import Macro
34 from IPython.core.macro import Macro
37 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
38 line_cell_magic, on_off, needs_local_scope)
36 line_cell_magic, on_off, needs_local_scope)
39 from IPython.testing.skipdoctest import skip_doctest
37 from IPython.testing.skipdoctest import skip_doctest
40 from IPython.utils import py3compat
38 from IPython.utils import py3compat
41 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
39 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
42 from IPython.utils.contexts import preserve_keys
40 from IPython.utils.contexts import preserve_keys
43 from IPython.utils.capture import capture_output
41 from IPython.utils.capture import capture_output
44 from IPython.utils.ipstruct import Struct
42 from IPython.utils.ipstruct import Struct
45 from IPython.utils.module_paths import find_mod
43 from IPython.utils.module_paths import find_mod
46 from IPython.utils.path import get_py_filename, shellglob
44 from IPython.utils.path import get_py_filename, shellglob
47 from IPython.utils.timing import clock, clock2
45 from IPython.utils.timing import clock, clock2
48 from warnings import warn
46 from warnings import warn
49 from logging import error
47 from logging import error
50
48
51 if PY3:
49 if PY3:
52 from io import StringIO
50 from io import StringIO
53 else:
51 else:
54 from StringIO import StringIO
52 from StringIO import StringIO
55
53
56 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
57 # Magic implementation classes
55 # Magic implementation classes
58 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
59
57
60
58
61 class TimeitResult(object):
59 class TimeitResult(object):
62 """
60 """
63 Object returned by the timeit magic with info about the run.
61 Object returned by the timeit magic with info about the run.
64
62
65 Contains the following attributes :
63 Contains the following attributes :
66
64
67 loops: (int) number of loops done per measurement
65 loops: (int) number of loops done per measurement
68 repeat: (int) number of times the measurement has been repeated
66 repeat: (int) number of times the measurement has been repeated
69 best: (float) best execution time / number
67 best: (float) best execution time / number
70 all_runs: (list of float) execution time of each run (in s)
68 all_runs: (list of float) execution time of each run (in s)
71 compile_time: (float) time of statement compilation (s)
69 compile_time: (float) time of statement compilation (s)
72
70
73 """
71 """
74 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
72 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
75 self.loops = loops
73 self.loops = loops
76 self.repeat = repeat
74 self.repeat = repeat
77 self.best = best
75 self.best = best
78 self.worst = worst
76 self.worst = worst
79 self.all_runs = all_runs
77 self.all_runs = all_runs
80 self.compile_time = compile_time
78 self.compile_time = compile_time
81 self._precision = precision
79 self._precision = precision
82 self.timings = [ dt / self.loops for dt in all_runs]
80 self.timings = [ dt / self.loops for dt in all_runs]
83
81
84 @property
82 @property
85 def average(self):
83 def average(self):
86 return math.fsum(self.timings) / len(self.timings)
84 return math.fsum(self.timings) / len(self.timings)
87
85
88 @property
86 @property
89 def stdev(self):
87 def stdev(self):
90 mean = self.average
88 mean = self.average
91 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
89 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
92
90
93 def __str__(self):
91 def __str__(self):
94 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
92 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
95 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
93 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
96 _format_time(self.average, self._precision),
94 _format_time(self.average, self._precision),
97 _format_time(self.stdev, self._precision)))
95 _format_time(self.stdev, self._precision)))
98
96
99 def _repr_pretty_(self, p , cycle):
97 def _repr_pretty_(self, p , cycle):
100 unic = self.__str__()
98 unic = self.__str__()
101 p.text(u'<TimeitResult : '+unic+u'>')
99 p.text(u'<TimeitResult : '+unic+u'>')
102
100
103
101
104
102
105 class TimeitTemplateFiller(ast.NodeTransformer):
103 class TimeitTemplateFiller(ast.NodeTransformer):
106 """Fill in the AST template for timing execution.
104 """Fill in the AST template for timing execution.
107
105
108 This is quite closely tied to the template definition, which is in
106 This is quite closely tied to the template definition, which is in
109 :meth:`ExecutionMagics.timeit`.
107 :meth:`ExecutionMagics.timeit`.
110 """
108 """
111 def __init__(self, ast_setup, ast_stmt):
109 def __init__(self, ast_setup, ast_stmt):
112 self.ast_setup = ast_setup
110 self.ast_setup = ast_setup
113 self.ast_stmt = ast_stmt
111 self.ast_stmt = ast_stmt
114
112
115 def visit_FunctionDef(self, node):
113 def visit_FunctionDef(self, node):
116 "Fill in the setup statement"
114 "Fill in the setup statement"
117 self.generic_visit(node)
115 self.generic_visit(node)
118 if node.name == "inner":
116 if node.name == "inner":
119 node.body[:1] = self.ast_setup.body
117 node.body[:1] = self.ast_setup.body
120
118
121 return node
119 return node
122
120
123 def visit_For(self, node):
121 def visit_For(self, node):
124 "Fill in the statement to be timed"
122 "Fill in the statement to be timed"
125 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
123 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
126 node.body = self.ast_stmt.body
124 node.body = self.ast_stmt.body
127 return node
125 return node
128
126
129
127
130 class Timer(timeit.Timer):
128 class Timer(timeit.Timer):
131 """Timer class that explicitly uses self.inner
129 """Timer class that explicitly uses self.inner
132
130
133 which is an undocumented implementation detail of CPython,
131 which is an undocumented implementation detail of CPython,
134 not shared by PyPy.
132 not shared by PyPy.
135 """
133 """
136 # Timer.timeit copied from CPython 3.4.2
134 # Timer.timeit copied from CPython 3.4.2
137 def timeit(self, number=timeit.default_number):
135 def timeit(self, number=timeit.default_number):
138 """Time 'number' executions of the main statement.
136 """Time 'number' executions of the main statement.
139
137
140 To be precise, this executes the setup statement once, and
138 To be precise, this executes the setup statement once, and
141 then returns the time it takes to execute the main statement
139 then returns the time it takes to execute the main statement
142 a number of times, as a float measured in seconds. The
140 a number of times, as a float measured in seconds. The
143 argument is the number of times through the loop, defaulting
141 argument is the number of times through the loop, defaulting
144 to one million. The main statement, the setup statement and
142 to one million. The main statement, the setup statement and
145 the timer function to be used are passed to the constructor.
143 the timer function to be used are passed to the constructor.
146 """
144 """
147 it = itertools.repeat(None, number)
145 it = itertools.repeat(None, number)
148 gcold = gc.isenabled()
146 gcold = gc.isenabled()
149 gc.disable()
147 gc.disable()
150 try:
148 try:
151 timing = self.inner(it, self.timer)
149 timing = self.inner(it, self.timer)
152 finally:
150 finally:
153 if gcold:
151 if gcold:
154 gc.enable()
152 gc.enable()
155 return timing
153 return timing
156
154
157
155
158 @magics_class
156 @magics_class
159 class ExecutionMagics(Magics):
157 class ExecutionMagics(Magics):
160 """Magics related to code execution, debugging, profiling, etc.
158 """Magics related to code execution, debugging, profiling, etc.
161
159
162 """
160 """
163
161
164 def __init__(self, shell):
162 def __init__(self, shell):
165 super(ExecutionMagics, self).__init__(shell)
163 super(ExecutionMagics, self).__init__(shell)
166 if profile is None:
164 if profile is None:
167 self.prun = self.profile_missing_notice
165 self.prun = self.profile_missing_notice
168 # Default execution function used to actually run user code.
166 # Default execution function used to actually run user code.
169 self.default_runner = None
167 self.default_runner = None
170
168
171 def profile_missing_notice(self, *args, **kwargs):
169 def profile_missing_notice(self, *args, **kwargs):
172 error("""\
170 error("""\
173 The profile module could not be found. It has been removed from the standard
171 The profile module could not be found. It has been removed from the standard
174 python packages because of its non-free license. To use profiling, install the
172 python packages because of its non-free license. To use profiling, install the
175 python-profiler package from non-free.""")
173 python-profiler package from non-free.""")
176
174
177 @skip_doctest
175 @skip_doctest
178 @line_cell_magic
176 @line_cell_magic
179 def prun(self, parameter_s='', cell=None):
177 def prun(self, parameter_s='', cell=None):
180
178
181 """Run a statement through the python code profiler.
179 """Run a statement through the python code profiler.
182
180
183 Usage, in line mode:
181 Usage, in line mode:
184 %prun [options] statement
182 %prun [options] statement
185
183
186 Usage, in cell mode:
184 Usage, in cell mode:
187 %%prun [options] [statement]
185 %%prun [options] [statement]
188 code...
186 code...
189 code...
187 code...
190
188
191 In cell mode, the additional code lines are appended to the (possibly
189 In cell mode, the additional code lines are appended to the (possibly
192 empty) statement in the first line. Cell mode allows you to easily
190 empty) statement in the first line. Cell mode allows you to easily
193 profile multiline blocks without having to put them in a separate
191 profile multiline blocks without having to put them in a separate
194 function.
192 function.
195
193
196 The given statement (which doesn't require quote marks) is run via the
194 The given statement (which doesn't require quote marks) is run via the
197 python profiler in a manner similar to the profile.run() function.
195 python profiler in a manner similar to the profile.run() function.
198 Namespaces are internally managed to work correctly; profile.run
196 Namespaces are internally managed to work correctly; profile.run
199 cannot be used in IPython because it makes certain assumptions about
197 cannot be used in IPython because it makes certain assumptions about
200 namespaces which do not hold under IPython.
198 namespaces which do not hold under IPython.
201
199
202 Options:
200 Options:
203
201
204 -l <limit>
202 -l <limit>
205 you can place restrictions on what or how much of the
203 you can place restrictions on what or how much of the
206 profile gets printed. The limit value can be:
204 profile gets printed. The limit value can be:
207
205
208 * A string: only information for function names containing this string
206 * A string: only information for function names containing this string
209 is printed.
207 is printed.
210
208
211 * An integer: only these many lines are printed.
209 * An integer: only these many lines are printed.
212
210
213 * A float (between 0 and 1): this fraction of the report is printed
211 * A float (between 0 and 1): this fraction of the report is printed
214 (for example, use a limit of 0.4 to see the topmost 40% only).
212 (for example, use a limit of 0.4 to see the topmost 40% only).
215
213
216 You can combine several limits with repeated use of the option. For
214 You can combine several limits with repeated use of the option. For
217 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
218 information about class constructors.
216 information about class constructors.
219
217
220 -r
218 -r
221 return the pstats.Stats object generated by the profiling. This
219 return the pstats.Stats object generated by the profiling. This
222 object has all the information about the profile in it, and you can
220 object has all the information about the profile in it, and you can
223 later use it for further analysis or in other functions.
221 later use it for further analysis or in other functions.
224
222
225 -s <key>
223 -s <key>
226 sort profile by given key. You can provide more than one key
224 sort profile by given key. You can provide more than one key
227 by using the option several times: '-s key1 -s key2 -s key3...'. The
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
228 default sorting key is 'time'.
226 default sorting key is 'time'.
229
227
230 The following is copied verbatim from the profile documentation
228 The following is copied verbatim from the profile documentation
231 referenced below:
229 referenced below:
232
230
233 When more than one key is provided, additional keys are used as
231 When more than one key is provided, additional keys are used as
234 secondary criteria when the there is equality in all keys selected
232 secondary criteria when the there is equality in all keys selected
235 before them.
233 before them.
236
234
237 Abbreviations can be used for any key names, as long as the
235 Abbreviations can be used for any key names, as long as the
238 abbreviation is unambiguous. The following are the keys currently
236 abbreviation is unambiguous. The following are the keys currently
239 defined:
237 defined:
240
238
241 ============ =====================
239 ============ =====================
242 Valid Arg Meaning
240 Valid Arg Meaning
243 ============ =====================
241 ============ =====================
244 "calls" call count
242 "calls" call count
245 "cumulative" cumulative time
243 "cumulative" cumulative time
246 "file" file name
244 "file" file name
247 "module" file name
245 "module" file name
248 "pcalls" primitive call count
246 "pcalls" primitive call count
249 "line" line number
247 "line" line number
250 "name" function name
248 "name" function name
251 "nfl" name/file/line
249 "nfl" name/file/line
252 "stdname" standard name
250 "stdname" standard name
253 "time" internal time
251 "time" internal time
254 ============ =====================
252 ============ =====================
255
253
256 Note that all sorts on statistics are in descending order (placing
254 Note that all sorts on statistics are in descending order (placing
257 most time consuming items first), where as name, file, and line number
255 most time consuming items first), where as name, file, and line number
258 searches are in ascending order (i.e., alphabetical). The subtle
256 searches are in ascending order (i.e., alphabetical). The subtle
259 distinction between "nfl" and "stdname" is that the standard name is a
257 distinction between "nfl" and "stdname" is that the standard name is a
260 sort of the name as printed, which means that the embedded line
258 sort of the name as printed, which means that the embedded line
261 numbers get compared in an odd way. For example, lines 3, 20, and 40
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
262 would (if the file names were the same) appear in the string order
260 would (if the file names were the same) appear in the string order
263 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
264 line numbers. In fact, sort_stats("nfl") is the same as
262 line numbers. In fact, sort_stats("nfl") is the same as
265 sort_stats("name", "file", "line").
263 sort_stats("name", "file", "line").
266
264
267 -T <filename>
265 -T <filename>
268 save profile results as shown on screen to a text
266 save profile results as shown on screen to a text
269 file. The profile is still shown on screen.
267 file. The profile is still shown on screen.
270
268
271 -D <filename>
269 -D <filename>
272 save (via dump_stats) profile statistics to given
270 save (via dump_stats) profile statistics to given
273 filename. This data is in a format understood by the pstats module, and
271 filename. This data is in a format understood by the pstats module, and
274 is generated by a call to the dump_stats() method of profile
272 is generated by a call to the dump_stats() method of profile
275 objects. The profile is still shown on screen.
273 objects. The profile is still shown on screen.
276
274
277 -q
275 -q
278 suppress output to the pager. Best used with -T and/or -D above.
276 suppress output to the pager. Best used with -T and/or -D above.
279
277
280 If you want to run complete programs under the profiler's control, use
278 If you want to run complete programs under the profiler's control, use
281 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
282 contains profiler specific options as described here.
280 contains profiler specific options as described here.
283
281
284 You can read the complete documentation for the profile module with::
282 You can read the complete documentation for the profile module with::
285
283
286 In [1]: import profile; profile.help()
284 In [1]: import profile; profile.help()
287 """
285 """
288 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
286 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
289 list_all=True, posix=False)
287 list_all=True, posix=False)
290 if cell is not None:
288 if cell is not None:
291 arg_str += '\n' + cell
289 arg_str += '\n' + cell
292 arg_str = self.shell.input_splitter.transform_cell(arg_str)
290 arg_str = self.shell.input_splitter.transform_cell(arg_str)
293 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
291 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
294
292
295 def _run_with_profiler(self, code, opts, namespace):
293 def _run_with_profiler(self, code, opts, namespace):
296 """
294 """
297 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
295 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
298
296
299 Parameters
297 Parameters
300 ----------
298 ----------
301 code : str
299 code : str
302 Code to be executed.
300 Code to be executed.
303 opts : Struct
301 opts : Struct
304 Options parsed by `self.parse_options`.
302 Options parsed by `self.parse_options`.
305 namespace : dict
303 namespace : dict
306 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
304 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
307
305
308 """
306 """
309
307
310 # Fill default values for unspecified options:
308 # Fill default values for unspecified options:
311 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
309 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
312
310
313 prof = profile.Profile()
311 prof = profile.Profile()
314 try:
312 try:
315 prof = prof.runctx(code, namespace, namespace)
313 prof = prof.runctx(code, namespace, namespace)
316 sys_exit = ''
314 sys_exit = ''
317 except SystemExit:
315 except SystemExit:
318 sys_exit = """*** SystemExit exception caught in code being profiled."""
316 sys_exit = """*** SystemExit exception caught in code being profiled."""
319
317
320 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
318 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
321
319
322 lims = opts.l
320 lims = opts.l
323 if lims:
321 if lims:
324 lims = [] # rebuild lims with ints/floats/strings
322 lims = [] # rebuild lims with ints/floats/strings
325 for lim in opts.l:
323 for lim in opts.l:
326 try:
324 try:
327 lims.append(int(lim))
325 lims.append(int(lim))
328 except ValueError:
326 except ValueError:
329 try:
327 try:
330 lims.append(float(lim))
328 lims.append(float(lim))
331 except ValueError:
329 except ValueError:
332 lims.append(lim)
330 lims.append(lim)
333
331
334 # Trap output.
332 # Trap output.
335 stdout_trap = StringIO()
333 stdout_trap = StringIO()
336 stats_stream = stats.stream
334 stats_stream = stats.stream
337 try:
335 try:
338 stats.stream = stdout_trap
336 stats.stream = stdout_trap
339 stats.print_stats(*lims)
337 stats.print_stats(*lims)
340 finally:
338 finally:
341 stats.stream = stats_stream
339 stats.stream = stats_stream
342
340
343 output = stdout_trap.getvalue()
341 output = stdout_trap.getvalue()
344 output = output.rstrip()
342 output = output.rstrip()
345
343
346 if 'q' not in opts:
344 if 'q' not in opts:
347 page.page(output)
345 page.page(output)
348 print(sys_exit, end=' ')
346 print(sys_exit, end=' ')
349
347
350 dump_file = opts.D[0]
348 dump_file = opts.D[0]
351 text_file = opts.T[0]
349 text_file = opts.T[0]
352 if dump_file:
350 if dump_file:
353 prof.dump_stats(dump_file)
351 prof.dump_stats(dump_file)
354 print('\n*** Profile stats marshalled to file',\
352 print('\n*** Profile stats marshalled to file',\
355 repr(dump_file)+'.',sys_exit)
353 repr(dump_file)+'.',sys_exit)
356 if text_file:
354 if text_file:
357 pfile = open(text_file,'w')
355 pfile = open(text_file,'w')
358 pfile.write(output)
356 pfile.write(output)
359 pfile.close()
357 pfile.close()
360 print('\n*** Profile printout saved to text file',\
358 print('\n*** Profile printout saved to text file',\
361 repr(text_file)+'.',sys_exit)
359 repr(text_file)+'.',sys_exit)
362
360
363 if 'r' in opts:
361 if 'r' in opts:
364 return stats
362 return stats
365 else:
363 else:
366 return None
364 return None
367
365
368 @line_magic
366 @line_magic
369 def pdb(self, parameter_s=''):
367 def pdb(self, parameter_s=''):
370 """Control the automatic calling of the pdb interactive debugger.
368 """Control the automatic calling of the pdb interactive debugger.
371
369
372 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
370 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
373 argument it works as a toggle.
371 argument it works as a toggle.
374
372
375 When an exception is triggered, IPython can optionally call the
373 When an exception is triggered, IPython can optionally call the
376 interactive pdb debugger after the traceback printout. %pdb toggles
374 interactive pdb debugger after the traceback printout. %pdb toggles
377 this feature on and off.
375 this feature on and off.
378
376
379 The initial state of this feature is set in your configuration
377 The initial state of this feature is set in your configuration
380 file (the option is ``InteractiveShell.pdb``).
378 file (the option is ``InteractiveShell.pdb``).
381
379
382 If you want to just activate the debugger AFTER an exception has fired,
380 If you want to just activate the debugger AFTER an exception has fired,
383 without having to type '%pdb on' and rerunning your code, you can use
381 without having to type '%pdb on' and rerunning your code, you can use
384 the %debug magic."""
382 the %debug magic."""
385
383
386 par = parameter_s.strip().lower()
384 par = parameter_s.strip().lower()
387
385
388 if par:
386 if par:
389 try:
387 try:
390 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
388 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
391 except KeyError:
389 except KeyError:
392 print ('Incorrect argument. Use on/1, off/0, '
390 print ('Incorrect argument. Use on/1, off/0, '
393 'or nothing for a toggle.')
391 'or nothing for a toggle.')
394 return
392 return
395 else:
393 else:
396 # toggle
394 # toggle
397 new_pdb = not self.shell.call_pdb
395 new_pdb = not self.shell.call_pdb
398
396
399 # set on the shell
397 # set on the shell
400 self.shell.call_pdb = new_pdb
398 self.shell.call_pdb = new_pdb
401 print('Automatic pdb calling has been turned',on_off(new_pdb))
399 print('Automatic pdb calling has been turned',on_off(new_pdb))
402
400
403 @skip_doctest
401 @skip_doctest
404 @magic_arguments.magic_arguments()
402 @magic_arguments.magic_arguments()
405 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
403 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
406 help="""
404 help="""
407 Set break point at LINE in FILE.
405 Set break point at LINE in FILE.
408 """
406 """
409 )
407 )
410 @magic_arguments.argument('statement', nargs='*',
408 @magic_arguments.argument('statement', nargs='*',
411 help="""
409 help="""
412 Code to run in debugger.
410 Code to run in debugger.
413 You can omit this in cell magic mode.
411 You can omit this in cell magic mode.
414 """
412 """
415 )
413 )
416 @line_cell_magic
414 @line_cell_magic
417 def debug(self, line='', cell=None):
415 def debug(self, line='', cell=None):
418 """Activate the interactive debugger.
416 """Activate the interactive debugger.
419
417
420 This magic command support two ways of activating debugger.
418 This magic command support two ways of activating debugger.
421 One is to activate debugger before executing code. This way, you
419 One is to activate debugger before executing code. This way, you
422 can set a break point, to step through the code from the point.
420 can set a break point, to step through the code from the point.
423 You can use this mode by giving statements to execute and optionally
421 You can use this mode by giving statements to execute and optionally
424 a breakpoint.
422 a breakpoint.
425
423
426 The other one is to activate debugger in post-mortem mode. You can
424 The other one is to activate debugger in post-mortem mode. You can
427 activate this mode simply running %debug without any argument.
425 activate this mode simply running %debug without any argument.
428 If an exception has just occurred, this lets you inspect its stack
426 If an exception has just occurred, this lets you inspect its stack
429 frames interactively. Note that this will always work only on the last
427 frames interactively. Note that this will always work only on the last
430 traceback that occurred, so you must call this quickly after an
428 traceback that occurred, so you must call this quickly after an
431 exception that you wish to inspect has fired, because if another one
429 exception that you wish to inspect has fired, because if another one
432 occurs, it clobbers the previous one.
430 occurs, it clobbers the previous one.
433
431
434 If you want IPython to automatically do this on every exception, see
432 If you want IPython to automatically do this on every exception, see
435 the %pdb magic for more details.
433 the %pdb magic for more details.
436 """
434 """
437 args = magic_arguments.parse_argstring(self.debug, line)
435 args = magic_arguments.parse_argstring(self.debug, line)
438
436
439 if not (args.breakpoint or args.statement or cell):
437 if not (args.breakpoint or args.statement or cell):
440 self._debug_post_mortem()
438 self._debug_post_mortem()
441 else:
439 else:
442 code = "\n".join(args.statement)
440 code = "\n".join(args.statement)
443 if cell:
441 if cell:
444 code += "\n" + cell
442 code += "\n" + cell
445 self._debug_exec(code, args.breakpoint)
443 self._debug_exec(code, args.breakpoint)
446
444
447 def _debug_post_mortem(self):
445 def _debug_post_mortem(self):
448 self.shell.debugger(force=True)
446 self.shell.debugger(force=True)
449
447
450 def _debug_exec(self, code, breakpoint):
448 def _debug_exec(self, code, breakpoint):
451 if breakpoint:
449 if breakpoint:
452 (filename, bp_line) = breakpoint.rsplit(':', 1)
450 (filename, bp_line) = breakpoint.rsplit(':', 1)
453 bp_line = int(bp_line)
451 bp_line = int(bp_line)
454 else:
452 else:
455 (filename, bp_line) = (None, None)
453 (filename, bp_line) = (None, None)
456 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
454 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
457
455
458 @line_magic
456 @line_magic
459 def tb(self, s):
457 def tb(self, s):
460 """Print the last traceback with the currently active exception mode.
458 """Print the last traceback with the currently active exception mode.
461
459
462 See %xmode for changing exception reporting modes."""
460 See %xmode for changing exception reporting modes."""
463 self.shell.showtraceback()
461 self.shell.showtraceback()
464
462
465 @skip_doctest
463 @skip_doctest
466 @line_magic
464 @line_magic
467 def run(self, parameter_s='', runner=None,
465 def run(self, parameter_s='', runner=None,
468 file_finder=get_py_filename):
466 file_finder=get_py_filename):
469 """Run the named file inside IPython as a program.
467 """Run the named file inside IPython as a program.
470
468
471 Usage::
469 Usage::
472
470
473 %run [-n -i -e -G]
471 %run [-n -i -e -G]
474 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
472 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
475 ( -m mod | file ) [args]
473 ( -m mod | file ) [args]
476
474
477 Parameters after the filename are passed as command-line arguments to
475 Parameters after the filename are passed as command-line arguments to
478 the program (put in sys.argv). Then, control returns to IPython's
476 the program (put in sys.argv). Then, control returns to IPython's
479 prompt.
477 prompt.
480
478
481 This is similar to running at a system prompt ``python file args``,
479 This is similar to running at a system prompt ``python file args``,
482 but with the advantage of giving you IPython's tracebacks, and of
480 but with the advantage of giving you IPython's tracebacks, and of
483 loading all variables into your interactive namespace for further use
481 loading all variables into your interactive namespace for further use
484 (unless -p is used, see below).
482 (unless -p is used, see below).
485
483
486 The file is executed in a namespace initially consisting only of
484 The file is executed in a namespace initially consisting only of
487 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
485 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
488 sees its environment as if it were being run as a stand-alone program
486 sees its environment as if it were being run as a stand-alone program
489 (except for sharing global objects such as previously imported
487 (except for sharing global objects such as previously imported
490 modules). But after execution, the IPython interactive namespace gets
488 modules). But after execution, the IPython interactive namespace gets
491 updated with all variables defined in the program (except for __name__
489 updated with all variables defined in the program (except for __name__
492 and sys.argv). This allows for very convenient loading of code for
490 and sys.argv). This allows for very convenient loading of code for
493 interactive work, while giving each program a 'clean sheet' to run in.
491 interactive work, while giving each program a 'clean sheet' to run in.
494
492
495 Arguments are expanded using shell-like glob match. Patterns
493 Arguments are expanded using shell-like glob match. Patterns
496 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
494 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
497 tilde '~' will be expanded into user's home directory. Unlike
495 tilde '~' will be expanded into user's home directory. Unlike
498 real shells, quotation does not suppress expansions. Use
496 real shells, quotation does not suppress expansions. Use
499 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
497 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
500 To completely disable these expansions, you can use -G flag.
498 To completely disable these expansions, you can use -G flag.
501
499
502 Options:
500 Options:
503
501
504 -n
502 -n
505 __name__ is NOT set to '__main__', but to the running file's name
503 __name__ is NOT set to '__main__', but to the running file's name
506 without extension (as python does under import). This allows running
504 without extension (as python does under import). This allows running
507 scripts and reloading the definitions in them without calling code
505 scripts and reloading the definitions in them without calling code
508 protected by an ``if __name__ == "__main__"`` clause.
506 protected by an ``if __name__ == "__main__"`` clause.
509
507
510 -i
508 -i
511 run the file in IPython's namespace instead of an empty one. This
509 run the file in IPython's namespace instead of an empty one. This
512 is useful if you are experimenting with code written in a text editor
510 is useful if you are experimenting with code written in a text editor
513 which depends on variables defined interactively.
511 which depends on variables defined interactively.
514
512
515 -e
513 -e
516 ignore sys.exit() calls or SystemExit exceptions in the script
514 ignore sys.exit() calls or SystemExit exceptions in the script
517 being run. This is particularly useful if IPython is being used to
515 being run. This is particularly useful if IPython is being used to
518 run unittests, which always exit with a sys.exit() call. In such
516 run unittests, which always exit with a sys.exit() call. In such
519 cases you are interested in the output of the test results, not in
517 cases you are interested in the output of the test results, not in
520 seeing a traceback of the unittest module.
518 seeing a traceback of the unittest module.
521
519
522 -t
520 -t
523 print timing information at the end of the run. IPython will give
521 print timing information at the end of the run. IPython will give
524 you an estimated CPU time consumption for your script, which under
522 you an estimated CPU time consumption for your script, which under
525 Unix uses the resource module to avoid the wraparound problems of
523 Unix uses the resource module to avoid the wraparound problems of
526 time.clock(). Under Unix, an estimate of time spent on system tasks
524 time.clock(). Under Unix, an estimate of time spent on system tasks
527 is also given (for Windows platforms this is reported as 0.0).
525 is also given (for Windows platforms this is reported as 0.0).
528
526
529 If -t is given, an additional ``-N<N>`` option can be given, where <N>
527 If -t is given, an additional ``-N<N>`` option can be given, where <N>
530 must be an integer indicating how many times you want the script to
528 must be an integer indicating how many times you want the script to
531 run. The final timing report will include total and per run results.
529 run. The final timing report will include total and per run results.
532
530
533 For example (testing the script uniq_stable.py)::
531 For example (testing the script uniq_stable.py)::
534
532
535 In [1]: run -t uniq_stable
533 In [1]: run -t uniq_stable
536
534
537 IPython CPU timings (estimated):
535 IPython CPU timings (estimated):
538 User : 0.19597 s.
536 User : 0.19597 s.
539 System: 0.0 s.
537 System: 0.0 s.
540
538
541 In [2]: run -t -N5 uniq_stable
539 In [2]: run -t -N5 uniq_stable
542
540
543 IPython CPU timings (estimated):
541 IPython CPU timings (estimated):
544 Total runs performed: 5
542 Total runs performed: 5
545 Times : Total Per run
543 Times : Total Per run
546 User : 0.910862 s, 0.1821724 s.
544 User : 0.910862 s, 0.1821724 s.
547 System: 0.0 s, 0.0 s.
545 System: 0.0 s, 0.0 s.
548
546
549 -d
547 -d
550 run your program under the control of pdb, the Python debugger.
548 run your program under the control of pdb, the Python debugger.
551 This allows you to execute your program step by step, watch variables,
549 This allows you to execute your program step by step, watch variables,
552 etc. Internally, what IPython does is similar to calling::
550 etc. Internally, what IPython does is similar to calling::
553
551
554 pdb.run('execfile("YOURFILENAME")')
552 pdb.run('execfile("YOURFILENAME")')
555
553
556 with a breakpoint set on line 1 of your file. You can change the line
554 with a breakpoint set on line 1 of your file. You can change the line
557 number for this automatic breakpoint to be <N> by using the -bN option
555 number for this automatic breakpoint to be <N> by using the -bN option
558 (where N must be an integer). For example::
556 (where N must be an integer). For example::
559
557
560 %run -d -b40 myscript
558 %run -d -b40 myscript
561
559
562 will set the first breakpoint at line 40 in myscript.py. Note that
560 will set the first breakpoint at line 40 in myscript.py. Note that
563 the first breakpoint must be set on a line which actually does
561 the first breakpoint must be set on a line which actually does
564 something (not a comment or docstring) for it to stop execution.
562 something (not a comment or docstring) for it to stop execution.
565
563
566 Or you can specify a breakpoint in a different file::
564 Or you can specify a breakpoint in a different file::
567
565
568 %run -d -b myotherfile.py:20 myscript
566 %run -d -b myotherfile.py:20 myscript
569
567
570 When the pdb debugger starts, you will see a (Pdb) prompt. You must
568 When the pdb debugger starts, you will see a (Pdb) prompt. You must
571 first enter 'c' (without quotes) to start execution up to the first
569 first enter 'c' (without quotes) to start execution up to the first
572 breakpoint.
570 breakpoint.
573
571
574 Entering 'help' gives information about the use of the debugger. You
572 Entering 'help' gives information about the use of the debugger. You
575 can easily see pdb's full documentation with "import pdb;pdb.help()"
573 can easily see pdb's full documentation with "import pdb;pdb.help()"
576 at a prompt.
574 at a prompt.
577
575
578 -p
576 -p
579 run program under the control of the Python profiler module (which
577 run program under the control of the Python profiler module (which
580 prints a detailed report of execution times, function calls, etc).
578 prints a detailed report of execution times, function calls, etc).
581
579
582 You can pass other options after -p which affect the behavior of the
580 You can pass other options after -p which affect the behavior of the
583 profiler itself. See the docs for %prun for details.
581 profiler itself. See the docs for %prun for details.
584
582
585 In this mode, the program's variables do NOT propagate back to the
583 In this mode, the program's variables do NOT propagate back to the
586 IPython interactive namespace (because they remain in the namespace
584 IPython interactive namespace (because they remain in the namespace
587 where the profiler executes them).
585 where the profiler executes them).
588
586
589 Internally this triggers a call to %prun, see its documentation for
587 Internally this triggers a call to %prun, see its documentation for
590 details on the options available specifically for profiling.
588 details on the options available specifically for profiling.
591
589
592 There is one special usage for which the text above doesn't apply:
590 There is one special usage for which the text above doesn't apply:
593 if the filename ends with .ipy[nb], the file is run as ipython script,
591 if the filename ends with .ipy[nb], the file is run as ipython script,
594 just as if the commands were written on IPython prompt.
592 just as if the commands were written on IPython prompt.
595
593
596 -m
594 -m
597 specify module name to load instead of script path. Similar to
595 specify module name to load instead of script path. Similar to
598 the -m option for the python interpreter. Use this option last if you
596 the -m option for the python interpreter. Use this option last if you
599 want to combine with other %run options. Unlike the python interpreter
597 want to combine with other %run options. Unlike the python interpreter
600 only source modules are allowed no .pyc or .pyo files.
598 only source modules are allowed no .pyc or .pyo files.
601 For example::
599 For example::
602
600
603 %run -m example
601 %run -m example
604
602
605 will run the example module.
603 will run the example module.
606
604
607 -G
605 -G
608 disable shell-like glob expansion of arguments.
606 disable shell-like glob expansion of arguments.
609
607
610 """
608 """
611
609
612 # get arguments and set sys.argv for program to be run.
610 # get arguments and set sys.argv for program to be run.
613 opts, arg_lst = self.parse_options(parameter_s,
611 opts, arg_lst = self.parse_options(parameter_s,
614 'nidtN:b:pD:l:rs:T:em:G',
612 'nidtN:b:pD:l:rs:T:em:G',
615 mode='list', list_all=1)
613 mode='list', list_all=1)
616 if "m" in opts:
614 if "m" in opts:
617 modulename = opts["m"][0]
615 modulename = opts["m"][0]
618 modpath = find_mod(modulename)
616 modpath = find_mod(modulename)
619 if modpath is None:
617 if modpath is None:
620 warn('%r is not a valid modulename on sys.path'%modulename)
618 warn('%r is not a valid modulename on sys.path'%modulename)
621 return
619 return
622 arg_lst = [modpath] + arg_lst
620 arg_lst = [modpath] + arg_lst
623 try:
621 try:
624 filename = file_finder(arg_lst[0])
622 filename = file_finder(arg_lst[0])
625 except IndexError:
623 except IndexError:
626 warn('you must provide at least a filename.')
624 warn('you must provide at least a filename.')
627 print('\n%run:\n', oinspect.getdoc(self.run))
625 print('\n%run:\n', oinspect.getdoc(self.run))
628 return
626 return
629 except IOError as e:
627 except IOError as e:
630 try:
628 try:
631 msg = str(e)
629 msg = str(e)
632 except UnicodeError:
630 except UnicodeError:
633 msg = e.message
631 msg = e.message
634 error(msg)
632 error(msg)
635 return
633 return
636
634
637 if filename.lower().endswith(('.ipy', '.ipynb')):
635 if filename.lower().endswith(('.ipy', '.ipynb')):
638 with preserve_keys(self.shell.user_ns, '__file__'):
636 with preserve_keys(self.shell.user_ns, '__file__'):
639 self.shell.user_ns['__file__'] = filename
637 self.shell.user_ns['__file__'] = filename
640 self.shell.safe_execfile_ipy(filename)
638 self.shell.safe_execfile_ipy(filename)
641 return
639 return
642
640
643 # Control the response to exit() calls made by the script being run
641 # Control the response to exit() calls made by the script being run
644 exit_ignore = 'e' in opts
642 exit_ignore = 'e' in opts
645
643
646 # Make sure that the running script gets a proper sys.argv as if it
644 # Make sure that the running script gets a proper sys.argv as if it
647 # were run from a system shell.
645 # were run from a system shell.
648 save_argv = sys.argv # save it for later restoring
646 save_argv = sys.argv # save it for later restoring
649
647
650 if 'G' in opts:
648 if 'G' in opts:
651 args = arg_lst[1:]
649 args = arg_lst[1:]
652 else:
650 else:
653 # tilde and glob expansion
651 # tilde and glob expansion
654 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
652 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
655
653
656 sys.argv = [filename] + args # put in the proper filename
654 sys.argv = [filename] + args # put in the proper filename
657 # protect sys.argv from potential unicode strings on Python 2:
655 # protect sys.argv from potential unicode strings on Python 2:
658 if not py3compat.PY3:
656 if not py3compat.PY3:
659 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
657 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
660
658
661 if 'i' in opts:
659 if 'i' in opts:
662 # Run in user's interactive namespace
660 # Run in user's interactive namespace
663 prog_ns = self.shell.user_ns
661 prog_ns = self.shell.user_ns
664 __name__save = self.shell.user_ns['__name__']
662 __name__save = self.shell.user_ns['__name__']
665 prog_ns['__name__'] = '__main__'
663 prog_ns['__name__'] = '__main__'
666 main_mod = self.shell.user_module
664 main_mod = self.shell.user_module
667
665
668 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
666 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
669 # set the __file__ global in the script's namespace
667 # set the __file__ global in the script's namespace
670 # TK: Is this necessary in interactive mode?
668 # TK: Is this necessary in interactive mode?
671 prog_ns['__file__'] = filename
669 prog_ns['__file__'] = filename
672 else:
670 else:
673 # Run in a fresh, empty namespace
671 # Run in a fresh, empty namespace
674 if 'n' in opts:
672 if 'n' in opts:
675 name = os.path.splitext(os.path.basename(filename))[0]
673 name = os.path.splitext(os.path.basename(filename))[0]
676 else:
674 else:
677 name = '__main__'
675 name = '__main__'
678
676
679 # The shell MUST hold a reference to prog_ns so after %run
677 # The shell MUST hold a reference to prog_ns so after %run
680 # exits, the python deletion mechanism doesn't zero it out
678 # exits, the python deletion mechanism doesn't zero it out
681 # (leaving dangling references). See interactiveshell for details
679 # (leaving dangling references). See interactiveshell for details
682 main_mod = self.shell.new_main_mod(filename, name)
680 main_mod = self.shell.new_main_mod(filename, name)
683 prog_ns = main_mod.__dict__
681 prog_ns = main_mod.__dict__
684
682
685 # pickle fix. See interactiveshell for an explanation. But we need to
683 # pickle fix. See interactiveshell for an explanation. But we need to
686 # make sure that, if we overwrite __main__, we replace it at the end
684 # make sure that, if we overwrite __main__, we replace it at the end
687 main_mod_name = prog_ns['__name__']
685 main_mod_name = prog_ns['__name__']
688
686
689 if main_mod_name == '__main__':
687 if main_mod_name == '__main__':
690 restore_main = sys.modules['__main__']
688 restore_main = sys.modules['__main__']
691 else:
689 else:
692 restore_main = False
690 restore_main = False
693
691
694 # This needs to be undone at the end to prevent holding references to
692 # This needs to be undone at the end to prevent holding references to
695 # every single object ever created.
693 # every single object ever created.
696 sys.modules[main_mod_name] = main_mod
694 sys.modules[main_mod_name] = main_mod
697
695
698 if 'p' in opts or 'd' in opts:
696 if 'p' in opts or 'd' in opts:
699 if 'm' in opts:
697 if 'm' in opts:
700 code = 'run_module(modulename, prog_ns)'
698 code = 'run_module(modulename, prog_ns)'
701 code_ns = {
699 code_ns = {
702 'run_module': self.shell.safe_run_module,
700 'run_module': self.shell.safe_run_module,
703 'prog_ns': prog_ns,
701 'prog_ns': prog_ns,
704 'modulename': modulename,
702 'modulename': modulename,
705 }
703 }
706 else:
704 else:
707 if 'd' in opts:
705 if 'd' in opts:
708 # allow exceptions to raise in debug mode
706 # allow exceptions to raise in debug mode
709 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
707 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
710 else:
708 else:
711 code = 'execfile(filename, prog_ns)'
709 code = 'execfile(filename, prog_ns)'
712 code_ns = {
710 code_ns = {
713 'execfile': self.shell.safe_execfile,
711 'execfile': self.shell.safe_execfile,
714 'prog_ns': prog_ns,
712 'prog_ns': prog_ns,
715 'filename': get_py_filename(filename),
713 'filename': get_py_filename(filename),
716 }
714 }
717
715
718 try:
716 try:
719 stats = None
717 stats = None
720 if 'p' in opts:
718 if 'p' in opts:
721 stats = self._run_with_profiler(code, opts, code_ns)
719 stats = self._run_with_profiler(code, opts, code_ns)
722 else:
720 else:
723 if 'd' in opts:
721 if 'd' in opts:
724 bp_file, bp_line = parse_breakpoint(
722 bp_file, bp_line = parse_breakpoint(
725 opts.get('b', ['1'])[0], filename)
723 opts.get('b', ['1'])[0], filename)
726 self._run_with_debugger(
724 self._run_with_debugger(
727 code, code_ns, filename, bp_line, bp_file)
725 code, code_ns, filename, bp_line, bp_file)
728 else:
726 else:
729 if 'm' in opts:
727 if 'm' in opts:
730 def run():
728 def run():
731 self.shell.safe_run_module(modulename, prog_ns)
729 self.shell.safe_run_module(modulename, prog_ns)
732 else:
730 else:
733 if runner is None:
731 if runner is None:
734 runner = self.default_runner
732 runner = self.default_runner
735 if runner is None:
733 if runner is None:
736 runner = self.shell.safe_execfile
734 runner = self.shell.safe_execfile
737
735
738 def run():
736 def run():
739 runner(filename, prog_ns, prog_ns,
737 runner(filename, prog_ns, prog_ns,
740 exit_ignore=exit_ignore)
738 exit_ignore=exit_ignore)
741
739
742 if 't' in opts:
740 if 't' in opts:
743 # timed execution
741 # timed execution
744 try:
742 try:
745 nruns = int(opts['N'][0])
743 nruns = int(opts['N'][0])
746 if nruns < 1:
744 if nruns < 1:
747 error('Number of runs must be >=1')
745 error('Number of runs must be >=1')
748 return
746 return
749 except (KeyError):
747 except (KeyError):
750 nruns = 1
748 nruns = 1
751 self._run_with_timing(run, nruns)
749 self._run_with_timing(run, nruns)
752 else:
750 else:
753 # regular execution
751 # regular execution
754 run()
752 run()
755
753
756 if 'i' in opts:
754 if 'i' in opts:
757 self.shell.user_ns['__name__'] = __name__save
755 self.shell.user_ns['__name__'] = __name__save
758 else:
756 else:
759 # update IPython interactive namespace
757 # update IPython interactive namespace
760
758
761 # Some forms of read errors on the file may mean the
759 # Some forms of read errors on the file may mean the
762 # __name__ key was never set; using pop we don't have to
760 # __name__ key was never set; using pop we don't have to
763 # worry about a possible KeyError.
761 # worry about a possible KeyError.
764 prog_ns.pop('__name__', None)
762 prog_ns.pop('__name__', None)
765
763
766 with preserve_keys(self.shell.user_ns, '__file__'):
764 with preserve_keys(self.shell.user_ns, '__file__'):
767 self.shell.user_ns.update(prog_ns)
765 self.shell.user_ns.update(prog_ns)
768 finally:
766 finally:
769 # It's a bit of a mystery why, but __builtins__ can change from
767 # It's a bit of a mystery why, but __builtins__ can change from
770 # being a module to becoming a dict missing some key data after
768 # being a module to becoming a dict missing some key data after
771 # %run. As best I can see, this is NOT something IPython is doing
769 # %run. As best I can see, this is NOT something IPython is doing
772 # at all, and similar problems have been reported before:
770 # at all, and similar problems have been reported before:
773 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
771 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
774 # Since this seems to be done by the interpreter itself, the best
772 # Since this seems to be done by the interpreter itself, the best
775 # we can do is to at least restore __builtins__ for the user on
773 # we can do is to at least restore __builtins__ for the user on
776 # exit.
774 # exit.
777 self.shell.user_ns['__builtins__'] = builtin_mod
775 self.shell.user_ns['__builtins__'] = builtin_mod
778
776
779 # Ensure key global structures are restored
777 # Ensure key global structures are restored
780 sys.argv = save_argv
778 sys.argv = save_argv
781 if restore_main:
779 if restore_main:
782 sys.modules['__main__'] = restore_main
780 sys.modules['__main__'] = restore_main
783 else:
781 else:
784 # Remove from sys.modules the reference to main_mod we'd
782 # Remove from sys.modules the reference to main_mod we'd
785 # added. Otherwise it will trap references to objects
783 # added. Otherwise it will trap references to objects
786 # contained therein.
784 # contained therein.
787 del sys.modules[main_mod_name]
785 del sys.modules[main_mod_name]
788
786
789 return stats
787 return stats
790
788
791 def _run_with_debugger(self, code, code_ns, filename=None,
789 def _run_with_debugger(self, code, code_ns, filename=None,
792 bp_line=None, bp_file=None):
790 bp_line=None, bp_file=None):
793 """
791 """
794 Run `code` in debugger with a break point.
792 Run `code` in debugger with a break point.
795
793
796 Parameters
794 Parameters
797 ----------
795 ----------
798 code : str
796 code : str
799 Code to execute.
797 Code to execute.
800 code_ns : dict
798 code_ns : dict
801 A namespace in which `code` is executed.
799 A namespace in which `code` is executed.
802 filename : str
800 filename : str
803 `code` is ran as if it is in `filename`.
801 `code` is ran as if it is in `filename`.
804 bp_line : int, optional
802 bp_line : int, optional
805 Line number of the break point.
803 Line number of the break point.
806 bp_file : str, optional
804 bp_file : str, optional
807 Path to the file in which break point is specified.
805 Path to the file in which break point is specified.
808 `filename` is used if not given.
806 `filename` is used if not given.
809
807
810 Raises
808 Raises
811 ------
809 ------
812 UsageError
810 UsageError
813 If the break point given by `bp_line` is not valid.
811 If the break point given by `bp_line` is not valid.
814
812
815 """
813 """
816 deb = self.shell.InteractiveTB.pdb
814 deb = self.shell.InteractiveTB.pdb
817 if not deb:
815 if not deb:
818 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
816 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
819 deb = self.shell.InteractiveTB.pdb
817 deb = self.shell.InteractiveTB.pdb
820
818
821 # reset Breakpoint state, which is moronically kept
819 # reset Breakpoint state, which is moronically kept
822 # in a class
820 # in a class
823 bdb.Breakpoint.next = 1
821 bdb.Breakpoint.next = 1
824 bdb.Breakpoint.bplist = {}
822 bdb.Breakpoint.bplist = {}
825 bdb.Breakpoint.bpbynumber = [None]
823 bdb.Breakpoint.bpbynumber = [None]
826 if bp_line is not None:
824 if bp_line is not None:
827 # Set an initial breakpoint to stop execution
825 # Set an initial breakpoint to stop execution
828 maxtries = 10
826 maxtries = 10
829 bp_file = bp_file or filename
827 bp_file = bp_file or filename
830 checkline = deb.checkline(bp_file, bp_line)
828 checkline = deb.checkline(bp_file, bp_line)
831 if not checkline:
829 if not checkline:
832 for bp in range(bp_line + 1, bp_line + maxtries + 1):
830 for bp in range(bp_line + 1, bp_line + maxtries + 1):
833 if deb.checkline(bp_file, bp):
831 if deb.checkline(bp_file, bp):
834 break
832 break
835 else:
833 else:
836 msg = ("\nI failed to find a valid line to set "
834 msg = ("\nI failed to find a valid line to set "
837 "a breakpoint\n"
835 "a breakpoint\n"
838 "after trying up to line: %s.\n"
836 "after trying up to line: %s.\n"
839 "Please set a valid breakpoint manually "
837 "Please set a valid breakpoint manually "
840 "with the -b option." % bp)
838 "with the -b option." % bp)
841 raise UsageError(msg)
839 raise UsageError(msg)
842 # if we find a good linenumber, set the breakpoint
840 # if we find a good linenumber, set the breakpoint
843 deb.do_break('%s:%s' % (bp_file, bp_line))
841 deb.do_break('%s:%s' % (bp_file, bp_line))
844
842
845 if filename:
843 if filename:
846 # Mimic Pdb._runscript(...)
844 # Mimic Pdb._runscript(...)
847 deb._wait_for_mainpyfile = True
845 deb._wait_for_mainpyfile = True
848 deb.mainpyfile = deb.canonic(filename)
846 deb.mainpyfile = deb.canonic(filename)
849
847
850 # Start file run
848 # Start file run
851 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
849 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
852 try:
850 try:
853 if filename:
851 if filename:
854 # save filename so it can be used by methods on the deb object
852 # save filename so it can be used by methods on the deb object
855 deb._exec_filename = filename
853 deb._exec_filename = filename
856 while True:
854 while True:
857 try:
855 try:
858 deb.run(code, code_ns)
856 deb.run(code, code_ns)
859 except Restart:
857 except Restart:
860 print("Restarting")
858 print("Restarting")
861 if filename:
859 if filename:
862 deb._wait_for_mainpyfile = True
860 deb._wait_for_mainpyfile = True
863 deb.mainpyfile = deb.canonic(filename)
861 deb.mainpyfile = deb.canonic(filename)
864 continue
862 continue
865 else:
863 else:
866 break
864 break
867
865
868
866
869 except:
867 except:
870 etype, value, tb = sys.exc_info()
868 etype, value, tb = sys.exc_info()
871 # Skip three frames in the traceback: the %run one,
869 # Skip three frames in the traceback: the %run one,
872 # one inside bdb.py, and the command-line typed by the
870 # one inside bdb.py, and the command-line typed by the
873 # user (run by exec in pdb itself).
871 # user (run by exec in pdb itself).
874 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
872 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
875
873
876 @staticmethod
874 @staticmethod
877 def _run_with_timing(run, nruns):
875 def _run_with_timing(run, nruns):
878 """
876 """
879 Run function `run` and print timing information.
877 Run function `run` and print timing information.
880
878
881 Parameters
879 Parameters
882 ----------
880 ----------
883 run : callable
881 run : callable
884 Any callable object which takes no argument.
882 Any callable object which takes no argument.
885 nruns : int
883 nruns : int
886 Number of times to execute `run`.
884 Number of times to execute `run`.
887
885
888 """
886 """
889 twall0 = time.time()
887 twall0 = time.time()
890 if nruns == 1:
888 if nruns == 1:
891 t0 = clock2()
889 t0 = clock2()
892 run()
890 run()
893 t1 = clock2()
891 t1 = clock2()
894 t_usr = t1[0] - t0[0]
892 t_usr = t1[0] - t0[0]
895 t_sys = t1[1] - t0[1]
893 t_sys = t1[1] - t0[1]
896 print("\nIPython CPU timings (estimated):")
894 print("\nIPython CPU timings (estimated):")
897 print(" User : %10.2f s." % t_usr)
895 print(" User : %10.2f s." % t_usr)
898 print(" System : %10.2f s." % t_sys)
896 print(" System : %10.2f s." % t_sys)
899 else:
897 else:
900 runs = range(nruns)
898 runs = range(nruns)
901 t0 = clock2()
899 t0 = clock2()
902 for nr in runs:
900 for nr in runs:
903 run()
901 run()
904 t1 = clock2()
902 t1 = clock2()
905 t_usr = t1[0] - t0[0]
903 t_usr = t1[0] - t0[0]
906 t_sys = t1[1] - t0[1]
904 t_sys = t1[1] - t0[1]
907 print("\nIPython CPU timings (estimated):")
905 print("\nIPython CPU timings (estimated):")
908 print("Total runs performed:", nruns)
906 print("Total runs performed:", nruns)
909 print(" Times : %10s %10s" % ('Total', 'Per run'))
907 print(" Times : %10s %10s" % ('Total', 'Per run'))
910 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
908 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
911 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
909 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
912 twall1 = time.time()
910 twall1 = time.time()
913 print("Wall time: %10.2f s." % (twall1 - twall0))
911 print("Wall time: %10.2f s." % (twall1 - twall0))
914
912
915 @skip_doctest
913 @skip_doctest
916 @line_cell_magic
914 @line_cell_magic
917 def timeit(self, line='', cell=None):
915 def timeit(self, line='', cell=None):
918 """Time execution of a Python statement or expression
916 """Time execution of a Python statement or expression
919
917
920 Usage, in line mode:
918 Usage, in line mode:
921 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
919 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
922 or in cell mode:
920 or in cell mode:
923 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
921 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
924 code
922 code
925 code...
923 code...
926
924
927 Time execution of a Python statement or expression using the timeit
925 Time execution of a Python statement or expression using the timeit
928 module. This function can be used both as a line and cell magic:
926 module. This function can be used both as a line and cell magic:
929
927
930 - In line mode you can time a single-line statement (though multiple
928 - In line mode you can time a single-line statement (though multiple
931 ones can be chained with using semicolons).
929 ones can be chained with using semicolons).
932
930
933 - In cell mode, the statement in the first line is used as setup code
931 - In cell mode, the statement in the first line is used as setup code
934 (executed but not timed) and the body of the cell is timed. The cell
932 (executed but not timed) and the body of the cell is timed. The cell
935 body has access to any variables created in the setup code.
933 body has access to any variables created in the setup code.
936
934
937 Options:
935 Options:
938 -n<N>: execute the given statement <N> times in a loop. If this value
936 -n<N>: execute the given statement <N> times in a loop. If this value
939 is not given, a fitting value is chosen.
937 is not given, a fitting value is chosen.
940
938
941 -r<R>: repeat the loop iteration <R> times and take the best result.
939 -r<R>: repeat the loop iteration <R> times and take the best result.
942 Default: 3
940 Default: 3
943
941
944 -t: use time.time to measure the time, which is the default on Unix.
942 -t: use time.time to measure the time, which is the default on Unix.
945 This function measures wall time.
943 This function measures wall time.
946
944
947 -c: use time.clock to measure the time, which is the default on
945 -c: use time.clock to measure the time, which is the default on
948 Windows and measures wall time. On Unix, resource.getrusage is used
946 Windows and measures wall time. On Unix, resource.getrusage is used
949 instead and returns the CPU user time.
947 instead and returns the CPU user time.
950
948
951 -p<P>: use a precision of <P> digits to display the timing result.
949 -p<P>: use a precision of <P> digits to display the timing result.
952 Default: 3
950 Default: 3
953
951
954 -q: Quiet, do not print result.
952 -q: Quiet, do not print result.
955
953
956 -o: return a TimeitResult that can be stored in a variable to inspect
954 -o: return a TimeitResult that can be stored in a variable to inspect
957 the result in more details.
955 the result in more details.
958
956
959
957
960 Examples
958 Examples
961 --------
959 --------
962 ::
960 ::
963
961
964 In [1]: %timeit pass
962 In [1]: %timeit pass
965 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
963 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
966
964
967 In [2]: u = None
965 In [2]: u = None
968
966
969 In [3]: %timeit u is None
967 In [3]: %timeit u is None
970 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
968 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
971
969
972 In [4]: %timeit -r 4 u == None
970 In [4]: %timeit -r 4 u == None
973 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
971 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
974
972
975 In [5]: import time
973 In [5]: import time
976
974
977 In [6]: %timeit -n1 time.sleep(2)
975 In [6]: %timeit -n1 time.sleep(2)
978 1 loop, average of 7: 2 s +- 4.71 µs per loop (using standard deviation)
976 1 loop, average of 7: 2 s +- 4.71 µs per loop (using standard deviation)
979
977
980
978
981 The times reported by %timeit will be slightly higher than those
979 The times reported by %timeit will be slightly higher than those
982 reported by the timeit.py script when variables are accessed. This is
980 reported by the timeit.py script when variables are accessed. This is
983 due to the fact that %timeit executes the statement in the namespace
981 due to the fact that %timeit executes the statement in the namespace
984 of the shell, compared with timeit.py, which uses a single setup
982 of the shell, compared with timeit.py, which uses a single setup
985 statement to import function or create variables. Generally, the bias
983 statement to import function or create variables. Generally, the bias
986 does not matter as long as results from timeit.py are not mixed with
984 does not matter as long as results from timeit.py are not mixed with
987 those from %timeit."""
985 those from %timeit."""
988
986
989 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
987 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
990 posix=False, strict=False)
988 posix=False, strict=False)
991 if stmt == "" and cell is None:
989 if stmt == "" and cell is None:
992 return
990 return
993
991
994 timefunc = timeit.default_timer
992 timefunc = timeit.default_timer
995 number = int(getattr(opts, "n", 0))
993 number = int(getattr(opts, "n", 0))
996 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
994 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
997 repeat = int(getattr(opts, "r", default_repeat))
995 repeat = int(getattr(opts, "r", default_repeat))
998 precision = int(getattr(opts, "p", 3))
996 precision = int(getattr(opts, "p", 3))
999 quiet = 'q' in opts
997 quiet = 'q' in opts
1000 return_result = 'o' in opts
998 return_result = 'o' in opts
1001 if hasattr(opts, "t"):
999 if hasattr(opts, "t"):
1002 timefunc = time.time
1000 timefunc = time.time
1003 if hasattr(opts, "c"):
1001 if hasattr(opts, "c"):
1004 timefunc = clock
1002 timefunc = clock
1005
1003
1006 timer = Timer(timer=timefunc)
1004 timer = Timer(timer=timefunc)
1007 # this code has tight coupling to the inner workings of timeit.Timer,
1005 # this code has tight coupling to the inner workings of timeit.Timer,
1008 # but is there a better way to achieve that the code stmt has access
1006 # but is there a better way to achieve that the code stmt has access
1009 # to the shell namespace?
1007 # to the shell namespace?
1010 transform = self.shell.input_splitter.transform_cell
1008 transform = self.shell.input_splitter.transform_cell
1011
1009
1012 if cell is None:
1010 if cell is None:
1013 # called as line magic
1011 # called as line magic
1014 ast_setup = self.shell.compile.ast_parse("pass")
1012 ast_setup = self.shell.compile.ast_parse("pass")
1015 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1013 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1016 else:
1014 else:
1017 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1015 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1018 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1016 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1019
1017
1020 ast_setup = self.shell.transform_ast(ast_setup)
1018 ast_setup = self.shell.transform_ast(ast_setup)
1021 ast_stmt = self.shell.transform_ast(ast_stmt)
1019 ast_stmt = self.shell.transform_ast(ast_stmt)
1022
1020
1023 # This codestring is taken from timeit.template - we fill it in as an
1021 # This codestring is taken from timeit.template - we fill it in as an
1024 # AST, so that we can apply our AST transformations to the user code
1022 # AST, so that we can apply our AST transformations to the user code
1025 # without affecting the timing code.
1023 # without affecting the timing code.
1026 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1024 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1027 ' setup\n'
1025 ' setup\n'
1028 ' _t0 = _timer()\n'
1026 ' _t0 = _timer()\n'
1029 ' for _i in _it:\n'
1027 ' for _i in _it:\n'
1030 ' stmt\n'
1028 ' stmt\n'
1031 ' _t1 = _timer()\n'
1029 ' _t1 = _timer()\n'
1032 ' return _t1 - _t0\n')
1030 ' return _t1 - _t0\n')
1033
1031
1034 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1032 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1035 timeit_ast = ast.fix_missing_locations(timeit_ast)
1033 timeit_ast = ast.fix_missing_locations(timeit_ast)
1036
1034
1037 # Track compilation time so it can be reported if too long
1035 # Track compilation time so it can be reported if too long
1038 # Minimum time above which compilation time will be reported
1036 # Minimum time above which compilation time will be reported
1039 tc_min = 0.1
1037 tc_min = 0.1
1040
1038
1041 t0 = clock()
1039 t0 = clock()
1042 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1040 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1043 tc = clock()-t0
1041 tc = clock()-t0
1044
1042
1045 ns = {}
1043 ns = {}
1046 exec(code, self.shell.user_ns, ns)
1044 exec(code, self.shell.user_ns, ns)
1047 timer.inner = ns["inner"]
1045 timer.inner = ns["inner"]
1048
1046
1049 # This is used to check if there is a huge difference between the
1047 # This is used to check if there is a huge difference between the
1050 # best and worst timings.
1048 # best and worst timings.
1051 # Issue: https://github.com/ipython/ipython/issues/6471
1049 # Issue: https://github.com/ipython/ipython/issues/6471
1052 if number == 0:
1050 if number == 0:
1053 # determine number so that 0.2 <= total time < 2.0
1051 # determine number so that 0.2 <= total time < 2.0
1054 for index in range(0, 10):
1052 for index in range(0, 10):
1055 number = 10 ** index
1053 number = 10 ** index
1056 time_number = timer.timeit(number)
1054 time_number = timer.timeit(number)
1057 if time_number >= 0.2:
1055 if time_number >= 0.2:
1058 break
1056 break
1059
1057
1060 all_runs = timer.repeat(repeat, number)
1058 all_runs = timer.repeat(repeat, number)
1061 best = min(all_runs) / number
1059 best = min(all_runs) / number
1062 worst = max(all_runs) / number
1060 worst = max(all_runs) / number
1063 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1061 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1064
1062
1065 if not quiet :
1063 if not quiet :
1066 # Check best timing is greater than zero to avoid a
1064 # Check best timing is greater than zero to avoid a
1067 # ZeroDivisionError.
1065 # ZeroDivisionError.
1068 # In cases where the slowest timing is lesser than a micosecond
1066 # In cases where the slowest timing is lesser than a micosecond
1069 # we assume that it does not really matter if the fastest
1067 # we assume that it does not really matter if the fastest
1070 # timing is 4 times faster than the slowest timing or not.
1068 # timing is 4 times faster than the slowest timing or not.
1071 if worst > 4 * best and best > 0 and worst > 1e-6:
1069 if worst > 4 * best and best > 0 and worst > 1e-6:
1072 print("The slowest run took %0.2f times longer than the "
1070 print("The slowest run took %0.2f times longer than the "
1073 "fastest. This could mean that an intermediate result "
1071 "fastest. This could mean that an intermediate result "
1074 "is being cached." % (worst / best))
1072 "is being cached." % (worst / best))
1075
1073
1076 print( timeit_result )
1074 print( timeit_result )
1077
1075
1078 if tc > tc_min:
1076 if tc > tc_min:
1079 print("Compiler time: %.2f s" % tc)
1077 print("Compiler time: %.2f s" % tc)
1080 if return_result:
1078 if return_result:
1081 return timeit_result
1079 return timeit_result
1082
1080
1083 @skip_doctest
1081 @skip_doctest
1084 @needs_local_scope
1082 @needs_local_scope
1085 @line_cell_magic
1083 @line_cell_magic
1086 def time(self,line='', cell=None, local_ns=None):
1084 def time(self,line='', cell=None, local_ns=None):
1087 """Time execution of a Python statement or expression.
1085 """Time execution of a Python statement or expression.
1088
1086
1089 The CPU and wall clock times are printed, and the value of the
1087 The CPU and wall clock times are printed, and the value of the
1090 expression (if any) is returned. Note that under Win32, system time
1088 expression (if any) is returned. Note that under Win32, system time
1091 is always reported as 0, since it can not be measured.
1089 is always reported as 0, since it can not be measured.
1092
1090
1093 This function can be used both as a line and cell magic:
1091 This function can be used both as a line and cell magic:
1094
1092
1095 - In line mode you can time a single-line statement (though multiple
1093 - In line mode you can time a single-line statement (though multiple
1096 ones can be chained with using semicolons).
1094 ones can be chained with using semicolons).
1097
1095
1098 - In cell mode, you can time the cell body (a directly
1096 - In cell mode, you can time the cell body (a directly
1099 following statement raises an error).
1097 following statement raises an error).
1100
1098
1101 This function provides very basic timing functionality. Use the timeit
1099 This function provides very basic timing functionality. Use the timeit
1102 magic for more control over the measurement.
1100 magic for more control over the measurement.
1103
1101
1104 Examples
1102 Examples
1105 --------
1103 --------
1106 ::
1104 ::
1107
1105
1108 In [1]: %time 2**128
1106 In [1]: %time 2**128
1109 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1107 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1110 Wall time: 0.00
1108 Wall time: 0.00
1111 Out[1]: 340282366920938463463374607431768211456L
1109 Out[1]: 340282366920938463463374607431768211456L
1112
1110
1113 In [2]: n = 1000000
1111 In [2]: n = 1000000
1114
1112
1115 In [3]: %time sum(range(n))
1113 In [3]: %time sum(range(n))
1116 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1114 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1117 Wall time: 1.37
1115 Wall time: 1.37
1118 Out[3]: 499999500000L
1116 Out[3]: 499999500000L
1119
1117
1120 In [4]: %time print 'hello world'
1118 In [4]: %time print 'hello world'
1121 hello world
1119 hello world
1122 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1120 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1123 Wall time: 0.00
1121 Wall time: 0.00
1124
1122
1125 Note that the time needed by Python to compile the given expression
1123 Note that the time needed by Python to compile the given expression
1126 will be reported if it is more than 0.1s. In this example, the
1124 will be reported if it is more than 0.1s. In this example, the
1127 actual exponentiation is done by Python at compilation time, so while
1125 actual exponentiation is done by Python at compilation time, so while
1128 the expression can take a noticeable amount of time to compute, that
1126 the expression can take a noticeable amount of time to compute, that
1129 time is purely due to the compilation:
1127 time is purely due to the compilation:
1130
1128
1131 In [5]: %time 3**9999;
1129 In [5]: %time 3**9999;
1132 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1130 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1133 Wall time: 0.00 s
1131 Wall time: 0.00 s
1134
1132
1135 In [6]: %time 3**999999;
1133 In [6]: %time 3**999999;
1136 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1134 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1137 Wall time: 0.00 s
1135 Wall time: 0.00 s
1138 Compiler : 0.78 s
1136 Compiler : 0.78 s
1139 """
1137 """
1140
1138
1141 # fail immediately if the given expression can't be compiled
1139 # fail immediately if the given expression can't be compiled
1142
1140
1143 if line and cell:
1141 if line and cell:
1144 raise UsageError("Can't use statement directly after '%%time'!")
1142 raise UsageError("Can't use statement directly after '%%time'!")
1145
1143
1146 if cell:
1144 if cell:
1147 expr = self.shell.input_transformer_manager.transform_cell(cell)
1145 expr = self.shell.input_transformer_manager.transform_cell(cell)
1148 else:
1146 else:
1149 expr = self.shell.input_transformer_manager.transform_cell(line)
1147 expr = self.shell.input_transformer_manager.transform_cell(line)
1150
1148
1151 # Minimum time above which parse time will be reported
1149 # Minimum time above which parse time will be reported
1152 tp_min = 0.1
1150 tp_min = 0.1
1153
1151
1154 t0 = clock()
1152 t0 = clock()
1155 expr_ast = self.shell.compile.ast_parse(expr)
1153 expr_ast = self.shell.compile.ast_parse(expr)
1156 tp = clock()-t0
1154 tp = clock()-t0
1157
1155
1158 # Apply AST transformations
1156 # Apply AST transformations
1159 expr_ast = self.shell.transform_ast(expr_ast)
1157 expr_ast = self.shell.transform_ast(expr_ast)
1160
1158
1161 # Minimum time above which compilation time will be reported
1159 # Minimum time above which compilation time will be reported
1162 tc_min = 0.1
1160 tc_min = 0.1
1163
1161
1164 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1162 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1165 mode = 'eval'
1163 mode = 'eval'
1166 source = '<timed eval>'
1164 source = '<timed eval>'
1167 expr_ast = ast.Expression(expr_ast.body[0].value)
1165 expr_ast = ast.Expression(expr_ast.body[0].value)
1168 else:
1166 else:
1169 mode = 'exec'
1167 mode = 'exec'
1170 source = '<timed exec>'
1168 source = '<timed exec>'
1171 t0 = clock()
1169 t0 = clock()
1172 code = self.shell.compile(expr_ast, source, mode)
1170 code = self.shell.compile(expr_ast, source, mode)
1173 tc = clock()-t0
1171 tc = clock()-t0
1174
1172
1175 # skew measurement as little as possible
1173 # skew measurement as little as possible
1176 glob = self.shell.user_ns
1174 glob = self.shell.user_ns
1177 wtime = time.time
1175 wtime = time.time
1178 # time execution
1176 # time execution
1179 wall_st = wtime()
1177 wall_st = wtime()
1180 if mode=='eval':
1178 if mode=='eval':
1181 st = clock2()
1179 st = clock2()
1182 out = eval(code, glob, local_ns)
1180 out = eval(code, glob, local_ns)
1183 end = clock2()
1181 end = clock2()
1184 else:
1182 else:
1185 st = clock2()
1183 st = clock2()
1186 exec(code, glob, local_ns)
1184 exec(code, glob, local_ns)
1187 end = clock2()
1185 end = clock2()
1188 out = None
1186 out = None
1189 wall_end = wtime()
1187 wall_end = wtime()
1190 # Compute actual times and report
1188 # Compute actual times and report
1191 wall_time = wall_end-wall_st
1189 wall_time = wall_end-wall_st
1192 cpu_user = end[0]-st[0]
1190 cpu_user = end[0]-st[0]
1193 cpu_sys = end[1]-st[1]
1191 cpu_sys = end[1]-st[1]
1194 cpu_tot = cpu_user+cpu_sys
1192 cpu_tot = cpu_user+cpu_sys
1195 # On windows cpu_sys is always zero, so no new information to the next print
1193 # On windows cpu_sys is always zero, so no new information to the next print
1196 if sys.platform != 'win32':
1194 if sys.platform != 'win32':
1197 print("CPU times: user %s, sys: %s, total: %s" % \
1195 print("CPU times: user %s, sys: %s, total: %s" % \
1198 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1196 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1199 print("Wall time: %s" % _format_time(wall_time))
1197 print("Wall time: %s" % _format_time(wall_time))
1200 if tc > tc_min:
1198 if tc > tc_min:
1201 print("Compiler : %s" % _format_time(tc))
1199 print("Compiler : %s" % _format_time(tc))
1202 if tp > tp_min:
1200 if tp > tp_min:
1203 print("Parser : %s" % _format_time(tp))
1201 print("Parser : %s" % _format_time(tp))
1204 return out
1202 return out
1205
1203
1206 @skip_doctest
1204 @skip_doctest
1207 @line_magic
1205 @line_magic
1208 def macro(self, parameter_s=''):
1206 def macro(self, parameter_s=''):
1209 """Define a macro for future re-execution. It accepts ranges of history,
1207 """Define a macro for future re-execution. It accepts ranges of history,
1210 filenames or string objects.
1208 filenames or string objects.
1211
1209
1212 Usage:\\
1210 Usage:\\
1213 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1211 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1214
1212
1215 Options:
1213 Options:
1216
1214
1217 -r: use 'raw' input. By default, the 'processed' history is used,
1215 -r: use 'raw' input. By default, the 'processed' history is used,
1218 so that magics are loaded in their transformed version to valid
1216 so that magics are loaded in their transformed version to valid
1219 Python. If this option is given, the raw input as typed at the
1217 Python. If this option is given, the raw input as typed at the
1220 command line is used instead.
1218 command line is used instead.
1221
1219
1222 -q: quiet macro definition. By default, a tag line is printed
1220 -q: quiet macro definition. By default, a tag line is printed
1223 to indicate the macro has been created, and then the contents of
1221 to indicate the macro has been created, and then the contents of
1224 the macro are printed. If this option is given, then no printout
1222 the macro are printed. If this option is given, then no printout
1225 is produced once the macro is created.
1223 is produced once the macro is created.
1226
1224
1227 This will define a global variable called `name` which is a string
1225 This will define a global variable called `name` which is a string
1228 made of joining the slices and lines you specify (n1,n2,... numbers
1226 made of joining the slices and lines you specify (n1,n2,... numbers
1229 above) from your input history into a single string. This variable
1227 above) from your input history into a single string. This variable
1230 acts like an automatic function which re-executes those lines as if
1228 acts like an automatic function which re-executes those lines as if
1231 you had typed them. You just type 'name' at the prompt and the code
1229 you had typed them. You just type 'name' at the prompt and the code
1232 executes.
1230 executes.
1233
1231
1234 The syntax for indicating input ranges is described in %history.
1232 The syntax for indicating input ranges is described in %history.
1235
1233
1236 Note: as a 'hidden' feature, you can also use traditional python slice
1234 Note: as a 'hidden' feature, you can also use traditional python slice
1237 notation, where N:M means numbers N through M-1.
1235 notation, where N:M means numbers N through M-1.
1238
1236
1239 For example, if your history contains (print using %hist -n )::
1237 For example, if your history contains (print using %hist -n )::
1240
1238
1241 44: x=1
1239 44: x=1
1242 45: y=3
1240 45: y=3
1243 46: z=x+y
1241 46: z=x+y
1244 47: print x
1242 47: print x
1245 48: a=5
1243 48: a=5
1246 49: print 'x',x,'y',y
1244 49: print 'x',x,'y',y
1247
1245
1248 you can create a macro with lines 44 through 47 (included) and line 49
1246 you can create a macro with lines 44 through 47 (included) and line 49
1249 called my_macro with::
1247 called my_macro with::
1250
1248
1251 In [55]: %macro my_macro 44-47 49
1249 In [55]: %macro my_macro 44-47 49
1252
1250
1253 Now, typing `my_macro` (without quotes) will re-execute all this code
1251 Now, typing `my_macro` (without quotes) will re-execute all this code
1254 in one pass.
1252 in one pass.
1255
1253
1256 You don't need to give the line-numbers in order, and any given line
1254 You don't need to give the line-numbers in order, and any given line
1257 number can appear multiple times. You can assemble macros with any
1255 number can appear multiple times. You can assemble macros with any
1258 lines from your input history in any order.
1256 lines from your input history in any order.
1259
1257
1260 The macro is a simple object which holds its value in an attribute,
1258 The macro is a simple object which holds its value in an attribute,
1261 but IPython's display system checks for macros and executes them as
1259 but IPython's display system checks for macros and executes them as
1262 code instead of printing them when you type their name.
1260 code instead of printing them when you type their name.
1263
1261
1264 You can view a macro's contents by explicitly printing it with::
1262 You can view a macro's contents by explicitly printing it with::
1265
1263
1266 print macro_name
1264 print macro_name
1267
1265
1268 """
1266 """
1269 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1267 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1270 if not args: # List existing macros
1268 if not args: # List existing macros
1271 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1269 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1272 isinstance(v, Macro))
1270 isinstance(v, Macro))
1273 if len(args) == 1:
1271 if len(args) == 1:
1274 raise UsageError(
1272 raise UsageError(
1275 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1273 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1276 name, codefrom = args[0], " ".join(args[1:])
1274 name, codefrom = args[0], " ".join(args[1:])
1277
1275
1278 #print 'rng',ranges # dbg
1276 #print 'rng',ranges # dbg
1279 try:
1277 try:
1280 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1278 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1281 except (ValueError, TypeError) as e:
1279 except (ValueError, TypeError) as e:
1282 print(e.args[0])
1280 print(e.args[0])
1283 return
1281 return
1284 macro = Macro(lines)
1282 macro = Macro(lines)
1285 self.shell.define_macro(name, macro)
1283 self.shell.define_macro(name, macro)
1286 if not ( 'q' in opts) :
1284 if not ( 'q' in opts) :
1287 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1285 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1288 print('=== Macro contents: ===')
1286 print('=== Macro contents: ===')
1289 print(macro, end=' ')
1287 print(macro, end=' ')
1290
1288
1291 @magic_arguments.magic_arguments()
1289 @magic_arguments.magic_arguments()
1292 @magic_arguments.argument('output', type=str, default='', nargs='?',
1290 @magic_arguments.argument('output', type=str, default='', nargs='?',
1293 help="""The name of the variable in which to store output.
1291 help="""The name of the variable in which to store output.
1294 This is a utils.io.CapturedIO object with stdout/err attributes
1292 This is a utils.io.CapturedIO object with stdout/err attributes
1295 for the text of the captured output.
1293 for the text of the captured output.
1296
1294
1297 CapturedOutput also has a show() method for displaying the output,
1295 CapturedOutput also has a show() method for displaying the output,
1298 and __call__ as well, so you can use that to quickly display the
1296 and __call__ as well, so you can use that to quickly display the
1299 output.
1297 output.
1300
1298
1301 If unspecified, captured output is discarded.
1299 If unspecified, captured output is discarded.
1302 """
1300 """
1303 )
1301 )
1304 @magic_arguments.argument('--no-stderr', action="store_true",
1302 @magic_arguments.argument('--no-stderr', action="store_true",
1305 help="""Don't capture stderr."""
1303 help="""Don't capture stderr."""
1306 )
1304 )
1307 @magic_arguments.argument('--no-stdout', action="store_true",
1305 @magic_arguments.argument('--no-stdout', action="store_true",
1308 help="""Don't capture stdout."""
1306 help="""Don't capture stdout."""
1309 )
1307 )
1310 @magic_arguments.argument('--no-display', action="store_true",
1308 @magic_arguments.argument('--no-display', action="store_true",
1311 help="""Don't capture IPython's rich display."""
1309 help="""Don't capture IPython's rich display."""
1312 )
1310 )
1313 @cell_magic
1311 @cell_magic
1314 def capture(self, line, cell):
1312 def capture(self, line, cell):
1315 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1313 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1316 args = magic_arguments.parse_argstring(self.capture, line)
1314 args = magic_arguments.parse_argstring(self.capture, line)
1317 out = not args.no_stdout
1315 out = not args.no_stdout
1318 err = not args.no_stderr
1316 err = not args.no_stderr
1319 disp = not args.no_display
1317 disp = not args.no_display
1320 with capture_output(out, err, disp) as io:
1318 with capture_output(out, err, disp) as io:
1321 self.shell.run_cell(cell)
1319 self.shell.run_cell(cell)
1322 if args.output:
1320 if args.output:
1323 self.shell.user_ns[args.output] = io
1321 self.shell.user_ns[args.output] = io
1324
1322
1325 def parse_breakpoint(text, current_file):
1323 def parse_breakpoint(text, current_file):
1326 '''Returns (file, line) for file:line and (current_file, line) for line'''
1324 '''Returns (file, line) for file:line and (current_file, line) for line'''
1327 colon = text.find(':')
1325 colon = text.find(':')
1328 if colon == -1:
1326 if colon == -1:
1329 return current_file, int(text)
1327 return current_file, int(text)
1330 else:
1328 else:
1331 return text[:colon], int(text[colon+1:])
1329 return text[:colon], int(text[colon+1:])
1332
1330
1333 def _format_time(timespan, precision=3):
1331 def _format_time(timespan, precision=3):
1334 """Formats the timespan in a human readable form"""
1332 """Formats the timespan in a human readable form"""
1335
1333
1336 if timespan >= 60.0:
1334 if timespan >= 60.0:
1337 # we have more than a minute, format that in a human readable form
1335 # we have more than a minute, format that in a human readable form
1338 # Idea from http://snipplr.com/view/5713/
1336 # Idea from http://snipplr.com/view/5713/
1339 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1337 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1340 time = []
1338 time = []
1341 leftover = timespan
1339 leftover = timespan
1342 for suffix, length in parts:
1340 for suffix, length in parts:
1343 value = int(leftover / length)
1341 value = int(leftover / length)
1344 if value > 0:
1342 if value > 0:
1345 leftover = leftover % length
1343 leftover = leftover % length
1346 time.append(u'%s%s' % (str(value), suffix))
1344 time.append(u'%s%s' % (str(value), suffix))
1347 if leftover < 1:
1345 if leftover < 1:
1348 break
1346 break
1349 return " ".join(time)
1347 return " ".join(time)
1350
1348
1351
1349
1352 # Unfortunately the unicode 'micro' symbol can cause problems in
1350 # Unfortunately the unicode 'micro' symbol can cause problems in
1353 # certain terminals.
1351 # certain terminals.
1354 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1352 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1355 # Try to prevent crashes by being more secure than it needs to
1353 # Try to prevent crashes by being more secure than it needs to
1356 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1354 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1357 units = [u"s", u"ms",u'us',"ns"] # the save value
1355 units = [u"s", u"ms",u'us',"ns"] # the save value
1358 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1356 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1359 try:
1357 try:
1360 u'\xb5'.encode(sys.stdout.encoding)
1358 u'\xb5'.encode(sys.stdout.encoding)
1361 units = [u"s", u"ms",u'\xb5s',"ns"]
1359 units = [u"s", u"ms",u'\xb5s',"ns"]
1362 except:
1360 except:
1363 pass
1361 pass
1364 scaling = [1, 1e3, 1e6, 1e9]
1362 scaling = [1, 1e3, 1e6, 1e9]
1365
1363
1366 if timespan > 0.0:
1364 if timespan > 0.0:
1367 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1365 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1368 else:
1366 else:
1369 order = 3
1367 order = 3
1370 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1368 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,67 +1,66 b''
1 """Implementation of magic functions for the extension machinery.
1 """Implementation of magic functions for the extension machinery.
2 """
2 """
3 from __future__ import print_function
4 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
6 #
5 #
7 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
8 #
7 #
9 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
11
10
12 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
13 # Imports
12 # Imports
14 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
15
14
16 # Stdlib
15 # Stdlib
17 import os
16 import os
18
17
19 # Our own packages
18 # Our own packages
20 from IPython.core.error import UsageError
19 from IPython.core.error import UsageError
21 from IPython.core.magic import Magics, magics_class, line_magic
20 from IPython.core.magic import Magics, magics_class, line_magic
22 from warnings import warn
21 from warnings import warn
23
22
24 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
25 # Magic implementation classes
24 # Magic implementation classes
26 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
27
26
28 @magics_class
27 @magics_class
29 class ExtensionMagics(Magics):
28 class ExtensionMagics(Magics):
30 """Magics to manage the IPython extensions system."""
29 """Magics to manage the IPython extensions system."""
31
30
32 @line_magic
31 @line_magic
33 def load_ext(self, module_str):
32 def load_ext(self, module_str):
34 """Load an IPython extension by its module name."""
33 """Load an IPython extension by its module name."""
35 if not module_str:
34 if not module_str:
36 raise UsageError('Missing module name.')
35 raise UsageError('Missing module name.')
37 res = self.shell.extension_manager.load_extension(module_str)
36 res = self.shell.extension_manager.load_extension(module_str)
38
37
39 if res == 'already loaded':
38 if res == 'already loaded':
40 print("The %s extension is already loaded. To reload it, use:" % module_str)
39 print("The %s extension is already loaded. To reload it, use:" % module_str)
41 print(" %reload_ext", module_str)
40 print(" %reload_ext", module_str)
42 elif res == 'no load function':
41 elif res == 'no load function':
43 print("The %s module is not an IPython extension." % module_str)
42 print("The %s module is not an IPython extension." % module_str)
44
43
45 @line_magic
44 @line_magic
46 def unload_ext(self, module_str):
45 def unload_ext(self, module_str):
47 """Unload an IPython extension by its module name.
46 """Unload an IPython extension by its module name.
48
47
49 Not all extensions can be unloaded, only those which define an
48 Not all extensions can be unloaded, only those which define an
50 ``unload_ipython_extension`` function.
49 ``unload_ipython_extension`` function.
51 """
50 """
52 if not module_str:
51 if not module_str:
53 raise UsageError('Missing module name.')
52 raise UsageError('Missing module name.')
54
53
55 res = self.shell.extension_manager.unload_extension(module_str)
54 res = self.shell.extension_manager.unload_extension(module_str)
56
55
57 if res == 'no unload function':
56 if res == 'no unload function':
58 print("The %s extension doesn't define how to unload it." % module_str)
57 print("The %s extension doesn't define how to unload it." % module_str)
59 elif res == "not loaded":
58 elif res == "not loaded":
60 print("The %s extension is not loaded." % module_str)
59 print("The %s extension is not loaded." % module_str)
61
60
62 @line_magic
61 @line_magic
63 def reload_ext(self, module_str):
62 def reload_ext(self, module_str):
64 """Reload an IPython extension by its module name."""
63 """Reload an IPython extension by its module name."""
65 if not module_str:
64 if not module_str:
66 raise UsageError('Missing module name.')
65 raise UsageError('Missing module name.')
67 self.shell.extension_manager.reload_extension(module_str)
66 self.shell.extension_manager.reload_extension(module_str)
@@ -1,320 +1,319 b''
1 """Implementation of magic functions related to History.
1 """Implementation of magic functions related to History.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012, IPython Development Team.
4 # Copyright (c) 2012, IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 from __future__ import print_function
15
14
16 # Stdlib
15 # Stdlib
17 import os
16 import os
18 import sys
17 import sys
19 from io import open as io_open
18 from io import open as io_open
20
19
21 # Our own packages
20 # Our own packages
22 from IPython.core.error import StdinNotImplementedError
21 from IPython.core.error import StdinNotImplementedError
23 from IPython.core.magic import Magics, magics_class, line_magic
22 from IPython.core.magic import Magics, magics_class, line_magic
24 from IPython.core.magic_arguments import (argument, magic_arguments,
23 from IPython.core.magic_arguments import (argument, magic_arguments,
25 parse_argstring)
24 parse_argstring)
26 from IPython.testing.skipdoctest import skip_doctest
25 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.utils import io
26 from IPython.utils import io
28 from IPython.utils.py3compat import cast_unicode_py2
27 from IPython.utils.py3compat import cast_unicode_py2
29
28
30 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
31 # Magics class implementation
30 # Magics class implementation
32 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
33
32
34
33
35 _unspecified = object()
34 _unspecified = object()
36
35
37
36
38 @magics_class
37 @magics_class
39 class HistoryMagics(Magics):
38 class HistoryMagics(Magics):
40
39
41 @magic_arguments()
40 @magic_arguments()
42 @argument(
41 @argument(
43 '-n', dest='print_nums', action='store_true', default=False,
42 '-n', dest='print_nums', action='store_true', default=False,
44 help="""
43 help="""
45 print line numbers for each input.
44 print line numbers for each input.
46 This feature is only available if numbered prompts are in use.
45 This feature is only available if numbered prompts are in use.
47 """)
46 """)
48 @argument(
47 @argument(
49 '-o', dest='get_output', action='store_true', default=False,
48 '-o', dest='get_output', action='store_true', default=False,
50 help="also print outputs for each input.")
49 help="also print outputs for each input.")
51 @argument(
50 @argument(
52 '-p', dest='pyprompts', action='store_true', default=False,
51 '-p', dest='pyprompts', action='store_true', default=False,
53 help="""
52 help="""
54 print classic '>>>' python prompts before each input.
53 print classic '>>>' python prompts before each input.
55 This is useful for making documentation, and in conjunction
54 This is useful for making documentation, and in conjunction
56 with -o, for producing doctest-ready output.
55 with -o, for producing doctest-ready output.
57 """)
56 """)
58 @argument(
57 @argument(
59 '-t', dest='raw', action='store_false', default=True,
58 '-t', dest='raw', action='store_false', default=True,
60 help="""
59 help="""
61 print the 'translated' history, as IPython understands it.
60 print the 'translated' history, as IPython understands it.
62 IPython filters your input and converts it all into valid Python
61 IPython filters your input and converts it all into valid Python
63 source before executing it (things like magics or aliases are turned
62 source before executing it (things like magics or aliases are turned
64 into function calls, for example). With this option, you'll see the
63 into function calls, for example). With this option, you'll see the
65 native history instead of the user-entered version: '%%cd /' will be
64 native history instead of the user-entered version: '%%cd /' will be
66 seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
65 seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
67 """)
66 """)
68 @argument(
67 @argument(
69 '-f', dest='filename',
68 '-f', dest='filename',
70 help="""
69 help="""
71 FILENAME: instead of printing the output to the screen, redirect
70 FILENAME: instead of printing the output to the screen, redirect
72 it to the given file. The file is always overwritten, though *when
71 it to the given file. The file is always overwritten, though *when
73 it can*, IPython asks for confirmation first. In particular, running
72 it can*, IPython asks for confirmation first. In particular, running
74 the command 'history -f FILENAME' from the IPython Notebook
73 the command 'history -f FILENAME' from the IPython Notebook
75 interface will replace FILENAME even if it already exists *without*
74 interface will replace FILENAME even if it already exists *without*
76 confirmation.
75 confirmation.
77 """)
76 """)
78 @argument(
77 @argument(
79 '-g', dest='pattern', nargs='*', default=None,
78 '-g', dest='pattern', nargs='*', default=None,
80 help="""
79 help="""
81 treat the arg as a glob pattern to search for in (full) history.
80 treat the arg as a glob pattern to search for in (full) history.
82 This includes the saved history (almost all commands ever written).
81 This includes the saved history (almost all commands ever written).
83 The pattern may contain '?' to match one unknown character and '*'
82 The pattern may contain '?' to match one unknown character and '*'
84 to match any number of unknown characters. Use '%%hist -g' to show
83 to match any number of unknown characters. Use '%%hist -g' to show
85 full saved history (may be very long).
84 full saved history (may be very long).
86 """)
85 """)
87 @argument(
86 @argument(
88 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
87 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
89 help="""
88 help="""
90 get the last n lines from all sessions. Specify n as a single
89 get the last n lines from all sessions. Specify n as a single
91 arg, or the default is the last 10 lines.
90 arg, or the default is the last 10 lines.
92 """)
91 """)
93 @argument(
92 @argument(
94 '-u', dest='unique', action='store_true',
93 '-u', dest='unique', action='store_true',
95 help="""
94 help="""
96 when searching history using `-g`, show only unique history.
95 when searching history using `-g`, show only unique history.
97 """)
96 """)
98 @argument('range', nargs='*')
97 @argument('range', nargs='*')
99 @skip_doctest
98 @skip_doctest
100 @line_magic
99 @line_magic
101 def history(self, parameter_s = ''):
100 def history(self, parameter_s = ''):
102 """Print input history (_i<n> variables), with most recent last.
101 """Print input history (_i<n> variables), with most recent last.
103
102
104 By default, input history is printed without line numbers so it can be
103 By default, input history is printed without line numbers so it can be
105 directly pasted into an editor. Use -n to show them.
104 directly pasted into an editor. Use -n to show them.
106
105
107 By default, all input history from the current session is displayed.
106 By default, all input history from the current session is displayed.
108 Ranges of history can be indicated using the syntax:
107 Ranges of history can be indicated using the syntax:
109
108
110 ``4``
109 ``4``
111 Line 4, current session
110 Line 4, current session
112 ``4-6``
111 ``4-6``
113 Lines 4-6, current session
112 Lines 4-6, current session
114 ``243/1-5``
113 ``243/1-5``
115 Lines 1-5, session 243
114 Lines 1-5, session 243
116 ``~2/7``
115 ``~2/7``
117 Line 7, session 2 before current
116 Line 7, session 2 before current
118 ``~8/1-~6/5``
117 ``~8/1-~6/5``
119 From the first line of 8 sessions ago, to the fifth line of 6
118 From the first line of 8 sessions ago, to the fifth line of 6
120 sessions ago.
119 sessions ago.
121
120
122 Multiple ranges can be entered, separated by spaces
121 Multiple ranges can be entered, separated by spaces
123
122
124 The same syntax is used by %macro, %save, %edit, %rerun
123 The same syntax is used by %macro, %save, %edit, %rerun
125
124
126 Examples
125 Examples
127 --------
126 --------
128 ::
127 ::
129
128
130 In [6]: %history -n 4-6
129 In [6]: %history -n 4-6
131 4:a = 12
130 4:a = 12
132 5:print a**2
131 5:print a**2
133 6:%history -n 4-6
132 6:%history -n 4-6
134
133
135 """
134 """
136
135
137 args = parse_argstring(self.history, parameter_s)
136 args = parse_argstring(self.history, parameter_s)
138
137
139 # For brevity
138 # For brevity
140 history_manager = self.shell.history_manager
139 history_manager = self.shell.history_manager
141
140
142 def _format_lineno(session, line):
141 def _format_lineno(session, line):
143 """Helper function to format line numbers properly."""
142 """Helper function to format line numbers properly."""
144 if session in (0, history_manager.session_number):
143 if session in (0, history_manager.session_number):
145 return str(line)
144 return str(line)
146 return "%s/%s" % (session, line)
145 return "%s/%s" % (session, line)
147
146
148 # Check if output to specific file was requested.
147 # Check if output to specific file was requested.
149 outfname = args.filename
148 outfname = args.filename
150 if not outfname:
149 if not outfname:
151 outfile = sys.stdout # default
150 outfile = sys.stdout # default
152 # We don't want to close stdout at the end!
151 # We don't want to close stdout at the end!
153 close_at_end = False
152 close_at_end = False
154 else:
153 else:
155 if os.path.exists(outfname):
154 if os.path.exists(outfname):
156 try:
155 try:
157 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
156 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
158 except StdinNotImplementedError:
157 except StdinNotImplementedError:
159 ans = True
158 ans = True
160 if not ans:
159 if not ans:
161 print('Aborting.')
160 print('Aborting.')
162 return
161 return
163 print("Overwriting file.")
162 print("Overwriting file.")
164 outfile = io_open(outfname, 'w', encoding='utf-8')
163 outfile = io_open(outfname, 'w', encoding='utf-8')
165 close_at_end = True
164 close_at_end = True
166
165
167 print_nums = args.print_nums
166 print_nums = args.print_nums
168 get_output = args.get_output
167 get_output = args.get_output
169 pyprompts = args.pyprompts
168 pyprompts = args.pyprompts
170 raw = args.raw
169 raw = args.raw
171
170
172 pattern = None
171 pattern = None
173 limit = None if args.limit is _unspecified else args.limit
172 limit = None if args.limit is _unspecified else args.limit
174
173
175 if args.pattern is not None:
174 if args.pattern is not None:
176 if args.pattern:
175 if args.pattern:
177 pattern = "*" + " ".join(args.pattern) + "*"
176 pattern = "*" + " ".join(args.pattern) + "*"
178 else:
177 else:
179 pattern = "*"
178 pattern = "*"
180 hist = history_manager.search(pattern, raw=raw, output=get_output,
179 hist = history_manager.search(pattern, raw=raw, output=get_output,
181 n=limit, unique=args.unique)
180 n=limit, unique=args.unique)
182 print_nums = True
181 print_nums = True
183 elif args.limit is not _unspecified:
182 elif args.limit is not _unspecified:
184 n = 10 if limit is None else limit
183 n = 10 if limit is None else limit
185 hist = history_manager.get_tail(n, raw=raw, output=get_output)
184 hist = history_manager.get_tail(n, raw=raw, output=get_output)
186 else:
185 else:
187 if args.range: # Get history by ranges
186 if args.range: # Get history by ranges
188 hist = history_manager.get_range_by_str(" ".join(args.range),
187 hist = history_manager.get_range_by_str(" ".join(args.range),
189 raw, get_output)
188 raw, get_output)
190 else: # Just get history for the current session
189 else: # Just get history for the current session
191 hist = history_manager.get_range(raw=raw, output=get_output)
190 hist = history_manager.get_range(raw=raw, output=get_output)
192
191
193 # We could be displaying the entire history, so let's not try to pull
192 # We could be displaying the entire history, so let's not try to pull
194 # it into a list in memory. Anything that needs more space will just
193 # it into a list in memory. Anything that needs more space will just
195 # misalign.
194 # misalign.
196 width = 4
195 width = 4
197
196
198 for session, lineno, inline in hist:
197 for session, lineno, inline in hist:
199 # Print user history with tabs expanded to 4 spaces. The GUI
198 # Print user history with tabs expanded to 4 spaces. The GUI
200 # clients use hard tabs for easier usability in auto-indented code,
199 # clients use hard tabs for easier usability in auto-indented code,
201 # but we want to produce PEP-8 compliant history for safe pasting
200 # but we want to produce PEP-8 compliant history for safe pasting
202 # into an editor.
201 # into an editor.
203 if get_output:
202 if get_output:
204 inline, output = inline
203 inline, output = inline
205 inline = inline.expandtabs(4).rstrip()
204 inline = inline.expandtabs(4).rstrip()
206
205
207 multiline = "\n" in inline
206 multiline = "\n" in inline
208 line_sep = '\n' if multiline else ' '
207 line_sep = '\n' if multiline else ' '
209 if print_nums:
208 if print_nums:
210 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
209 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
211 line_sep), file=outfile, end=u'')
210 line_sep), file=outfile, end=u'')
212 if pyprompts:
211 if pyprompts:
213 print(u">>> ", end=u"", file=outfile)
212 print(u">>> ", end=u"", file=outfile)
214 if multiline:
213 if multiline:
215 inline = "\n... ".join(inline.splitlines()) + "\n..."
214 inline = "\n... ".join(inline.splitlines()) + "\n..."
216 print(inline, file=outfile)
215 print(inline, file=outfile)
217 if get_output and output:
216 if get_output and output:
218 print(cast_unicode_py2(output), file=outfile)
217 print(cast_unicode_py2(output), file=outfile)
219
218
220 if close_at_end:
219 if close_at_end:
221 outfile.close()
220 outfile.close()
222
221
223 @line_magic
222 @line_magic
224 def recall(self, arg):
223 def recall(self, arg):
225 r"""Repeat a command, or get command to input line for editing.
224 r"""Repeat a command, or get command to input line for editing.
226
225
227 %recall and %rep are equivalent.
226 %recall and %rep are equivalent.
228
227
229 - %recall (no arguments):
228 - %recall (no arguments):
230
229
231 Place a string version of last computation result (stored in the
230 Place a string version of last computation result (stored in the
232 special '_' variable) to the next input prompt. Allows you to create
231 special '_' variable) to the next input prompt. Allows you to create
233 elaborate command lines without using copy-paste::
232 elaborate command lines without using copy-paste::
234
233
235 In[1]: l = ["hei", "vaan"]
234 In[1]: l = ["hei", "vaan"]
236 In[2]: "".join(l)
235 In[2]: "".join(l)
237 Out[2]: heivaan
236 Out[2]: heivaan
238 In[3]: %recall
237 In[3]: %recall
239 In[4]: heivaan_ <== cursor blinking
238 In[4]: heivaan_ <== cursor blinking
240
239
241 %recall 45
240 %recall 45
242
241
243 Place history line 45 on the next input prompt. Use %hist to find
242 Place history line 45 on the next input prompt. Use %hist to find
244 out the number.
243 out the number.
245
244
246 %recall 1-4
245 %recall 1-4
247
246
248 Combine the specified lines into one cell, and place it on the next
247 Combine the specified lines into one cell, and place it on the next
249 input prompt. See %history for the slice syntax.
248 input prompt. See %history for the slice syntax.
250
249
251 %recall foo+bar
250 %recall foo+bar
252
251
253 If foo+bar can be evaluated in the user namespace, the result is
252 If foo+bar can be evaluated in the user namespace, the result is
254 placed at the next input prompt. Otherwise, the history is searched
253 placed at the next input prompt. Otherwise, the history is searched
255 for lines which contain that substring, and the most recent one is
254 for lines which contain that substring, and the most recent one is
256 placed at the next input prompt.
255 placed at the next input prompt.
257 """
256 """
258 if not arg: # Last output
257 if not arg: # Last output
259 self.shell.set_next_input(str(self.shell.user_ns["_"]))
258 self.shell.set_next_input(str(self.shell.user_ns["_"]))
260 return
259 return
261 # Get history range
260 # Get history range
262 histlines = self.shell.history_manager.get_range_by_str(arg)
261 histlines = self.shell.history_manager.get_range_by_str(arg)
263 cmd = "\n".join(x[2] for x in histlines)
262 cmd = "\n".join(x[2] for x in histlines)
264 if cmd:
263 if cmd:
265 self.shell.set_next_input(cmd.rstrip())
264 self.shell.set_next_input(cmd.rstrip())
266 return
265 return
267
266
268 try: # Variable in user namespace
267 try: # Variable in user namespace
269 cmd = str(eval(arg, self.shell.user_ns))
268 cmd = str(eval(arg, self.shell.user_ns))
270 except Exception: # Search for term in history
269 except Exception: # Search for term in history
271 histlines = self.shell.history_manager.search("*"+arg+"*")
270 histlines = self.shell.history_manager.search("*"+arg+"*")
272 for h in reversed([x[2] for x in histlines]):
271 for h in reversed([x[2] for x in histlines]):
273 if 'recall' in h or 'rep' in h:
272 if 'recall' in h or 'rep' in h:
274 continue
273 continue
275 self.shell.set_next_input(h.rstrip())
274 self.shell.set_next_input(h.rstrip())
276 return
275 return
277 else:
276 else:
278 self.shell.set_next_input(cmd.rstrip())
277 self.shell.set_next_input(cmd.rstrip())
279 print("Couldn't evaluate or find in history:", arg)
278 print("Couldn't evaluate or find in history:", arg)
280
279
281 @line_magic
280 @line_magic
282 def rerun(self, parameter_s=''):
281 def rerun(self, parameter_s=''):
283 """Re-run previous input
282 """Re-run previous input
284
283
285 By default, you can specify ranges of input history to be repeated
284 By default, you can specify ranges of input history to be repeated
286 (as with %history). With no arguments, it will repeat the last line.
285 (as with %history). With no arguments, it will repeat the last line.
287
286
288 Options:
287 Options:
289
288
290 -l <n> : Repeat the last n lines of input, not including the
289 -l <n> : Repeat the last n lines of input, not including the
291 current command.
290 current command.
292
291
293 -g foo : Repeat the most recent line which contains foo
292 -g foo : Repeat the most recent line which contains foo
294 """
293 """
295 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
294 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
296 if "l" in opts: # Last n lines
295 if "l" in opts: # Last n lines
297 n = int(opts['l'])
296 n = int(opts['l'])
298 hist = self.shell.history_manager.get_tail(n)
297 hist = self.shell.history_manager.get_tail(n)
299 elif "g" in opts: # Search
298 elif "g" in opts: # Search
300 p = "*"+opts['g']+"*"
299 p = "*"+opts['g']+"*"
301 hist = list(self.shell.history_manager.search(p))
300 hist = list(self.shell.history_manager.search(p))
302 for l in reversed(hist):
301 for l in reversed(hist):
303 if "rerun" not in l[2]:
302 if "rerun" not in l[2]:
304 hist = [l] # The last match which isn't a %rerun
303 hist = [l] # The last match which isn't a %rerun
305 break
304 break
306 else:
305 else:
307 hist = [] # No matches except %rerun
306 hist = [] # No matches except %rerun
308 elif args: # Specify history ranges
307 elif args: # Specify history ranges
309 hist = self.shell.history_manager.get_range_by_str(args)
308 hist = self.shell.history_manager.get_range_by_str(args)
310 else: # Last line
309 else: # Last line
311 hist = self.shell.history_manager.get_tail(1)
310 hist = self.shell.history_manager.get_tail(1)
312 hist = [x[2] for x in hist]
311 hist = [x[2] for x in hist]
313 if not hist:
312 if not hist:
314 print("No lines in history match specification")
313 print("No lines in history match specification")
315 return
314 return
316 histlines = "\n".join(hist)
315 histlines = "\n".join(hist)
317 print("=== Executing: ===")
316 print("=== Executing: ===")
318 print(histlines)
317 print(histlines)
319 print("=== Output: ===")
318 print("=== Output: ===")
320 self.shell.run_cell("\n".join(hist), store_history=False)
319 self.shell.run_cell("\n".join(hist), store_history=False)
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
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