Show More
@@ -1,114 +1,114 b'' | |||
|
1 | 1 | """ |
|
2 | 2 | A context manager for managing things injected into :mod:`__builtin__`. |
|
3 | 3 | |
|
4 | 4 | Authors: |
|
5 | 5 | |
|
6 | 6 | * Brian Granger |
|
7 | 7 | * Fernando Perez |
|
8 | 8 | """ |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | # Copyright (C) 2010-2011 The IPython Development Team. |
|
11 | 11 | # |
|
12 | 12 | # Distributed under the terms of the BSD License. |
|
13 | 13 | # |
|
14 | 14 | # Complete license in the file COPYING.txt, distributed with this software. |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | # Imports |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | from traitlets.config.configurable import Configurable |
|
22 | 22 | |
|
23 | 23 | from IPython.utils.py3compat import builtin_mod, iteritems |
|
24 | 24 | from traitlets import Instance |
|
25 | 25 | |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | # Classes and functions |
|
28 | 28 | #----------------------------------------------------------------------------- |
|
29 | 29 | |
|
30 | 30 | class __BuiltinUndefined(object): pass |
|
31 | 31 | BuiltinUndefined = __BuiltinUndefined() |
|
32 | 32 | |
|
33 | 33 | class __HideBuiltin(object): pass |
|
34 | 34 | HideBuiltin = __HideBuiltin() |
|
35 | 35 | |
|
36 | 36 | |
|
37 | 37 | class BuiltinTrap(Configurable): |
|
38 | 38 | |
|
39 | 39 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', |
|
40 | 40 | allow_none=True) |
|
41 | 41 | |
|
42 | 42 | def __init__(self, shell=None): |
|
43 | 43 | super(BuiltinTrap, self).__init__(shell=shell, config=None) |
|
44 | 44 | self._orig_builtins = {} |
|
45 | 45 | # We define this to track if a single BuiltinTrap is nested. |
|
46 | 46 | # Only turn off the trap when the outermost call to __exit__ is made. |
|
47 | 47 | self._nested_level = 0 |
|
48 | 48 | self.shell = shell |
|
49 | 49 | # builtins we always add - if set to HideBuiltin, they will just |
|
50 | 50 | # be removed instead of being replaced by something else |
|
51 | 51 | self.auto_builtins = {'exit': HideBuiltin, |
|
52 | 52 | 'quit': HideBuiltin, |
|
53 | 53 | 'get_ipython': self.shell.get_ipython, |
|
54 | 54 | } |
|
55 | 55 | # Recursive reload function |
|
56 | 56 | try: |
|
57 | 57 | from IPython.lib import deepreload |
|
58 | 58 | if self.shell.deep_reload: |
|
59 | 59 | from warnings import warn |
|
60 | warn("Automatically replacing builtin `reload` by `deepreload.reload` is deprecated, please import `reload` explicitly from `IPython.lib.deeprelaod", DeprecationWarning) | |
|
60 | warn("Automatically replacing builtin `reload` by `deepreload.reload` is deprecated and will be removed in IPython 6.0, please import `reload` explicitly from `IPython.lib.deeprelaod", DeprecationWarning) | |
|
61 | 61 | self.auto_builtins['reload'] = deepreload._dreload |
|
62 | 62 | else: |
|
63 | 63 | self.auto_builtins['dreload']= deepreload._dreload |
|
64 | 64 | except ImportError: |
|
65 | 65 | pass |
|
66 | 66 | |
|
67 | 67 | def __enter__(self): |
|
68 | 68 | if self._nested_level == 0: |
|
69 | 69 | self.activate() |
|
70 | 70 | self._nested_level += 1 |
|
71 | 71 | # I return self, so callers can use add_builtin in a with clause. |
|
72 | 72 | return self |
|
73 | 73 | |
|
74 | 74 | def __exit__(self, type, value, traceback): |
|
75 | 75 | if self._nested_level == 1: |
|
76 | 76 | self.deactivate() |
|
77 | 77 | self._nested_level -= 1 |
|
78 | 78 | # Returning False will cause exceptions to propagate |
|
79 | 79 | return False |
|
80 | 80 | |
|
81 | 81 | def add_builtin(self, key, value): |
|
82 | 82 | """Add a builtin and save the original.""" |
|
83 | 83 | bdict = builtin_mod.__dict__ |
|
84 | 84 | orig = bdict.get(key, BuiltinUndefined) |
|
85 | 85 | if value is HideBuiltin: |
|
86 | 86 | if orig is not BuiltinUndefined: #same as 'key in bdict' |
|
87 | 87 | self._orig_builtins[key] = orig |
|
88 | 88 | del bdict[key] |
|
89 | 89 | else: |
|
90 | 90 | self._orig_builtins[key] = orig |
|
91 | 91 | bdict[key] = value |
|
92 | 92 | |
|
93 | 93 | def remove_builtin(self, key, orig): |
|
94 | 94 | """Remove an added builtin and re-set the original.""" |
|
95 | 95 | if orig is BuiltinUndefined: |
|
96 | 96 | del builtin_mod.__dict__[key] |
|
97 | 97 | else: |
|
98 | 98 | builtin_mod.__dict__[key] = orig |
|
99 | 99 | |
|
100 | 100 | def activate(self): |
|
101 | 101 | """Store ipython references in the __builtin__ namespace.""" |
|
102 | 102 | |
|
103 | 103 | add_builtin = self.add_builtin |
|
104 | 104 | for name, func in iteritems(self.auto_builtins): |
|
105 | 105 | add_builtin(name, func) |
|
106 | 106 | |
|
107 | 107 | def deactivate(self): |
|
108 | 108 | """Remove any builtins which might have been added by add_builtins, or |
|
109 | 109 | restore overwritten ones to their previous values.""" |
|
110 | 110 | remove_builtin = self.remove_builtin |
|
111 | 111 | for key, val in iteritems(self._orig_builtins): |
|
112 | 112 | remove_builtin(key, val) |
|
113 | 113 | self._orig_builtins.clear() |
|
114 | 114 | self._builtins_added = False |
@@ -1,147 +1,147 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Color schemes for exception handling code in IPython. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | import warnings |
|
7 | 7 | |
|
8 | 8 | #***************************************************************************** |
|
9 | 9 | # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu> |
|
10 | 10 | # |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | 12 | # the file COPYING, distributed as part of this software. |
|
13 | 13 | #***************************************************************************** |
|
14 | 14 | |
|
15 | 15 | from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme |
|
16 | 16 | |
|
17 | 17 | def exception_colors(): |
|
18 | 18 | """Return a color table with fields for exception reporting. |
|
19 | 19 | |
|
20 | 20 | The table is an instance of ColorSchemeTable with schemes added for |
|
21 | 21 | 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled |
|
22 | 22 | in. |
|
23 | 23 | |
|
24 | 24 | Examples: |
|
25 | 25 | |
|
26 | 26 | >>> ec = exception_colors() |
|
27 | 27 | >>> ec.active_scheme_name |
|
28 | 28 | '' |
|
29 | 29 | >>> print(ec.active_colors) |
|
30 | 30 | None |
|
31 | 31 | |
|
32 | 32 | Now we activate a color scheme: |
|
33 | 33 | >>> ec.set_active_scheme('NoColor') |
|
34 | 34 | >>> ec.active_scheme_name |
|
35 | 35 | 'NoColor' |
|
36 | 36 | >>> sorted(ec.active_colors.keys()) |
|
37 | 37 | ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line', |
|
38 | 38 | 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName', |
|
39 | 39 | 'val', 'valEm'] |
|
40 | 40 | """ |
|
41 | 41 | |
|
42 | 42 | ex_colors = ColorSchemeTable() |
|
43 | 43 | |
|
44 | 44 | # Populate it with color schemes |
|
45 | 45 | C = TermColors # shorthand and local lookup |
|
46 | 46 | ex_colors.add_scheme(ColorScheme( |
|
47 | 47 | 'NoColor', |
|
48 | 48 | # The color to be used for the top line |
|
49 | 49 | topline = C.NoColor, |
|
50 | 50 | |
|
51 | 51 | # The colors to be used in the traceback |
|
52 | 52 | filename = C.NoColor, |
|
53 | 53 | lineno = C.NoColor, |
|
54 | 54 | name = C.NoColor, |
|
55 | 55 | vName = C.NoColor, |
|
56 | 56 | val = C.NoColor, |
|
57 | 57 | em = C.NoColor, |
|
58 | 58 | |
|
59 | 59 | # Emphasized colors for the last frame of the traceback |
|
60 | 60 | normalEm = C.NoColor, |
|
61 | 61 | filenameEm = C.NoColor, |
|
62 | 62 | linenoEm = C.NoColor, |
|
63 | 63 | nameEm = C.NoColor, |
|
64 | 64 | valEm = C.NoColor, |
|
65 | 65 | |
|
66 | 66 | # Colors for printing the exception |
|
67 | 67 | excName = C.NoColor, |
|
68 | 68 | line = C.NoColor, |
|
69 | 69 | caret = C.NoColor, |
|
70 | 70 | Normal = C.NoColor |
|
71 | 71 | )) |
|
72 | 72 | |
|
73 | 73 | # make some schemes as instances so we can copy them for modification easily |
|
74 | 74 | ex_colors.add_scheme(ColorScheme( |
|
75 | 75 | 'Linux', |
|
76 | 76 | # The color to be used for the top line |
|
77 | 77 | topline = C.LightRed, |
|
78 | 78 | |
|
79 | 79 | # The colors to be used in the traceback |
|
80 | 80 | filename = C.Green, |
|
81 | 81 | lineno = C.Green, |
|
82 | 82 | name = C.Purple, |
|
83 | 83 | vName = C.Cyan, |
|
84 | 84 | val = C.Green, |
|
85 | 85 | em = C.LightCyan, |
|
86 | 86 | |
|
87 | 87 | # Emphasized colors for the last frame of the traceback |
|
88 | 88 | normalEm = C.LightCyan, |
|
89 | 89 | filenameEm = C.LightGreen, |
|
90 | 90 | linenoEm = C.LightGreen, |
|
91 | 91 | nameEm = C.LightPurple, |
|
92 | 92 | valEm = C.LightBlue, |
|
93 | 93 | |
|
94 | 94 | # Colors for printing the exception |
|
95 | 95 | excName = C.LightRed, |
|
96 | 96 | line = C.Yellow, |
|
97 | 97 | caret = C.White, |
|
98 | 98 | Normal = C.Normal |
|
99 | 99 | )) |
|
100 | 100 | |
|
101 | 101 | # For light backgrounds, swap dark/light colors |
|
102 | 102 | ex_colors.add_scheme(ColorScheme( |
|
103 | 103 | 'LightBG', |
|
104 | 104 | # The color to be used for the top line |
|
105 | 105 | topline = C.Red, |
|
106 | 106 | |
|
107 | 107 | # The colors to be used in the traceback |
|
108 | 108 | filename = C.LightGreen, |
|
109 | 109 | lineno = C.LightGreen, |
|
110 | 110 | name = C.LightPurple, |
|
111 | 111 | vName = C.Cyan, |
|
112 | 112 | val = C.LightGreen, |
|
113 | 113 | em = C.Cyan, |
|
114 | 114 | |
|
115 | 115 | # Emphasized colors for the last frame of the traceback |
|
116 | 116 | normalEm = C.Cyan, |
|
117 | 117 | filenameEm = C.Green, |
|
118 | 118 | linenoEm = C.Green, |
|
119 | 119 | nameEm = C.Purple, |
|
120 | 120 | valEm = C.Blue, |
|
121 | 121 | |
|
122 | 122 | # Colors for printing the exception |
|
123 | 123 | excName = C.Red, |
|
124 | 124 | #line = C.Brown, # brown often is displayed as yellow |
|
125 | 125 | line = C.Red, |
|
126 | 126 | caret = C.Normal, |
|
127 | 127 | Normal = C.Normal, |
|
128 | 128 | )) |
|
129 | 129 | |
|
130 | 130 | return ex_colors |
|
131 | 131 | |
|
132 | 132 | class Deprec(object): |
|
133 | 133 | |
|
134 | 134 | def __init__(self, wrapped_obj): |
|
135 | 135 | self.wrapped=wrapped_obj |
|
136 | 136 | |
|
137 | 137 | def __getattr__(self, name): |
|
138 | 138 | val = getattr(self.wrapped, name) |
|
139 | warnings.warn("Using ExceptionColors global is deprecated", DeprecationWarning) | |
|
139 | warnings.warn("Using ExceptionColors global is deprecated and will be removed in IPython 6.0", DeprecationWarning) | |
|
140 | 140 | # using getattr after warnings break ipydoctest in weird way for 3.5 |
|
141 | 141 | return val |
|
142 | 142 | |
|
143 | 143 | # For backwards compatibility, keep around a single global object. Note that |
|
144 | 144 | # this should NOT be used, the factory function should be used instead, since |
|
145 | 145 | # these objects are stateful and it's very easy to get strange bugs if any code |
|
146 | 146 | # modifies the module-level object's state. |
|
147 | 147 | ExceptionColors = Deprec(exception_colors()) |
@@ -1,972 +1,974 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Display formatters. |
|
3 | 3 | |
|
4 | 4 | Inheritance diagram: |
|
5 | 5 | |
|
6 | 6 | .. inheritance-diagram:: IPython.core.formatters |
|
7 | 7 | :parts: 3 |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | # Copyright (c) IPython Development Team. |
|
11 | 11 | # Distributed under the terms of the Modified BSD License. |
|
12 | 12 | |
|
13 | 13 | import abc |
|
14 | 14 | import inspect |
|
15 | 15 | import json |
|
16 | 16 | import sys |
|
17 | 17 | import traceback |
|
18 | 18 | import warnings |
|
19 | 19 | |
|
20 | 20 | from decorator import decorator |
|
21 | 21 | |
|
22 | 22 | from traitlets.config.configurable import Configurable |
|
23 | 23 | from IPython.core.getipython import get_ipython |
|
24 | 24 | from IPython.utils.sentinel import Sentinel |
|
25 | 25 | from IPython.lib import pretty |
|
26 | 26 | from traitlets import ( |
|
27 | 27 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, |
|
28 | 28 | ForwardDeclaredInstance, |
|
29 | 29 | ) |
|
30 | 30 | from IPython.utils.py3compat import ( |
|
31 | 31 | with_metaclass, string_types, unicode_type, |
|
32 | 32 | ) |
|
33 | 33 | |
|
34 | 34 | |
|
35 | 35 | #----------------------------------------------------------------------------- |
|
36 | 36 | # The main DisplayFormatter class |
|
37 | 37 | #----------------------------------------------------------------------------- |
|
38 | 38 | |
|
39 | 39 | |
|
40 | 40 | def _safe_get_formatter_method(obj, name): |
|
41 | 41 | """Safely get a formatter method |
|
42 | 42 | |
|
43 | 43 | - Classes cannot have formatter methods, only instance |
|
44 | 44 | - protect against proxy objects that claim to have everything |
|
45 | 45 | """ |
|
46 | 46 | if inspect.isclass(obj): |
|
47 | 47 | # repr methods only make sense on instances, not classes |
|
48 | 48 | return None |
|
49 | 49 | method = pretty._safe_getattr(obj, name, None) |
|
50 | 50 | if callable(method): |
|
51 | 51 | # obj claims to have repr method... |
|
52 | 52 | if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)): |
|
53 | 53 | # ...but don't trust proxy objects that claim to have everything |
|
54 | 54 | return None |
|
55 | 55 | return method |
|
56 | 56 | |
|
57 | 57 | |
|
58 | 58 | class DisplayFormatter(Configurable): |
|
59 | 59 | |
|
60 | 60 | # When set to true only the default plain text formatter will be used. |
|
61 | 61 | plain_text_only = Bool(False, config=True) |
|
62 | 62 | def _plain_text_only_changed(self, name, old, new): |
|
63 | 63 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. |
|
64 | 64 | |
|
65 | It will be removed in IPython 5.0 | |
|
66 | ||
|
65 | 67 | Use DisplayFormatter.active_types = ['text/plain'] |
|
66 | 68 | for the same effect. |
|
67 | 69 | """, DeprecationWarning) |
|
68 | 70 | if new: |
|
69 | 71 | self.active_types = ['text/plain'] |
|
70 | 72 | else: |
|
71 | 73 | self.active_types = self.format_types |
|
72 | 74 | |
|
73 | 75 | active_types = List(Unicode(), config=True, |
|
74 | 76 | help="""List of currently active mime-types to display. |
|
75 | 77 | You can use this to set a white-list for formats to display. |
|
76 | 78 | |
|
77 | 79 | Most users will not need to change this value. |
|
78 | 80 | """) |
|
79 | 81 | def _active_types_default(self): |
|
80 | 82 | return self.format_types |
|
81 | 83 | |
|
82 | 84 | def _active_types_changed(self, name, old, new): |
|
83 | 85 | for key, formatter in self.formatters.items(): |
|
84 | 86 | if key in new: |
|
85 | 87 | formatter.enabled = True |
|
86 | 88 | else: |
|
87 | 89 | formatter.enabled = False |
|
88 | 90 | |
|
89 | 91 | ipython_display_formatter = ForwardDeclaredInstance('FormatterABC') |
|
90 | 92 | def _ipython_display_formatter_default(self): |
|
91 | 93 | return IPythonDisplayFormatter(parent=self) |
|
92 | 94 | |
|
93 | 95 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
94 | 96 | # values are subclasses of BaseFormatter. |
|
95 | 97 | formatters = Dict() |
|
96 | 98 | def _formatters_default(self): |
|
97 | 99 | """Activate the default formatters.""" |
|
98 | 100 | formatter_classes = [ |
|
99 | 101 | PlainTextFormatter, |
|
100 | 102 | HTMLFormatter, |
|
101 | 103 | MarkdownFormatter, |
|
102 | 104 | SVGFormatter, |
|
103 | 105 | PNGFormatter, |
|
104 | 106 | PDFFormatter, |
|
105 | 107 | JPEGFormatter, |
|
106 | 108 | LatexFormatter, |
|
107 | 109 | JSONFormatter, |
|
108 | 110 | JavascriptFormatter |
|
109 | 111 | ] |
|
110 | 112 | d = {} |
|
111 | 113 | for cls in formatter_classes: |
|
112 | 114 | f = cls(parent=self) |
|
113 | 115 | d[f.format_type] = f |
|
114 | 116 | return d |
|
115 | 117 | |
|
116 | 118 | def format(self, obj, include=None, exclude=None): |
|
117 | 119 | """Return a format data dict for an object. |
|
118 | 120 | |
|
119 | 121 | By default all format types will be computed. |
|
120 | 122 | |
|
121 | 123 | The following MIME types are currently implemented: |
|
122 | 124 | |
|
123 | 125 | * text/plain |
|
124 | 126 | * text/html |
|
125 | 127 | * text/markdown |
|
126 | 128 | * text/latex |
|
127 | 129 | * application/json |
|
128 | 130 | * application/javascript |
|
129 | 131 | * application/pdf |
|
130 | 132 | * image/png |
|
131 | 133 | * image/jpeg |
|
132 | 134 | * image/svg+xml |
|
133 | 135 | |
|
134 | 136 | Parameters |
|
135 | 137 | ---------- |
|
136 | 138 | obj : object |
|
137 | 139 | The Python object whose format data will be computed. |
|
138 | 140 | include : list or tuple, optional |
|
139 | 141 | A list of format type strings (MIME types) to include in the |
|
140 | 142 | format data dict. If this is set *only* the format types included |
|
141 | 143 | in this list will be computed. |
|
142 | 144 | exclude : list or tuple, optional |
|
143 | 145 | A list of format type string (MIME types) to exclude in the format |
|
144 | 146 | data dict. If this is set all format types will be computed, |
|
145 | 147 | except for those included in this argument. |
|
146 | 148 | |
|
147 | 149 | Returns |
|
148 | 150 | ------- |
|
149 | 151 | (format_dict, metadata_dict) : tuple of two dicts |
|
150 | 152 | |
|
151 | 153 | format_dict is a dictionary of key/value pairs, one of each format that was |
|
152 | 154 | generated for the object. The keys are the format types, which |
|
153 | 155 | will usually be MIME type strings and the values and JSON'able |
|
154 | 156 | data structure containing the raw data for the representation in |
|
155 | 157 | that format. |
|
156 | 158 | |
|
157 | 159 | metadata_dict is a dictionary of metadata about each mime-type output. |
|
158 | 160 | Its keys will be a strict subset of the keys in format_dict. |
|
159 | 161 | """ |
|
160 | 162 | format_dict = {} |
|
161 | 163 | md_dict = {} |
|
162 | 164 | |
|
163 | 165 | if self.ipython_display_formatter(obj): |
|
164 | 166 | # object handled itself, don't proceed |
|
165 | 167 | return {}, {} |
|
166 | 168 | |
|
167 | 169 | for format_type, formatter in self.formatters.items(): |
|
168 | 170 | if include and format_type not in include: |
|
169 | 171 | continue |
|
170 | 172 | if exclude and format_type in exclude: |
|
171 | 173 | continue |
|
172 | 174 | |
|
173 | 175 | md = None |
|
174 | 176 | try: |
|
175 | 177 | data = formatter(obj) |
|
176 | 178 | except: |
|
177 | 179 | # FIXME: log the exception |
|
178 | 180 | raise |
|
179 | 181 | |
|
180 | 182 | # formatters can return raw data or (data, metadata) |
|
181 | 183 | if isinstance(data, tuple) and len(data) == 2: |
|
182 | 184 | data, md = data |
|
183 | 185 | |
|
184 | 186 | if data is not None: |
|
185 | 187 | format_dict[format_type] = data |
|
186 | 188 | if md is not None: |
|
187 | 189 | md_dict[format_type] = md |
|
188 | 190 | |
|
189 | 191 | return format_dict, md_dict |
|
190 | 192 | |
|
191 | 193 | @property |
|
192 | 194 | def format_types(self): |
|
193 | 195 | """Return the format types (MIME types) of the active formatters.""" |
|
194 | 196 | return list(self.formatters.keys()) |
|
195 | 197 | |
|
196 | 198 | |
|
197 | 199 | #----------------------------------------------------------------------------- |
|
198 | 200 | # Formatters for specific format types (text, html, svg, etc.) |
|
199 | 201 | #----------------------------------------------------------------------------- |
|
200 | 202 | |
|
201 | 203 | |
|
202 | 204 | def _safe_repr(obj): |
|
203 | 205 | """Try to return a repr of an object |
|
204 | 206 | |
|
205 | 207 | always returns a string, at least. |
|
206 | 208 | """ |
|
207 | 209 | try: |
|
208 | 210 | return repr(obj) |
|
209 | 211 | except Exception as e: |
|
210 | 212 | return "un-repr-able object (%r)" % e |
|
211 | 213 | |
|
212 | 214 | |
|
213 | 215 | class FormatterWarning(UserWarning): |
|
214 | 216 | """Warning class for errors in formatters""" |
|
215 | 217 | |
|
216 | 218 | @decorator |
|
217 | 219 | def catch_format_error(method, self, *args, **kwargs): |
|
218 | 220 | """show traceback on failed format call""" |
|
219 | 221 | try: |
|
220 | 222 | r = method(self, *args, **kwargs) |
|
221 | 223 | except NotImplementedError: |
|
222 | 224 | # don't warn on NotImplementedErrors |
|
223 | 225 | return None |
|
224 | 226 | except Exception: |
|
225 | 227 | exc_info = sys.exc_info() |
|
226 | 228 | ip = get_ipython() |
|
227 | 229 | if ip is not None: |
|
228 | 230 | ip.showtraceback(exc_info) |
|
229 | 231 | else: |
|
230 | 232 | traceback.print_exception(*exc_info) |
|
231 | 233 | return None |
|
232 | 234 | return self._check_return(r, args[0]) |
|
233 | 235 | |
|
234 | 236 | |
|
235 | 237 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): |
|
236 | 238 | """ Abstract base class for Formatters. |
|
237 | 239 | |
|
238 | 240 | A formatter is a callable class that is responsible for computing the |
|
239 | 241 | raw format data for a particular format type (MIME type). For example, |
|
240 | 242 | an HTML formatter would have a format type of `text/html` and would return |
|
241 | 243 | the HTML representation of the object when called. |
|
242 | 244 | """ |
|
243 | 245 | |
|
244 | 246 | # The format type of the data returned, usually a MIME type. |
|
245 | 247 | format_type = 'text/plain' |
|
246 | 248 | |
|
247 | 249 | # Is the formatter enabled... |
|
248 | 250 | enabled = True |
|
249 | 251 | |
|
250 | 252 | @abc.abstractmethod |
|
251 | 253 | def __call__(self, obj): |
|
252 | 254 | """Return a JSON'able representation of the object. |
|
253 | 255 | |
|
254 | 256 | If the object cannot be formatted by this formatter, |
|
255 | 257 | warn and return None. |
|
256 | 258 | """ |
|
257 | 259 | return repr(obj) |
|
258 | 260 | |
|
259 | 261 | |
|
260 | 262 | def _mod_name_key(typ): |
|
261 | 263 | """Return a (__module__, __name__) tuple for a type. |
|
262 | 264 | |
|
263 | 265 | Used as key in Formatter.deferred_printers. |
|
264 | 266 | """ |
|
265 | 267 | module = getattr(typ, '__module__', None) |
|
266 | 268 | name = getattr(typ, '__name__', None) |
|
267 | 269 | return (module, name) |
|
268 | 270 | |
|
269 | 271 | |
|
270 | 272 | def _get_type(obj): |
|
271 | 273 | """Return the type of an instance (old and new-style)""" |
|
272 | 274 | return getattr(obj, '__class__', None) or type(obj) |
|
273 | 275 | |
|
274 | 276 | |
|
275 | 277 | _raise_key_error = Sentinel('_raise_key_error', __name__, |
|
276 | 278 | """ |
|
277 | 279 | Special value to raise a KeyError |
|
278 | 280 | |
|
279 | 281 | Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop` |
|
280 | 282 | """) |
|
281 | 283 | |
|
282 | 284 | |
|
283 | 285 | class BaseFormatter(Configurable): |
|
284 | 286 | """A base formatter class that is configurable. |
|
285 | 287 | |
|
286 | 288 | This formatter should usually be used as the base class of all formatters. |
|
287 | 289 | It is a traited :class:`Configurable` class and includes an extensible |
|
288 | 290 | API for users to determine how their objects are formatted. The following |
|
289 | 291 | logic is used to find a function to format an given object. |
|
290 | 292 | |
|
291 | 293 | 1. The object is introspected to see if it has a method with the name |
|
292 | 294 | :attr:`print_method`. If is does, that object is passed to that method |
|
293 | 295 | for formatting. |
|
294 | 296 | 2. If no print method is found, three internal dictionaries are consulted |
|
295 | 297 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
296 | 298 | and :attr:`deferred_printers`. |
|
297 | 299 | |
|
298 | 300 | Users should use these dictionaries to register functions that will be |
|
299 | 301 | used to compute the format data for their objects (if those objects don't |
|
300 | 302 | have the special print methods). The easiest way of using these |
|
301 | 303 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
302 | 304 | methods. |
|
303 | 305 | |
|
304 | 306 | If no function/callable is found to compute the format data, ``None`` is |
|
305 | 307 | returned and this format type is not used. |
|
306 | 308 | """ |
|
307 | 309 | |
|
308 | 310 | format_type = Unicode('text/plain') |
|
309 | 311 | _return_type = string_types |
|
310 | 312 | |
|
311 | 313 | enabled = Bool(True, config=True) |
|
312 | 314 | |
|
313 | 315 | print_method = ObjectName('__repr__') |
|
314 | 316 | |
|
315 | 317 | # The singleton printers. |
|
316 | 318 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
317 | 319 | singleton_printers = Dict(config=True) |
|
318 | 320 | |
|
319 | 321 | # The type-specific printers. |
|
320 | 322 | # Map type objects to the format functions. |
|
321 | 323 | type_printers = Dict(config=True) |
|
322 | 324 | |
|
323 | 325 | # The deferred-import type-specific printers. |
|
324 | 326 | # Map (modulename, classname) pairs to the format functions. |
|
325 | 327 | deferred_printers = Dict(config=True) |
|
326 | 328 | |
|
327 | 329 | @catch_format_error |
|
328 | 330 | def __call__(self, obj): |
|
329 | 331 | """Compute the format for an object.""" |
|
330 | 332 | if self.enabled: |
|
331 | 333 | # lookup registered printer |
|
332 | 334 | try: |
|
333 | 335 | printer = self.lookup(obj) |
|
334 | 336 | except KeyError: |
|
335 | 337 | pass |
|
336 | 338 | else: |
|
337 | 339 | return printer(obj) |
|
338 | 340 | # Finally look for special method names |
|
339 | 341 | method = _safe_get_formatter_method(obj, self.print_method) |
|
340 | 342 | if method is not None: |
|
341 | 343 | return method() |
|
342 | 344 | return None |
|
343 | 345 | else: |
|
344 | 346 | return None |
|
345 | 347 | |
|
346 | 348 | def __contains__(self, typ): |
|
347 | 349 | """map in to lookup_by_type""" |
|
348 | 350 | try: |
|
349 | 351 | self.lookup_by_type(typ) |
|
350 | 352 | except KeyError: |
|
351 | 353 | return False |
|
352 | 354 | else: |
|
353 | 355 | return True |
|
354 | 356 | |
|
355 | 357 | def _check_return(self, r, obj): |
|
356 | 358 | """Check that a return value is appropriate |
|
357 | 359 | |
|
358 | 360 | Return the value if so, None otherwise, warning if invalid. |
|
359 | 361 | """ |
|
360 | 362 | if r is None or isinstance(r, self._return_type) or \ |
|
361 | 363 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): |
|
362 | 364 | return r |
|
363 | 365 | else: |
|
364 | 366 | warnings.warn( |
|
365 | 367 | "%s formatter returned invalid type %s (expected %s) for object: %s" % \ |
|
366 | 368 | (self.format_type, type(r), self._return_type, _safe_repr(obj)), |
|
367 | 369 | FormatterWarning |
|
368 | 370 | ) |
|
369 | 371 | |
|
370 | 372 | def lookup(self, obj): |
|
371 | 373 | """Look up the formatter for a given instance. |
|
372 | 374 | |
|
373 | 375 | Parameters |
|
374 | 376 | ---------- |
|
375 | 377 | obj : object instance |
|
376 | 378 | |
|
377 | 379 | Returns |
|
378 | 380 | ------- |
|
379 | 381 | f : callable |
|
380 | 382 | The registered formatting callable for the type. |
|
381 | 383 | |
|
382 | 384 | Raises |
|
383 | 385 | ------ |
|
384 | 386 | KeyError if the type has not been registered. |
|
385 | 387 | """ |
|
386 | 388 | # look for singleton first |
|
387 | 389 | obj_id = id(obj) |
|
388 | 390 | if obj_id in self.singleton_printers: |
|
389 | 391 | return self.singleton_printers[obj_id] |
|
390 | 392 | # then lookup by type |
|
391 | 393 | return self.lookup_by_type(_get_type(obj)) |
|
392 | 394 | |
|
393 | 395 | def lookup_by_type(self, typ): |
|
394 | 396 | """Look up the registered formatter for a type. |
|
395 | 397 | |
|
396 | 398 | Parameters |
|
397 | 399 | ---------- |
|
398 | 400 | typ : type or '__module__.__name__' string for a type |
|
399 | 401 | |
|
400 | 402 | Returns |
|
401 | 403 | ------- |
|
402 | 404 | f : callable |
|
403 | 405 | The registered formatting callable for the type. |
|
404 | 406 | |
|
405 | 407 | Raises |
|
406 | 408 | ------ |
|
407 | 409 | KeyError if the type has not been registered. |
|
408 | 410 | """ |
|
409 | 411 | if isinstance(typ, string_types): |
|
410 | 412 | typ_key = tuple(typ.rsplit('.',1)) |
|
411 | 413 | if typ_key not in self.deferred_printers: |
|
412 | 414 | # We may have it cached in the type map. We will have to |
|
413 | 415 | # iterate over all of the types to check. |
|
414 | 416 | for cls in self.type_printers: |
|
415 | 417 | if _mod_name_key(cls) == typ_key: |
|
416 | 418 | return self.type_printers[cls] |
|
417 | 419 | else: |
|
418 | 420 | return self.deferred_printers[typ_key] |
|
419 | 421 | else: |
|
420 | 422 | for cls in pretty._get_mro(typ): |
|
421 | 423 | if cls in self.type_printers or self._in_deferred_types(cls): |
|
422 | 424 | return self.type_printers[cls] |
|
423 | 425 | |
|
424 | 426 | # If we have reached here, the lookup failed. |
|
425 | 427 | raise KeyError("No registered printer for {0!r}".format(typ)) |
|
426 | 428 | |
|
427 | 429 | def for_type(self, typ, func=None): |
|
428 | 430 | """Add a format function for a given type. |
|
429 | 431 | |
|
430 | 432 | Parameters |
|
431 | 433 | ----------- |
|
432 | 434 | typ : type or '__module__.__name__' string for a type |
|
433 | 435 | The class of the object that will be formatted using `func`. |
|
434 | 436 | func : callable |
|
435 | 437 | A callable for computing the format data. |
|
436 | 438 | `func` will be called with the object to be formatted, |
|
437 | 439 | and will return the raw data in this formatter's format. |
|
438 | 440 | Subclasses may use a different call signature for the |
|
439 | 441 | `func` argument. |
|
440 | 442 | |
|
441 | 443 | If `func` is None or not specified, there will be no change, |
|
442 | 444 | only returning the current value. |
|
443 | 445 | |
|
444 | 446 | Returns |
|
445 | 447 | ------- |
|
446 | 448 | oldfunc : callable |
|
447 | 449 | The currently registered callable. |
|
448 | 450 | If you are registering a new formatter, |
|
449 | 451 | this will be the previous value (to enable restoring later). |
|
450 | 452 | """ |
|
451 | 453 | # if string given, interpret as 'pkg.module.class_name' |
|
452 | 454 | if isinstance(typ, string_types): |
|
453 | 455 | type_module, type_name = typ.rsplit('.', 1) |
|
454 | 456 | return self.for_type_by_name(type_module, type_name, func) |
|
455 | 457 | |
|
456 | 458 | try: |
|
457 | 459 | oldfunc = self.lookup_by_type(typ) |
|
458 | 460 | except KeyError: |
|
459 | 461 | oldfunc = None |
|
460 | 462 | |
|
461 | 463 | if func is not None: |
|
462 | 464 | self.type_printers[typ] = func |
|
463 | 465 | |
|
464 | 466 | return oldfunc |
|
465 | 467 | |
|
466 | 468 | def for_type_by_name(self, type_module, type_name, func=None): |
|
467 | 469 | """Add a format function for a type specified by the full dotted |
|
468 | 470 | module and name of the type, rather than the type of the object. |
|
469 | 471 | |
|
470 | 472 | Parameters |
|
471 | 473 | ---------- |
|
472 | 474 | type_module : str |
|
473 | 475 | The full dotted name of the module the type is defined in, like |
|
474 | 476 | ``numpy``. |
|
475 | 477 | type_name : str |
|
476 | 478 | The name of the type (the class name), like ``dtype`` |
|
477 | 479 | func : callable |
|
478 | 480 | A callable for computing the format data. |
|
479 | 481 | `func` will be called with the object to be formatted, |
|
480 | 482 | and will return the raw data in this formatter's format. |
|
481 | 483 | Subclasses may use a different call signature for the |
|
482 | 484 | `func` argument. |
|
483 | 485 | |
|
484 | 486 | If `func` is None or unspecified, there will be no change, |
|
485 | 487 | only returning the current value. |
|
486 | 488 | |
|
487 | 489 | Returns |
|
488 | 490 | ------- |
|
489 | 491 | oldfunc : callable |
|
490 | 492 | The currently registered callable. |
|
491 | 493 | If you are registering a new formatter, |
|
492 | 494 | this will be the previous value (to enable restoring later). |
|
493 | 495 | """ |
|
494 | 496 | key = (type_module, type_name) |
|
495 | 497 | |
|
496 | 498 | try: |
|
497 | 499 | oldfunc = self.lookup_by_type("%s.%s" % key) |
|
498 | 500 | except KeyError: |
|
499 | 501 | oldfunc = None |
|
500 | 502 | |
|
501 | 503 | if func is not None: |
|
502 | 504 | self.deferred_printers[key] = func |
|
503 | 505 | return oldfunc |
|
504 | 506 | |
|
505 | 507 | def pop(self, typ, default=_raise_key_error): |
|
506 | 508 | """Pop a formatter for the given type. |
|
507 | 509 | |
|
508 | 510 | Parameters |
|
509 | 511 | ---------- |
|
510 | 512 | typ : type or '__module__.__name__' string for a type |
|
511 | 513 | default : object |
|
512 | 514 | value to be returned if no formatter is registered for typ. |
|
513 | 515 | |
|
514 | 516 | Returns |
|
515 | 517 | ------- |
|
516 | 518 | obj : object |
|
517 | 519 | The last registered object for the type. |
|
518 | 520 | |
|
519 | 521 | Raises |
|
520 | 522 | ------ |
|
521 | 523 | KeyError if the type is not registered and default is not specified. |
|
522 | 524 | """ |
|
523 | 525 | |
|
524 | 526 | if isinstance(typ, string_types): |
|
525 | 527 | typ_key = tuple(typ.rsplit('.',1)) |
|
526 | 528 | if typ_key not in self.deferred_printers: |
|
527 | 529 | # We may have it cached in the type map. We will have to |
|
528 | 530 | # iterate over all of the types to check. |
|
529 | 531 | for cls in self.type_printers: |
|
530 | 532 | if _mod_name_key(cls) == typ_key: |
|
531 | 533 | old = self.type_printers.pop(cls) |
|
532 | 534 | break |
|
533 | 535 | else: |
|
534 | 536 | old = default |
|
535 | 537 | else: |
|
536 | 538 | old = self.deferred_printers.pop(typ_key) |
|
537 | 539 | else: |
|
538 | 540 | if typ in self.type_printers: |
|
539 | 541 | old = self.type_printers.pop(typ) |
|
540 | 542 | else: |
|
541 | 543 | old = self.deferred_printers.pop(_mod_name_key(typ), default) |
|
542 | 544 | if old is _raise_key_error: |
|
543 | 545 | raise KeyError("No registered value for {0!r}".format(typ)) |
|
544 | 546 | return old |
|
545 | 547 | |
|
546 | 548 | def _in_deferred_types(self, cls): |
|
547 | 549 | """ |
|
548 | 550 | Check if the given class is specified in the deferred type registry. |
|
549 | 551 | |
|
550 | 552 | Successful matches will be moved to the regular type registry for future use. |
|
551 | 553 | """ |
|
552 | 554 | mod = getattr(cls, '__module__', None) |
|
553 | 555 | name = getattr(cls, '__name__', None) |
|
554 | 556 | key = (mod, name) |
|
555 | 557 | if key in self.deferred_printers: |
|
556 | 558 | # Move the printer over to the regular registry. |
|
557 | 559 | printer = self.deferred_printers.pop(key) |
|
558 | 560 | self.type_printers[cls] = printer |
|
559 | 561 | return True |
|
560 | 562 | return False |
|
561 | 563 | |
|
562 | 564 | |
|
563 | 565 | class PlainTextFormatter(BaseFormatter): |
|
564 | 566 | """The default pretty-printer. |
|
565 | 567 | |
|
566 | 568 | This uses :mod:`IPython.lib.pretty` to compute the format data of |
|
567 | 569 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
568 | 570 | See the documentation of :mod:`IPython.lib.pretty` for details on |
|
569 | 571 | how to write pretty printers. Here is a simple example:: |
|
570 | 572 | |
|
571 | 573 | def dtype_pprinter(obj, p, cycle): |
|
572 | 574 | if cycle: |
|
573 | 575 | return p.text('dtype(...)') |
|
574 | 576 | if hasattr(obj, 'fields'): |
|
575 | 577 | if obj.fields is None: |
|
576 | 578 | p.text(repr(obj)) |
|
577 | 579 | else: |
|
578 | 580 | p.begin_group(7, 'dtype([') |
|
579 | 581 | for i, field in enumerate(obj.descr): |
|
580 | 582 | if i > 0: |
|
581 | 583 | p.text(',') |
|
582 | 584 | p.breakable() |
|
583 | 585 | p.pretty(field) |
|
584 | 586 | p.end_group(7, '])') |
|
585 | 587 | """ |
|
586 | 588 | |
|
587 | 589 | # The format type of data returned. |
|
588 | 590 | format_type = Unicode('text/plain') |
|
589 | 591 | |
|
590 | 592 | # This subclass ignores this attribute as it always need to return |
|
591 | 593 | # something. |
|
592 | 594 | enabled = Bool(True, config=False) |
|
593 | 595 | |
|
594 | 596 | max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True, |
|
595 | 597 | help="""Truncate large collections (lists, dicts, tuples, sets) to this size. |
|
596 | 598 | |
|
597 | 599 | Set to 0 to disable truncation. |
|
598 | 600 | """ |
|
599 | 601 | ) |
|
600 | 602 | |
|
601 | 603 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
602 | 604 | print_method = ObjectName('_repr_pretty_') |
|
603 | 605 | |
|
604 | 606 | # Whether to pretty-print or not. |
|
605 | 607 | pprint = Bool(True, config=True) |
|
606 | 608 | |
|
607 | 609 | # Whether to be verbose or not. |
|
608 | 610 | verbose = Bool(False, config=True) |
|
609 | 611 | |
|
610 | 612 | # The maximum width. |
|
611 | 613 | max_width = Integer(79, config=True) |
|
612 | 614 | |
|
613 | 615 | # The newline character. |
|
614 | 616 | newline = Unicode('\n', config=True) |
|
615 | 617 | |
|
616 | 618 | # format-string for pprinting floats |
|
617 | 619 | float_format = Unicode('%r') |
|
618 | 620 | # setter for float precision, either int or direct format-string |
|
619 | 621 | float_precision = CUnicode('', config=True) |
|
620 | 622 | |
|
621 | 623 | def _float_precision_changed(self, name, old, new): |
|
622 | 624 | """float_precision changed, set float_format accordingly. |
|
623 | 625 | |
|
624 | 626 | float_precision can be set by int or str. |
|
625 | 627 | This will set float_format, after interpreting input. |
|
626 | 628 | If numpy has been imported, numpy print precision will also be set. |
|
627 | 629 | |
|
628 | 630 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
629 | 631 | |
|
630 | 632 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
631 | 633 | |
|
632 | 634 | This parameter can be set via the '%precision' magic. |
|
633 | 635 | """ |
|
634 | 636 | |
|
635 | 637 | if '%' in new: |
|
636 | 638 | # got explicit format string |
|
637 | 639 | fmt = new |
|
638 | 640 | try: |
|
639 | 641 | fmt%3.14159 |
|
640 | 642 | except Exception: |
|
641 | 643 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
642 | 644 | elif new: |
|
643 | 645 | # otherwise, should be an int |
|
644 | 646 | try: |
|
645 | 647 | i = int(new) |
|
646 | 648 | assert i >= 0 |
|
647 | 649 | except ValueError: |
|
648 | 650 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
649 | 651 | except AssertionError: |
|
650 | 652 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
651 | 653 | |
|
652 | 654 | fmt = '%%.%if'%i |
|
653 | 655 | if 'numpy' in sys.modules: |
|
654 | 656 | # set numpy precision if it has been imported |
|
655 | 657 | import numpy |
|
656 | 658 | numpy.set_printoptions(precision=i) |
|
657 | 659 | else: |
|
658 | 660 | # default back to repr |
|
659 | 661 | fmt = '%r' |
|
660 | 662 | if 'numpy' in sys.modules: |
|
661 | 663 | import numpy |
|
662 | 664 | # numpy default is 8 |
|
663 | 665 | numpy.set_printoptions(precision=8) |
|
664 | 666 | self.float_format = fmt |
|
665 | 667 | |
|
666 | 668 | # Use the default pretty printers from IPython.lib.pretty. |
|
667 | 669 | def _singleton_printers_default(self): |
|
668 | 670 | return pretty._singleton_pprinters.copy() |
|
669 | 671 | |
|
670 | 672 | def _type_printers_default(self): |
|
671 | 673 | d = pretty._type_pprinters.copy() |
|
672 | 674 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
673 | 675 | return d |
|
674 | 676 | |
|
675 | 677 | def _deferred_printers_default(self): |
|
676 | 678 | return pretty._deferred_type_pprinters.copy() |
|
677 | 679 | |
|
678 | 680 | #### FormatterABC interface #### |
|
679 | 681 | |
|
680 | 682 | @catch_format_error |
|
681 | 683 | def __call__(self, obj): |
|
682 | 684 | """Compute the pretty representation of the object.""" |
|
683 | 685 | if not self.pprint: |
|
684 | 686 | return repr(obj) |
|
685 | 687 | else: |
|
686 | 688 | # handle str and unicode on Python 2 |
|
687 | 689 | # io.StringIO only accepts unicode, |
|
688 | 690 | # cStringIO doesn't handle unicode on py2, |
|
689 | 691 | # StringIO allows str, unicode but only ascii str |
|
690 | 692 | stream = pretty.CUnicodeIO() |
|
691 | 693 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
692 | 694 | self.max_width, self.newline, |
|
693 | 695 | max_seq_length=self.max_seq_length, |
|
694 | 696 | singleton_pprinters=self.singleton_printers, |
|
695 | 697 | type_pprinters=self.type_printers, |
|
696 | 698 | deferred_pprinters=self.deferred_printers) |
|
697 | 699 | printer.pretty(obj) |
|
698 | 700 | printer.flush() |
|
699 | 701 | return stream.getvalue() |
|
700 | 702 | |
|
701 | 703 | |
|
702 | 704 | class HTMLFormatter(BaseFormatter): |
|
703 | 705 | """An HTML formatter. |
|
704 | 706 | |
|
705 | 707 | To define the callables that compute the HTML representation of your |
|
706 | 708 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
707 | 709 | or :meth:`for_type_by_name` methods to register functions that handle |
|
708 | 710 | this. |
|
709 | 711 | |
|
710 | 712 | The return value of this formatter should be a valid HTML snippet that |
|
711 | 713 | could be injected into an existing DOM. It should *not* include the |
|
712 | 714 | ```<html>`` or ```<body>`` tags. |
|
713 | 715 | """ |
|
714 | 716 | format_type = Unicode('text/html') |
|
715 | 717 | |
|
716 | 718 | print_method = ObjectName('_repr_html_') |
|
717 | 719 | |
|
718 | 720 | |
|
719 | 721 | class MarkdownFormatter(BaseFormatter): |
|
720 | 722 | """A Markdown formatter. |
|
721 | 723 | |
|
722 | 724 | To define the callables that compute the Markdown representation of your |
|
723 | 725 | objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type` |
|
724 | 726 | or :meth:`for_type_by_name` methods to register functions that handle |
|
725 | 727 | this. |
|
726 | 728 | |
|
727 | 729 | The return value of this formatter should be a valid Markdown. |
|
728 | 730 | """ |
|
729 | 731 | format_type = Unicode('text/markdown') |
|
730 | 732 | |
|
731 | 733 | print_method = ObjectName('_repr_markdown_') |
|
732 | 734 | |
|
733 | 735 | class SVGFormatter(BaseFormatter): |
|
734 | 736 | """An SVG formatter. |
|
735 | 737 | |
|
736 | 738 | To define the callables that compute the SVG representation of your |
|
737 | 739 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
738 | 740 | or :meth:`for_type_by_name` methods to register functions that handle |
|
739 | 741 | this. |
|
740 | 742 | |
|
741 | 743 | The return value of this formatter should be valid SVG enclosed in |
|
742 | 744 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
743 | 745 | *not* include the ```<html>`` or ```<body>`` tags. |
|
744 | 746 | """ |
|
745 | 747 | format_type = Unicode('image/svg+xml') |
|
746 | 748 | |
|
747 | 749 | print_method = ObjectName('_repr_svg_') |
|
748 | 750 | |
|
749 | 751 | |
|
750 | 752 | class PNGFormatter(BaseFormatter): |
|
751 | 753 | """A PNG formatter. |
|
752 | 754 | |
|
753 | 755 | To define the callables that compute the PNG representation of your |
|
754 | 756 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
755 | 757 | or :meth:`for_type_by_name` methods to register functions that handle |
|
756 | 758 | this. |
|
757 | 759 | |
|
758 | 760 | The return value of this formatter should be raw PNG data, *not* |
|
759 | 761 | base64 encoded. |
|
760 | 762 | """ |
|
761 | 763 | format_type = Unicode('image/png') |
|
762 | 764 | |
|
763 | 765 | print_method = ObjectName('_repr_png_') |
|
764 | 766 | |
|
765 | 767 | _return_type = (bytes, unicode_type) |
|
766 | 768 | |
|
767 | 769 | |
|
768 | 770 | class JPEGFormatter(BaseFormatter): |
|
769 | 771 | """A JPEG formatter. |
|
770 | 772 | |
|
771 | 773 | To define the callables that compute the JPEG representation of your |
|
772 | 774 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` |
|
773 | 775 | or :meth:`for_type_by_name` methods to register functions that handle |
|
774 | 776 | this. |
|
775 | 777 | |
|
776 | 778 | The return value of this formatter should be raw JPEG data, *not* |
|
777 | 779 | base64 encoded. |
|
778 | 780 | """ |
|
779 | 781 | format_type = Unicode('image/jpeg') |
|
780 | 782 | |
|
781 | 783 | print_method = ObjectName('_repr_jpeg_') |
|
782 | 784 | |
|
783 | 785 | _return_type = (bytes, unicode_type) |
|
784 | 786 | |
|
785 | 787 | |
|
786 | 788 | class LatexFormatter(BaseFormatter): |
|
787 | 789 | """A LaTeX formatter. |
|
788 | 790 | |
|
789 | 791 | To define the callables that compute the LaTeX representation of your |
|
790 | 792 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
791 | 793 | or :meth:`for_type_by_name` methods to register functions that handle |
|
792 | 794 | this. |
|
793 | 795 | |
|
794 | 796 | The return value of this formatter should be a valid LaTeX equation, |
|
795 | 797 | enclosed in either ```$```, ```$$``` or another LaTeX equation |
|
796 | 798 | environment. |
|
797 | 799 | """ |
|
798 | 800 | format_type = Unicode('text/latex') |
|
799 | 801 | |
|
800 | 802 | print_method = ObjectName('_repr_latex_') |
|
801 | 803 | |
|
802 | 804 | |
|
803 | 805 | class JSONFormatter(BaseFormatter): |
|
804 | 806 | """A JSON string formatter. |
|
805 | 807 | |
|
806 | 808 | To define the callables that compute the JSONable representation of |
|
807 | 809 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
808 | 810 | or :meth:`for_type_by_name` methods to register functions that handle |
|
809 | 811 | this. |
|
810 | 812 | |
|
811 | 813 | The return value of this formatter should be a JSONable list or dict. |
|
812 | 814 | JSON scalars (None, number, string) are not allowed, only dict or list containers. |
|
813 | 815 | """ |
|
814 | 816 | format_type = Unicode('application/json') |
|
815 | 817 | _return_type = (list, dict) |
|
816 | 818 | |
|
817 | 819 | print_method = ObjectName('_repr_json_') |
|
818 | 820 | |
|
819 | 821 | def _check_return(self, r, obj): |
|
820 | 822 | """Check that a return value is appropriate |
|
821 | 823 | |
|
822 | 824 | Return the value if so, None otherwise, warning if invalid. |
|
823 | 825 | """ |
|
824 | 826 | if r is None: |
|
825 | 827 | return |
|
826 | 828 | md = None |
|
827 | 829 | if isinstance(r, tuple): |
|
828 | 830 | # unpack data, metadata tuple for type checking on first element |
|
829 | 831 | r, md = r |
|
830 | 832 | |
|
831 | 833 | # handle deprecated JSON-as-string form from IPython < 3 |
|
832 | 834 | if isinstance(r, string_types): |
|
833 | 835 | warnings.warn("JSON expects JSONable list/dict containers, not JSON strings", |
|
834 | 836 | FormatterWarning) |
|
835 | 837 | r = json.loads(r) |
|
836 | 838 | |
|
837 | 839 | if md is not None: |
|
838 | 840 | # put the tuple back together |
|
839 | 841 | r = (r, md) |
|
840 | 842 | return super(JSONFormatter, self)._check_return(r, obj) |
|
841 | 843 | |
|
842 | 844 | |
|
843 | 845 | class JavascriptFormatter(BaseFormatter): |
|
844 | 846 | """A Javascript formatter. |
|
845 | 847 | |
|
846 | 848 | To define the callables that compute the Javascript representation of |
|
847 | 849 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
848 | 850 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
849 | 851 | that handle this. |
|
850 | 852 | |
|
851 | 853 | The return value of this formatter should be valid Javascript code and |
|
852 | 854 | should *not* be enclosed in ```<script>``` tags. |
|
853 | 855 | """ |
|
854 | 856 | format_type = Unicode('application/javascript') |
|
855 | 857 | |
|
856 | 858 | print_method = ObjectName('_repr_javascript_') |
|
857 | 859 | |
|
858 | 860 | |
|
859 | 861 | class PDFFormatter(BaseFormatter): |
|
860 | 862 | """A PDF formatter. |
|
861 | 863 | |
|
862 | 864 | To define the callables that compute the PDF representation of your |
|
863 | 865 | objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` |
|
864 | 866 | or :meth:`for_type_by_name` methods to register functions that handle |
|
865 | 867 | this. |
|
866 | 868 | |
|
867 | 869 | The return value of this formatter should be raw PDF data, *not* |
|
868 | 870 | base64 encoded. |
|
869 | 871 | """ |
|
870 | 872 | format_type = Unicode('application/pdf') |
|
871 | 873 | |
|
872 | 874 | print_method = ObjectName('_repr_pdf_') |
|
873 | 875 | |
|
874 | 876 | _return_type = (bytes, unicode_type) |
|
875 | 877 | |
|
876 | 878 | class IPythonDisplayFormatter(BaseFormatter): |
|
877 | 879 | """A Formatter for objects that know how to display themselves. |
|
878 | 880 | |
|
879 | 881 | To define the callables that compute the representation of your |
|
880 | 882 | objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` |
|
881 | 883 | or :meth:`for_type_by_name` methods to register functions that handle |
|
882 | 884 | this. Unlike mime-type displays, this method should not return anything, |
|
883 | 885 | instead calling any appropriate display methods itself. |
|
884 | 886 | |
|
885 | 887 | This display formatter has highest priority. |
|
886 | 888 | If it fires, no other display formatter will be called. |
|
887 | 889 | """ |
|
888 | 890 | print_method = ObjectName('_ipython_display_') |
|
889 | 891 | _return_type = (type(None), bool) |
|
890 | 892 | |
|
891 | 893 | |
|
892 | 894 | @catch_format_error |
|
893 | 895 | def __call__(self, obj): |
|
894 | 896 | """Compute the format for an object.""" |
|
895 | 897 | if self.enabled: |
|
896 | 898 | # lookup registered printer |
|
897 | 899 | try: |
|
898 | 900 | printer = self.lookup(obj) |
|
899 | 901 | except KeyError: |
|
900 | 902 | pass |
|
901 | 903 | else: |
|
902 | 904 | printer(obj) |
|
903 | 905 | return True |
|
904 | 906 | # Finally look for special method names |
|
905 | 907 | method = _safe_get_formatter_method(obj, self.print_method) |
|
906 | 908 | if method is not None: |
|
907 | 909 | method() |
|
908 | 910 | return True |
|
909 | 911 | |
|
910 | 912 | |
|
911 | 913 | FormatterABC.register(BaseFormatter) |
|
912 | 914 | FormatterABC.register(PlainTextFormatter) |
|
913 | 915 | FormatterABC.register(HTMLFormatter) |
|
914 | 916 | FormatterABC.register(MarkdownFormatter) |
|
915 | 917 | FormatterABC.register(SVGFormatter) |
|
916 | 918 | FormatterABC.register(PNGFormatter) |
|
917 | 919 | FormatterABC.register(PDFFormatter) |
|
918 | 920 | FormatterABC.register(JPEGFormatter) |
|
919 | 921 | FormatterABC.register(LatexFormatter) |
|
920 | 922 | FormatterABC.register(JSONFormatter) |
|
921 | 923 | FormatterABC.register(JavascriptFormatter) |
|
922 | 924 | FormatterABC.register(IPythonDisplayFormatter) |
|
923 | 925 | |
|
924 | 926 | |
|
925 | 927 | def format_display_data(obj, include=None, exclude=None): |
|
926 | 928 | """Return a format data dict for an object. |
|
927 | 929 | |
|
928 | 930 | By default all format types will be computed. |
|
929 | 931 | |
|
930 | 932 | The following MIME types are currently implemented: |
|
931 | 933 | |
|
932 | 934 | * text/plain |
|
933 | 935 | * text/html |
|
934 | 936 | * text/markdown |
|
935 | 937 | * text/latex |
|
936 | 938 | * application/json |
|
937 | 939 | * application/javascript |
|
938 | 940 | * application/pdf |
|
939 | 941 | * image/png |
|
940 | 942 | * image/jpeg |
|
941 | 943 | * image/svg+xml |
|
942 | 944 | |
|
943 | 945 | Parameters |
|
944 | 946 | ---------- |
|
945 | 947 | obj : object |
|
946 | 948 | The Python object whose format data will be computed. |
|
947 | 949 | |
|
948 | 950 | Returns |
|
949 | 951 | ------- |
|
950 | 952 | format_dict : dict |
|
951 | 953 | A dictionary of key/value pairs, one or each format that was |
|
952 | 954 | generated for the object. The keys are the format types, which |
|
953 | 955 | will usually be MIME type strings and the values and JSON'able |
|
954 | 956 | data structure containing the raw data for the representation in |
|
955 | 957 | that format. |
|
956 | 958 | include : list or tuple, optional |
|
957 | 959 | A list of format type strings (MIME types) to include in the |
|
958 | 960 | format data dict. If this is set *only* the format types included |
|
959 | 961 | in this list will be computed. |
|
960 | 962 | exclude : list or tuple, optional |
|
961 | 963 | A list of format type string (MIME types) to exclue in the format |
|
962 | 964 | data dict. If this is set all format types will be computed, |
|
963 | 965 | except for those included in this argument. |
|
964 | 966 | """ |
|
965 | 967 | from IPython.core.interactiveshell import InteractiveShell |
|
966 | 968 | |
|
967 | 969 | InteractiveShell.instance().display_formatter.format( |
|
968 | 970 | obj, |
|
969 | 971 | include, |
|
970 | 972 | exclude |
|
971 | 973 | ) |
|
972 | 974 |
@@ -1,3413 +1,3415 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Main IPython class.""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
6 | 6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
7 | 7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | from __future__ import absolute_import, print_function |
|
14 | 14 | |
|
15 | 15 | import __future__ |
|
16 | 16 | import abc |
|
17 | 17 | import ast |
|
18 | 18 | import atexit |
|
19 | 19 | import functools |
|
20 | 20 | import os |
|
21 | 21 | import re |
|
22 | 22 | import runpy |
|
23 | 23 | import sys |
|
24 | 24 | import tempfile |
|
25 | 25 | import traceback |
|
26 | 26 | import types |
|
27 | 27 | import subprocess |
|
28 | 28 | import warnings |
|
29 | 29 | from io import open as io_open |
|
30 | 30 | |
|
31 | 31 | from pickleshare import PickleShareDB |
|
32 | 32 | |
|
33 | 33 | from traitlets.config.configurable import SingletonConfigurable |
|
34 | 34 | from IPython.core import debugger, oinspect |
|
35 | 35 | from IPython.core import magic |
|
36 | 36 | from IPython.core import page |
|
37 | 37 | from IPython.core import prefilter |
|
38 | 38 | from IPython.core import shadowns |
|
39 | 39 | from IPython.core import ultratb |
|
40 | 40 | from IPython.core.alias import Alias, AliasManager |
|
41 | 41 | from IPython.core.autocall import ExitAutocall |
|
42 | 42 | from IPython.core.builtin_trap import BuiltinTrap |
|
43 | 43 | from IPython.core.events import EventManager, available_events |
|
44 | 44 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
45 | 45 | from IPython.core.display_trap import DisplayTrap |
|
46 | 46 | from IPython.core.displayhook import DisplayHook |
|
47 | 47 | from IPython.core.displaypub import DisplayPublisher |
|
48 | 48 | from IPython.core.error import InputRejected, UsageError |
|
49 | 49 | from IPython.core.extensions import ExtensionManager |
|
50 | 50 | from IPython.core.formatters import DisplayFormatter |
|
51 | 51 | from IPython.core.history import HistoryManager |
|
52 | 52 | from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2 |
|
53 | 53 | from IPython.core.logger import Logger |
|
54 | 54 | from IPython.core.macro import Macro |
|
55 | 55 | from IPython.core.payload import PayloadManager |
|
56 | 56 | from IPython.core.prefilter import PrefilterManager |
|
57 | 57 | from IPython.core.profiledir import ProfileDir |
|
58 | 58 | from IPython.core.prompts import PromptManager |
|
59 | 59 | from IPython.core.usage import default_banner |
|
60 | 60 | from IPython.testing.skipdoctest import skip_doctest |
|
61 | 61 | from IPython.utils import PyColorize |
|
62 | 62 | from IPython.utils import io |
|
63 | 63 | from IPython.utils import py3compat |
|
64 | 64 | from IPython.utils import openpy |
|
65 | 65 | from IPython.utils.decorators import undoc |
|
66 | 66 | from IPython.utils.io import ask_yes_no |
|
67 | 67 | from IPython.utils.ipstruct import Struct |
|
68 | 68 | from IPython.paths import get_ipython_dir |
|
69 | 69 | from IPython.utils.path import get_home_dir, get_py_filename, unquote_filename, ensure_dir_exists |
|
70 | 70 | from IPython.utils.process import system, getoutput |
|
71 | 71 | from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types, |
|
72 | 72 | with_metaclass, iteritems) |
|
73 | 73 | from IPython.utils.strdispatch import StrDispatch |
|
74 | 74 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
75 | 75 | from IPython.utils.text import (format_screen, LSString, SList, |
|
76 | 76 | DollarFormatter) |
|
77 | 77 | from traitlets import (Integer, Bool, CBool, CaselessStrEnum, Enum, |
|
78 | 78 | List, Dict, Unicode, Instance, Type) |
|
79 | 79 | from IPython.utils.warn import warn, error |
|
80 | 80 | import IPython.core.hooks |
|
81 | 81 | |
|
82 | 82 | #----------------------------------------------------------------------------- |
|
83 | 83 | # Globals |
|
84 | 84 | #----------------------------------------------------------------------------- |
|
85 | 85 | |
|
86 | 86 | # compiled regexps for autoindent management |
|
87 | 87 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
88 | 88 | |
|
89 | 89 | #----------------------------------------------------------------------------- |
|
90 | 90 | # Utilities |
|
91 | 91 | #----------------------------------------------------------------------------- |
|
92 | 92 | |
|
93 | 93 | @undoc |
|
94 | 94 | def softspace(file, newvalue): |
|
95 | 95 | """Copied from code.py, to remove the dependency""" |
|
96 | 96 | |
|
97 | 97 | oldvalue = 0 |
|
98 | 98 | try: |
|
99 | 99 | oldvalue = file.softspace |
|
100 | 100 | except AttributeError: |
|
101 | 101 | pass |
|
102 | 102 | try: |
|
103 | 103 | file.softspace = newvalue |
|
104 | 104 | except (AttributeError, TypeError): |
|
105 | 105 | # "attribute-less object" or "read-only attributes" |
|
106 | 106 | pass |
|
107 | 107 | return oldvalue |
|
108 | 108 | |
|
109 | 109 | @undoc |
|
110 | 110 | def no_op(*a, **kw): pass |
|
111 | 111 | |
|
112 | 112 | @undoc |
|
113 | 113 | class NoOpContext(object): |
|
114 | 114 | def __enter__(self): pass |
|
115 | 115 | def __exit__(self, type, value, traceback): pass |
|
116 | 116 | no_op_context = NoOpContext() |
|
117 | 117 | |
|
118 | 118 | class SpaceInInput(Exception): pass |
|
119 | 119 | |
|
120 | 120 | @undoc |
|
121 | 121 | class Bunch: pass |
|
122 | 122 | |
|
123 | 123 | |
|
124 | 124 | def get_default_colors(): |
|
125 | 125 | if sys.platform=='darwin': |
|
126 | 126 | return "LightBG" |
|
127 | 127 | elif os.name=='nt': |
|
128 | 128 | return 'Linux' |
|
129 | 129 | else: |
|
130 | 130 | return 'Linux' |
|
131 | 131 | |
|
132 | 132 | |
|
133 | 133 | class SeparateUnicode(Unicode): |
|
134 | 134 | r"""A Unicode subclass to validate separate_in, separate_out, etc. |
|
135 | 135 | |
|
136 | 136 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. |
|
137 | 137 | """ |
|
138 | 138 | |
|
139 | 139 | def validate(self, obj, value): |
|
140 | 140 | if value == '0': value = '' |
|
141 | 141 | value = value.replace('\\n','\n') |
|
142 | 142 | return super(SeparateUnicode, self).validate(obj, value) |
|
143 | 143 | |
|
144 | 144 | |
|
145 | 145 | class ReadlineNoRecord(object): |
|
146 | 146 | """Context manager to execute some code, then reload readline history |
|
147 | 147 | so that interactive input to the code doesn't appear when pressing up.""" |
|
148 | 148 | def __init__(self, shell): |
|
149 | 149 | self.shell = shell |
|
150 | 150 | self._nested_level = 0 |
|
151 | 151 | |
|
152 | 152 | def __enter__(self): |
|
153 | 153 | if self._nested_level == 0: |
|
154 | 154 | try: |
|
155 | 155 | self.orig_length = self.current_length() |
|
156 | 156 | self.readline_tail = self.get_readline_tail() |
|
157 | 157 | except (AttributeError, IndexError): # Can fail with pyreadline |
|
158 | 158 | self.orig_length, self.readline_tail = 999999, [] |
|
159 | 159 | self._nested_level += 1 |
|
160 | 160 | |
|
161 | 161 | def __exit__(self, type, value, traceback): |
|
162 | 162 | self._nested_level -= 1 |
|
163 | 163 | if self._nested_level == 0: |
|
164 | 164 | # Try clipping the end if it's got longer |
|
165 | 165 | try: |
|
166 | 166 | e = self.current_length() - self.orig_length |
|
167 | 167 | if e > 0: |
|
168 | 168 | for _ in range(e): |
|
169 | 169 | self.shell.readline.remove_history_item(self.orig_length) |
|
170 | 170 | |
|
171 | 171 | # If it still doesn't match, just reload readline history. |
|
172 | 172 | if self.current_length() != self.orig_length \ |
|
173 | 173 | or self.get_readline_tail() != self.readline_tail: |
|
174 | 174 | self.shell.refill_readline_hist() |
|
175 | 175 | except (AttributeError, IndexError): |
|
176 | 176 | pass |
|
177 | 177 | # Returning False will cause exceptions to propagate |
|
178 | 178 | return False |
|
179 | 179 | |
|
180 | 180 | def current_length(self): |
|
181 | 181 | return self.shell.readline.get_current_history_length() |
|
182 | 182 | |
|
183 | 183 | def get_readline_tail(self, n=10): |
|
184 | 184 | """Get the last n items in readline history.""" |
|
185 | 185 | end = self.shell.readline.get_current_history_length() + 1 |
|
186 | 186 | start = max(end-n, 1) |
|
187 | 187 | ghi = self.shell.readline.get_history_item |
|
188 | 188 | return [ghi(x) for x in range(start, end)] |
|
189 | 189 | |
|
190 | 190 | |
|
191 | 191 | @undoc |
|
192 | 192 | class DummyMod(object): |
|
193 | 193 | """A dummy module used for IPython's interactive module when |
|
194 | 194 | a namespace must be assigned to the module's __dict__.""" |
|
195 | 195 | pass |
|
196 | 196 | |
|
197 | 197 | |
|
198 | 198 | class ExecutionResult(object): |
|
199 | 199 | """The result of a call to :meth:`InteractiveShell.run_cell` |
|
200 | 200 | |
|
201 | 201 | Stores information about what took place. |
|
202 | 202 | """ |
|
203 | 203 | execution_count = None |
|
204 | 204 | error_before_exec = None |
|
205 | 205 | error_in_exec = None |
|
206 | 206 | result = None |
|
207 | 207 | |
|
208 | 208 | @property |
|
209 | 209 | def success(self): |
|
210 | 210 | return (self.error_before_exec is None) and (self.error_in_exec is None) |
|
211 | 211 | |
|
212 | 212 | def raise_error(self): |
|
213 | 213 | """Reraises error if `success` is `False`, otherwise does nothing""" |
|
214 | 214 | if self.error_before_exec is not None: |
|
215 | 215 | raise self.error_before_exec |
|
216 | 216 | if self.error_in_exec is not None: |
|
217 | 217 | raise self.error_in_exec |
|
218 | 218 | |
|
219 | 219 | |
|
220 | 220 | class InteractiveShell(SingletonConfigurable): |
|
221 | 221 | """An enhanced, interactive shell for Python.""" |
|
222 | 222 | |
|
223 | 223 | _instance = None |
|
224 | 224 | |
|
225 | 225 | ast_transformers = List([], config=True, help= |
|
226 | 226 | """ |
|
227 | 227 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
228 | 228 | to user input before code is run. |
|
229 | 229 | """ |
|
230 | 230 | ) |
|
231 | 231 | |
|
232 | 232 | autocall = Enum((0,1,2), default_value=0, config=True, help= |
|
233 | 233 | """ |
|
234 | 234 | Make IPython automatically call any callable object even if you didn't |
|
235 | 235 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
236 | 236 | automatically. The value can be '0' to disable the feature, '1' for |
|
237 | 237 | 'smart' autocall, where it is not applied if there are no more |
|
238 | 238 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
239 | 239 | objects are automatically called (even if no arguments are present). |
|
240 | 240 | """ |
|
241 | 241 | ) |
|
242 | 242 | # TODO: remove all autoindent logic and put into frontends. |
|
243 | 243 | # We can't do this yet because even runlines uses the autoindent. |
|
244 | 244 | autoindent = CBool(True, config=True, help= |
|
245 | 245 | """ |
|
246 | 246 | Autoindent IPython code entered interactively. |
|
247 | 247 | """ |
|
248 | 248 | ) |
|
249 | 249 | automagic = CBool(True, config=True, help= |
|
250 | 250 | """ |
|
251 | 251 | Enable magic commands to be called without the leading %. |
|
252 | 252 | """ |
|
253 | 253 | ) |
|
254 | 254 | |
|
255 | 255 | banner1 = Unicode(default_banner, config=True, |
|
256 | 256 | help="""The part of the banner to be printed before the profile""" |
|
257 | 257 | ) |
|
258 | 258 | banner2 = Unicode('', config=True, |
|
259 | 259 | help="""The part of the banner to be printed after the profile""" |
|
260 | 260 | ) |
|
261 | 261 | |
|
262 | 262 | cache_size = Integer(1000, config=True, help= |
|
263 | 263 | """ |
|
264 | 264 | Set the size of the output cache. The default is 1000, you can |
|
265 | 265 | change it permanently in your config file. Setting it to 0 completely |
|
266 | 266 | disables the caching system, and the minimum value accepted is 20 (if |
|
267 | 267 | you provide a value less than 20, it is reset to 0 and a warning is |
|
268 | 268 | issued). This limit is defined because otherwise you'll spend more |
|
269 | 269 | time re-flushing a too small cache than working |
|
270 | 270 | """ |
|
271 | 271 | ) |
|
272 | 272 | color_info = CBool(True, config=True, help= |
|
273 | 273 | """ |
|
274 | 274 | Use colors for displaying information about objects. Because this |
|
275 | 275 | information is passed through a pager (like 'less'), and some pagers |
|
276 | 276 | get confused with color codes, this capability can be turned off. |
|
277 | 277 | """ |
|
278 | 278 | ) |
|
279 | 279 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
280 | 280 | default_value=get_default_colors(), config=True, |
|
281 | 281 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
282 | 282 | ) |
|
283 | 283 | colors_force = CBool(False, help= |
|
284 | 284 | """ |
|
285 | 285 | Force use of ANSI color codes, regardless of OS and readline |
|
286 | 286 | availability. |
|
287 | 287 | """ |
|
288 | 288 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
289 | 289 | # without readline on Win32. When the ZMQ formatting system is |
|
290 | 290 | # refactored, this should be removed. |
|
291 | 291 | ) |
|
292 | 292 | debug = CBool(False, config=True) |
|
293 | 293 | deep_reload = CBool(False, config=True, help= |
|
294 | 294 | """ |
|
295 | 295 | **Deprecated** |
|
296 | 296 | |
|
297 | Will be removed in IPython 6.0 | |
|
298 | ||
|
297 | 299 | Enable deep (recursive) reloading by default. IPython can use the |
|
298 | 300 | deep_reload module which reloads changes in modules recursively (it |
|
299 | 301 | replaces the reload() function, so you don't need to change anything to |
|
300 | 302 | use it). `deep_reload` forces a full reload of modules whose code may |
|
301 | 303 | have changed, which the default reload() function does not. When |
|
302 | 304 | deep_reload is off, IPython will use the normal reload(), but |
|
303 | 305 | deep_reload will still be available as dreload(). |
|
304 | 306 | """ |
|
305 | 307 | ) |
|
306 | 308 | disable_failing_post_execute = CBool(False, config=True, |
|
307 | 309 | help="Don't call post-execute functions that have failed in the past." |
|
308 | 310 | ) |
|
309 | 311 | display_formatter = Instance(DisplayFormatter, allow_none=True) |
|
310 | 312 | displayhook_class = Type(DisplayHook) |
|
311 | 313 | display_pub_class = Type(DisplayPublisher) |
|
312 | 314 | data_pub_class = None |
|
313 | 315 | |
|
314 | 316 | exit_now = CBool(False) |
|
315 | 317 | exiter = Instance(ExitAutocall) |
|
316 | 318 | def _exiter_default(self): |
|
317 | 319 | return ExitAutocall(self) |
|
318 | 320 | # Monotonically increasing execution counter |
|
319 | 321 | execution_count = Integer(1) |
|
320 | 322 | filename = Unicode("<ipython console>") |
|
321 | 323 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
322 | 324 | |
|
323 | 325 | # Input splitter, to transform input line by line and detect when a block |
|
324 | 326 | # is ready to be executed. |
|
325 | 327 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
326 | 328 | (), {'line_input_checker': True}) |
|
327 | 329 | |
|
328 | 330 | # This InputSplitter instance is used to transform completed cells before |
|
329 | 331 | # running them. It allows cell magics to contain blank lines. |
|
330 | 332 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
331 | 333 | (), {'line_input_checker': False}) |
|
332 | 334 | |
|
333 | 335 | logstart = CBool(False, config=True, help= |
|
334 | 336 | """ |
|
335 | 337 | Start logging to the default log file in overwrite mode. |
|
336 | 338 | Use `logappend` to specify a log file to **append** logs to. |
|
337 | 339 | """ |
|
338 | 340 | ) |
|
339 | 341 | logfile = Unicode('', config=True, help= |
|
340 | 342 | """ |
|
341 | 343 | The name of the logfile to use. |
|
342 | 344 | """ |
|
343 | 345 | ) |
|
344 | 346 | logappend = Unicode('', config=True, help= |
|
345 | 347 | """ |
|
346 | 348 | Start logging to the given file in append mode. |
|
347 | 349 | Use `logfile` to specify a log file to **overwrite** logs to. |
|
348 | 350 | """ |
|
349 | 351 | ) |
|
350 | 352 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
351 | 353 | config=True) |
|
352 | 354 | pdb = CBool(False, config=True, help= |
|
353 | 355 | """ |
|
354 | 356 | Automatically call the pdb debugger after every exception. |
|
355 | 357 | """ |
|
356 | 358 | ) |
|
357 | 359 | multiline_history = CBool(sys.platform != 'win32', config=True, |
|
358 | 360 | help="Save multi-line entries as one entry in readline history" |
|
359 | 361 | ) |
|
360 | 362 | display_page = Bool(False, config=True, |
|
361 | 363 | help="""If True, anything that would be passed to the pager |
|
362 | 364 | will be displayed as regular output instead.""" |
|
363 | 365 | ) |
|
364 | 366 | |
|
365 | 367 | # deprecated prompt traits: |
|
366 | 368 | |
|
367 | 369 | prompt_in1 = Unicode('In [\\#]: ', config=True, |
|
368 | help="Deprecated, use PromptManager.in_template") | |
|
370 | help="Deprecated, will be removed in IPython 5.0, use PromptManager.in_template") | |
|
369 | 371 | prompt_in2 = Unicode(' .\\D.: ', config=True, |
|
370 | help="Deprecated, use PromptManager.in2_template") | |
|
372 | help="Deprecated, will be removed in IPython 5.0, use PromptManager.in2_template") | |
|
371 | 373 | prompt_out = Unicode('Out[\\#]: ', config=True, |
|
372 | help="Deprecated, use PromptManager.out_template") | |
|
374 | help="Deprecated, will be removed in IPython 5.0, use PromptManager.out_template") | |
|
373 | 375 | prompts_pad_left = CBool(True, config=True, |
|
374 | help="Deprecated, use PromptManager.justify") | |
|
376 | help="Deprecated, will be removed in IPython 5.0, use PromptManager.justify") | |
|
375 | 377 | |
|
376 | 378 | def _prompt_trait_changed(self, name, old, new): |
|
377 | 379 | table = { |
|
378 | 380 | 'prompt_in1' : 'in_template', |
|
379 | 381 | 'prompt_in2' : 'in2_template', |
|
380 | 382 | 'prompt_out' : 'out_template', |
|
381 | 383 | 'prompts_pad_left' : 'justify', |
|
382 | 384 | } |
|
383 | 385 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format( |
|
384 | 386 | name=name, newname=table[name]) |
|
385 | 387 | ) |
|
386 | 388 | # protect against weird cases where self.config may not exist: |
|
387 | 389 | if self.config is not None: |
|
388 | 390 | # propagate to corresponding PromptManager trait |
|
389 | 391 | setattr(self.config.PromptManager, table[name], new) |
|
390 | 392 | |
|
391 | 393 | _prompt_in1_changed = _prompt_trait_changed |
|
392 | 394 | _prompt_in2_changed = _prompt_trait_changed |
|
393 | 395 | _prompt_out_changed = _prompt_trait_changed |
|
394 | 396 | _prompt_pad_left_changed = _prompt_trait_changed |
|
395 | 397 | |
|
396 | 398 | show_rewritten_input = CBool(True, config=True, |
|
397 | 399 | help="Show rewritten input, e.g. for autocall." |
|
398 | 400 | ) |
|
399 | 401 | |
|
400 | 402 | quiet = CBool(False, config=True) |
|
401 | 403 | |
|
402 | 404 | history_length = Integer(10000, config=True) |
|
403 | 405 | |
|
404 | 406 | history_load_length = Integer(1000, config=True, help= |
|
405 | 407 | """ |
|
406 | 408 | The number of saved history entries to be loaded |
|
407 | 409 | into the readline buffer at startup. |
|
408 | 410 | """ |
|
409 | 411 | ) |
|
410 | 412 | |
|
411 | 413 | # The readline stuff will eventually be moved to the terminal subclass |
|
412 | 414 | # but for now, we can't do that as readline is welded in everywhere. |
|
413 | 415 | readline_use = CBool(True, config=True) |
|
414 | 416 | readline_remove_delims = Unicode('-/~', config=True) |
|
415 | 417 | readline_delims = Unicode() # set by init_readline() |
|
416 | 418 | # don't use \M- bindings by default, because they |
|
417 | 419 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
418 | 420 | readline_parse_and_bind = List([ |
|
419 | 421 | 'tab: complete', |
|
420 | 422 | '"\C-l": clear-screen', |
|
421 | 423 | 'set show-all-if-ambiguous on', |
|
422 | 424 | '"\C-o": tab-insert', |
|
423 | 425 | '"\C-r": reverse-search-history', |
|
424 | 426 | '"\C-s": forward-search-history', |
|
425 | 427 | '"\C-p": history-search-backward', |
|
426 | 428 | '"\C-n": history-search-forward', |
|
427 | 429 | '"\e[A": history-search-backward', |
|
428 | 430 | '"\e[B": history-search-forward', |
|
429 | 431 | '"\C-k": kill-line', |
|
430 | 432 | '"\C-u": unix-line-discard', |
|
431 | 433 | ], config=True) |
|
432 | 434 | |
|
433 | 435 | _custom_readline_config = False |
|
434 | 436 | |
|
435 | 437 | def _readline_parse_and_bind_changed(self, name, old, new): |
|
436 | 438 | # notice that readline config is customized |
|
437 | 439 | # indicates that it should have higher priority than inputrc |
|
438 | 440 | self._custom_readline_config = True |
|
439 | 441 | |
|
440 | 442 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
441 | 443 | default_value='last_expr', config=True, |
|
442 | 444 | help=""" |
|
443 | 445 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
444 | 446 | run interactively (displaying output from expressions).""") |
|
445 | 447 | |
|
446 | 448 | # TODO: this part of prompt management should be moved to the frontends. |
|
447 | 449 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
448 | 450 | separate_in = SeparateUnicode('\n', config=True) |
|
449 | 451 | separate_out = SeparateUnicode('', config=True) |
|
450 | 452 | separate_out2 = SeparateUnicode('', config=True) |
|
451 | 453 | wildcards_case_sensitive = CBool(True, config=True) |
|
452 | 454 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
453 | 455 | default_value='Context', config=True) |
|
454 | 456 | |
|
455 | 457 | # Subcomponents of InteractiveShell |
|
456 | 458 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) |
|
457 | 459 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) |
|
458 | 460 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) |
|
459 | 461 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) |
|
460 | 462 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) |
|
461 | 463 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) |
|
462 | 464 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) |
|
463 | 465 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) |
|
464 | 466 | |
|
465 | 467 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) |
|
466 | 468 | @property |
|
467 | 469 | def profile(self): |
|
468 | 470 | if self.profile_dir is not None: |
|
469 | 471 | name = os.path.basename(self.profile_dir.location) |
|
470 | 472 | return name.replace('profile_','') |
|
471 | 473 | |
|
472 | 474 | |
|
473 | 475 | # Private interface |
|
474 | 476 | _post_execute = Dict() |
|
475 | 477 | |
|
476 | 478 | # Tracks any GUI loop loaded for pylab |
|
477 | 479 | pylab_gui_select = None |
|
478 | 480 | |
|
479 | 481 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
480 | 482 | user_module=None, user_ns=None, |
|
481 | 483 | custom_exceptions=((), None), **kwargs): |
|
482 | 484 | |
|
483 | 485 | # This is where traits with a config_key argument are updated |
|
484 | 486 | # from the values on config. |
|
485 | 487 | super(InteractiveShell, self).__init__(**kwargs) |
|
486 | 488 | self.configurables = [self] |
|
487 | 489 | |
|
488 | 490 | # These are relatively independent and stateless |
|
489 | 491 | self.init_ipython_dir(ipython_dir) |
|
490 | 492 | self.init_profile_dir(profile_dir) |
|
491 | 493 | self.init_instance_attrs() |
|
492 | 494 | self.init_environment() |
|
493 | 495 | |
|
494 | 496 | # Check if we're in a virtualenv, and set up sys.path. |
|
495 | 497 | self.init_virtualenv() |
|
496 | 498 | |
|
497 | 499 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
498 | 500 | self.init_create_namespaces(user_module, user_ns) |
|
499 | 501 | # This has to be done after init_create_namespaces because it uses |
|
500 | 502 | # something in self.user_ns, but before init_sys_modules, which |
|
501 | 503 | # is the first thing to modify sys. |
|
502 | 504 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
503 | 505 | # is created, we are saving the overridden ones here. Not sure if this |
|
504 | 506 | # is what we want to do. |
|
505 | 507 | self.save_sys_module_state() |
|
506 | 508 | self.init_sys_modules() |
|
507 | 509 | |
|
508 | 510 | # While we're trying to have each part of the code directly access what |
|
509 | 511 | # it needs without keeping redundant references to objects, we have too |
|
510 | 512 | # much legacy code that expects ip.db to exist. |
|
511 | 513 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
512 | 514 | |
|
513 | 515 | self.init_history() |
|
514 | 516 | self.init_encoding() |
|
515 | 517 | self.init_prefilter() |
|
516 | 518 | |
|
517 | 519 | self.init_syntax_highlighting() |
|
518 | 520 | self.init_hooks() |
|
519 | 521 | self.init_events() |
|
520 | 522 | self.init_pushd_popd_magic() |
|
521 | 523 | # self.init_traceback_handlers use to be here, but we moved it below |
|
522 | 524 | # because it and init_io have to come after init_readline. |
|
523 | 525 | self.init_user_ns() |
|
524 | 526 | self.init_logger() |
|
525 | 527 | self.init_builtins() |
|
526 | 528 | |
|
527 | 529 | # The following was in post_config_initialization |
|
528 | 530 | self.init_inspector() |
|
529 | 531 | # init_readline() must come before init_io(), because init_io uses |
|
530 | 532 | # readline related things. |
|
531 | 533 | self.init_readline() |
|
532 | 534 | # We save this here in case user code replaces raw_input, but it needs |
|
533 | 535 | # to be after init_readline(), because PyPy's readline works by replacing |
|
534 | 536 | # raw_input. |
|
535 | 537 | if py3compat.PY3: |
|
536 | 538 | self.raw_input_original = input |
|
537 | 539 | else: |
|
538 | 540 | self.raw_input_original = raw_input |
|
539 | 541 | # init_completer must come after init_readline, because it needs to |
|
540 | 542 | # know whether readline is present or not system-wide to configure the |
|
541 | 543 | # completers, since the completion machinery can now operate |
|
542 | 544 | # independently of readline (e.g. over the network) |
|
543 | 545 | self.init_completer() |
|
544 | 546 | # TODO: init_io() needs to happen before init_traceback handlers |
|
545 | 547 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
546 | 548 | # This logic in in debugger.Pdb and should eventually be changed. |
|
547 | 549 | self.init_io() |
|
548 | 550 | self.init_traceback_handlers(custom_exceptions) |
|
549 | 551 | self.init_prompts() |
|
550 | 552 | self.init_display_formatter() |
|
551 | 553 | self.init_display_pub() |
|
552 | 554 | self.init_data_pub() |
|
553 | 555 | self.init_displayhook() |
|
554 | 556 | self.init_magics() |
|
555 | 557 | self.init_alias() |
|
556 | 558 | self.init_logstart() |
|
557 | 559 | self.init_pdb() |
|
558 | 560 | self.init_extension_manager() |
|
559 | 561 | self.init_payload() |
|
560 | 562 | self.init_deprecation_warnings() |
|
561 | 563 | self.hooks.late_startup_hook() |
|
562 | 564 | self.events.trigger('shell_initialized', self) |
|
563 | 565 | atexit.register(self.atexit_operations) |
|
564 | 566 | |
|
565 | 567 | def get_ipython(self): |
|
566 | 568 | """Return the currently running IPython instance.""" |
|
567 | 569 | return self |
|
568 | 570 | |
|
569 | 571 | #------------------------------------------------------------------------- |
|
570 | 572 | # Trait changed handlers |
|
571 | 573 | #------------------------------------------------------------------------- |
|
572 | 574 | |
|
573 | 575 | def _ipython_dir_changed(self, name, new): |
|
574 | 576 | ensure_dir_exists(new) |
|
575 | 577 | |
|
576 | 578 | def set_autoindent(self,value=None): |
|
577 | 579 | """Set the autoindent flag, checking for readline support. |
|
578 | 580 | |
|
579 | 581 | If called with no arguments, it acts as a toggle.""" |
|
580 | 582 | |
|
581 | 583 | if value != 0 and not self.has_readline: |
|
582 | 584 | if os.name == 'posix': |
|
583 | 585 | warn("The auto-indent feature requires the readline library") |
|
584 | 586 | self.autoindent = 0 |
|
585 | 587 | return |
|
586 | 588 | if value is None: |
|
587 | 589 | self.autoindent = not self.autoindent |
|
588 | 590 | else: |
|
589 | 591 | self.autoindent = value |
|
590 | 592 | |
|
591 | 593 | #------------------------------------------------------------------------- |
|
592 | 594 | # init_* methods called by __init__ |
|
593 | 595 | #------------------------------------------------------------------------- |
|
594 | 596 | |
|
595 | 597 | def init_ipython_dir(self, ipython_dir): |
|
596 | 598 | if ipython_dir is not None: |
|
597 | 599 | self.ipython_dir = ipython_dir |
|
598 | 600 | return |
|
599 | 601 | |
|
600 | 602 | self.ipython_dir = get_ipython_dir() |
|
601 | 603 | |
|
602 | 604 | def init_profile_dir(self, profile_dir): |
|
603 | 605 | if profile_dir is not None: |
|
604 | 606 | self.profile_dir = profile_dir |
|
605 | 607 | return |
|
606 | 608 | self.profile_dir =\ |
|
607 | 609 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
608 | 610 | |
|
609 | 611 | def init_instance_attrs(self): |
|
610 | 612 | self.more = False |
|
611 | 613 | |
|
612 | 614 | # command compiler |
|
613 | 615 | self.compile = CachingCompiler() |
|
614 | 616 | |
|
615 | 617 | # Make an empty namespace, which extension writers can rely on both |
|
616 | 618 | # existing and NEVER being used by ipython itself. This gives them a |
|
617 | 619 | # convenient location for storing additional information and state |
|
618 | 620 | # their extensions may require, without fear of collisions with other |
|
619 | 621 | # ipython names that may develop later. |
|
620 | 622 | self.meta = Struct() |
|
621 | 623 | |
|
622 | 624 | # Temporary files used for various purposes. Deleted at exit. |
|
623 | 625 | self.tempfiles = [] |
|
624 | 626 | self.tempdirs = [] |
|
625 | 627 | |
|
626 | 628 | # Keep track of readline usage (later set by init_readline) |
|
627 | 629 | self.has_readline = False |
|
628 | 630 | |
|
629 | 631 | # keep track of where we started running (mainly for crash post-mortem) |
|
630 | 632 | # This is not being used anywhere currently. |
|
631 | 633 | self.starting_dir = py3compat.getcwd() |
|
632 | 634 | |
|
633 | 635 | # Indentation management |
|
634 | 636 | self.indent_current_nsp = 0 |
|
635 | 637 | |
|
636 | 638 | # Dict to track post-execution functions that have been registered |
|
637 | 639 | self._post_execute = {} |
|
638 | 640 | |
|
639 | 641 | def init_environment(self): |
|
640 | 642 | """Any changes we need to make to the user's environment.""" |
|
641 | 643 | pass |
|
642 | 644 | |
|
643 | 645 | def init_encoding(self): |
|
644 | 646 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
645 | 647 | # under Win32 have it set to None, and we need to have a known valid |
|
646 | 648 | # encoding to use in the raw_input() method |
|
647 | 649 | try: |
|
648 | 650 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
649 | 651 | except AttributeError: |
|
650 | 652 | self.stdin_encoding = 'ascii' |
|
651 | 653 | |
|
652 | 654 | def init_syntax_highlighting(self): |
|
653 | 655 | # Python source parser/formatter for syntax highlighting |
|
654 | 656 | pyformat = PyColorize.Parser().format |
|
655 | 657 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
656 | 658 | |
|
657 | 659 | def init_pushd_popd_magic(self): |
|
658 | 660 | # for pushd/popd management |
|
659 | 661 | self.home_dir = get_home_dir() |
|
660 | 662 | |
|
661 | 663 | self.dir_stack = [] |
|
662 | 664 | |
|
663 | 665 | def init_logger(self): |
|
664 | 666 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
665 | 667 | logmode='rotate') |
|
666 | 668 | |
|
667 | 669 | def init_logstart(self): |
|
668 | 670 | """Initialize logging in case it was requested at the command line. |
|
669 | 671 | """ |
|
670 | 672 | if self.logappend: |
|
671 | 673 | self.magic('logstart %s append' % self.logappend) |
|
672 | 674 | elif self.logfile: |
|
673 | 675 | self.magic('logstart %s' % self.logfile) |
|
674 | 676 | elif self.logstart: |
|
675 | 677 | self.magic('logstart') |
|
676 | 678 | |
|
677 | 679 | def init_deprecation_warnings(self): |
|
678 | 680 | """ |
|
679 | 681 | register default filter for deprecation warning. |
|
680 | 682 | |
|
681 | 683 | This will allow deprecation warning of function used interactively to show |
|
682 | 684 | warning to users, and still hide deprecation warning from libraries import. |
|
683 | 685 | """ |
|
684 | 686 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) |
|
685 | 687 | |
|
686 | 688 | def init_builtins(self): |
|
687 | 689 | # A single, static flag that we set to True. Its presence indicates |
|
688 | 690 | # that an IPython shell has been created, and we make no attempts at |
|
689 | 691 | # removing on exit or representing the existence of more than one |
|
690 | 692 | # IPython at a time. |
|
691 | 693 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
692 | 694 | |
|
693 | 695 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to |
|
694 | 696 | # manage on enter/exit, but with all our shells it's virtually |
|
695 | 697 | # impossible to get all the cases right. We're leaving the name in for |
|
696 | 698 | # those who adapted their codes to check for this flag, but will |
|
697 | 699 | # eventually remove it after a few more releases. |
|
698 | 700 | builtin_mod.__dict__['__IPYTHON__active'] = \ |
|
699 | 701 | 'Deprecated, check for __IPYTHON__' |
|
700 | 702 | |
|
701 | 703 | self.builtin_trap = BuiltinTrap(shell=self) |
|
702 | 704 | |
|
703 | 705 | def init_inspector(self): |
|
704 | 706 | # Object inspector |
|
705 | 707 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
706 | 708 | PyColorize.ANSICodeColors, |
|
707 | 709 | 'NoColor', |
|
708 | 710 | self.object_info_string_level) |
|
709 | 711 | |
|
710 | 712 | def init_io(self): |
|
711 | 713 | # This will just use sys.stdout and sys.stderr. If you want to |
|
712 | 714 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
713 | 715 | # *before* instantiating this class, because io holds onto |
|
714 | 716 | # references to the underlying streams. |
|
715 | 717 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: |
|
716 | 718 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
717 | 719 | else: |
|
718 | 720 | io.stdout = io.IOStream(sys.stdout) |
|
719 | 721 | io.stderr = io.IOStream(sys.stderr) |
|
720 | 722 | |
|
721 | 723 | def init_prompts(self): |
|
722 | 724 | self.prompt_manager = PromptManager(shell=self, parent=self) |
|
723 | 725 | self.configurables.append(self.prompt_manager) |
|
724 | 726 | # Set system prompts, so that scripts can decide if they are running |
|
725 | 727 | # interactively. |
|
726 | 728 | sys.ps1 = 'In : ' |
|
727 | 729 | sys.ps2 = '...: ' |
|
728 | 730 | sys.ps3 = 'Out: ' |
|
729 | 731 | |
|
730 | 732 | def init_display_formatter(self): |
|
731 | 733 | self.display_formatter = DisplayFormatter(parent=self) |
|
732 | 734 | self.configurables.append(self.display_formatter) |
|
733 | 735 | |
|
734 | 736 | def init_display_pub(self): |
|
735 | 737 | self.display_pub = self.display_pub_class(parent=self) |
|
736 | 738 | self.configurables.append(self.display_pub) |
|
737 | 739 | |
|
738 | 740 | def init_data_pub(self): |
|
739 | 741 | if not self.data_pub_class: |
|
740 | 742 | self.data_pub = None |
|
741 | 743 | return |
|
742 | 744 | self.data_pub = self.data_pub_class(parent=self) |
|
743 | 745 | self.configurables.append(self.data_pub) |
|
744 | 746 | |
|
745 | 747 | def init_displayhook(self): |
|
746 | 748 | # Initialize displayhook, set in/out prompts and printing system |
|
747 | 749 | self.displayhook = self.displayhook_class( |
|
748 | 750 | parent=self, |
|
749 | 751 | shell=self, |
|
750 | 752 | cache_size=self.cache_size, |
|
751 | 753 | ) |
|
752 | 754 | self.configurables.append(self.displayhook) |
|
753 | 755 | # This is a context manager that installs/revmoes the displayhook at |
|
754 | 756 | # the appropriate time. |
|
755 | 757 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
756 | 758 | |
|
757 | 759 | def init_virtualenv(self): |
|
758 | 760 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
759 | 761 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
760 | 762 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
761 | 763 | warning will appear suggesting the user installs IPython in the |
|
762 | 764 | virtualenv, but for many cases, it probably works well enough. |
|
763 | 765 | |
|
764 | 766 | Adapted from code snippets online. |
|
765 | 767 | |
|
766 | 768 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
767 | 769 | """ |
|
768 | 770 | if 'VIRTUAL_ENV' not in os.environ: |
|
769 | 771 | # Not in a virtualenv |
|
770 | 772 | return |
|
771 | 773 | |
|
772 | 774 | # venv detection: |
|
773 | 775 | # stdlib venv may symlink sys.executable, so we can't use realpath. |
|
774 | 776 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. |
|
775 | 777 | # So we just check every item in the symlink tree (generally <= 3) |
|
776 | 778 | p = os.path.normcase(sys.executable) |
|
777 | 779 | paths = [p] |
|
778 | 780 | while os.path.islink(p): |
|
779 | 781 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) |
|
780 | 782 | paths.append(p) |
|
781 | 783 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) |
|
782 | 784 | if any(p.startswith(p_venv) for p in paths): |
|
783 | 785 | # Running properly in the virtualenv, don't need to do anything |
|
784 | 786 | return |
|
785 | 787 | |
|
786 | 788 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
787 | 789 | "install IPython inside the virtualenv.") |
|
788 | 790 | if sys.platform == "win32": |
|
789 | 791 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
790 | 792 | else: |
|
791 | 793 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
792 | 794 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
793 | 795 | |
|
794 | 796 | import site |
|
795 | 797 | sys.path.insert(0, virtual_env) |
|
796 | 798 | site.addsitedir(virtual_env) |
|
797 | 799 | |
|
798 | 800 | #------------------------------------------------------------------------- |
|
799 | 801 | # Things related to injections into the sys module |
|
800 | 802 | #------------------------------------------------------------------------- |
|
801 | 803 | |
|
802 | 804 | def save_sys_module_state(self): |
|
803 | 805 | """Save the state of hooks in the sys module. |
|
804 | 806 | |
|
805 | 807 | This has to be called after self.user_module is created. |
|
806 | 808 | """ |
|
807 | 809 | self._orig_sys_module_state = {'stdin': sys.stdin, |
|
808 | 810 | 'stdout': sys.stdout, |
|
809 | 811 | 'stderr': sys.stderr, |
|
810 | 812 | 'excepthook': sys.excepthook} |
|
811 | 813 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
812 | 814 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
813 | 815 | |
|
814 | 816 | def restore_sys_module_state(self): |
|
815 | 817 | """Restore the state of the sys module.""" |
|
816 | 818 | try: |
|
817 | 819 | for k, v in iteritems(self._orig_sys_module_state): |
|
818 | 820 | setattr(sys, k, v) |
|
819 | 821 | except AttributeError: |
|
820 | 822 | pass |
|
821 | 823 | # Reset what what done in self.init_sys_modules |
|
822 | 824 | if self._orig_sys_modules_main_mod is not None: |
|
823 | 825 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
824 | 826 | |
|
825 | 827 | #------------------------------------------------------------------------- |
|
826 | 828 | # Things related to the banner |
|
827 | 829 | #------------------------------------------------------------------------- |
|
828 | 830 | |
|
829 | 831 | @property |
|
830 | 832 | def banner(self): |
|
831 | 833 | banner = self.banner1 |
|
832 | 834 | if self.profile and self.profile != 'default': |
|
833 | 835 | banner += '\nIPython profile: %s\n' % self.profile |
|
834 | 836 | if self.banner2: |
|
835 | 837 | banner += '\n' + self.banner2 |
|
836 | 838 | return banner |
|
837 | 839 | |
|
838 | 840 | def show_banner(self, banner=None): |
|
839 | 841 | if banner is None: |
|
840 | 842 | banner = self.banner |
|
841 | 843 | self.write(banner) |
|
842 | 844 | |
|
843 | 845 | #------------------------------------------------------------------------- |
|
844 | 846 | # Things related to hooks |
|
845 | 847 | #------------------------------------------------------------------------- |
|
846 | 848 | |
|
847 | 849 | def init_hooks(self): |
|
848 | 850 | # hooks holds pointers used for user-side customizations |
|
849 | 851 | self.hooks = Struct() |
|
850 | 852 | |
|
851 | 853 | self.strdispatchers = {} |
|
852 | 854 | |
|
853 | 855 | # Set all default hooks, defined in the IPython.hooks module. |
|
854 | 856 | hooks = IPython.core.hooks |
|
855 | 857 | for hook_name in hooks.__all__: |
|
856 | 858 | # default hooks have priority 100, i.e. low; user hooks should have |
|
857 | 859 | # 0-100 priority |
|
858 | 860 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) |
|
859 | 861 | |
|
860 | 862 | if self.display_page: |
|
861 | 863 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) |
|
862 | 864 | |
|
863 | 865 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, |
|
864 | 866 | _warn_deprecated=True): |
|
865 | 867 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
866 | 868 | |
|
867 | 869 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
868 | 870 | adding your function to one of these hooks, you can modify IPython's |
|
869 | 871 | behavior to call at runtime your own routines.""" |
|
870 | 872 | |
|
871 | 873 | # At some point in the future, this should validate the hook before it |
|
872 | 874 | # accepts it. Probably at least check that the hook takes the number |
|
873 | 875 | # of args it's supposed to. |
|
874 | 876 | |
|
875 | 877 | f = types.MethodType(hook,self) |
|
876 | 878 | |
|
877 | 879 | # check if the hook is for strdispatcher first |
|
878 | 880 | if str_key is not None: |
|
879 | 881 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
880 | 882 | sdp.add_s(str_key, f, priority ) |
|
881 | 883 | self.strdispatchers[name] = sdp |
|
882 | 884 | return |
|
883 | 885 | if re_key is not None: |
|
884 | 886 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
885 | 887 | sdp.add_re(re.compile(re_key), f, priority ) |
|
886 | 888 | self.strdispatchers[name] = sdp |
|
887 | 889 | return |
|
888 | 890 | |
|
889 | 891 | dp = getattr(self.hooks, name, None) |
|
890 | 892 | if name not in IPython.core.hooks.__all__: |
|
891 | 893 | print("Warning! Hook '%s' is not one of %s" % \ |
|
892 | 894 | (name, IPython.core.hooks.__all__ )) |
|
893 | 895 | |
|
894 | 896 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): |
|
895 | 897 | alternative = IPython.core.hooks.deprecated[name] |
|
896 | 898 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative)) |
|
897 | 899 | |
|
898 | 900 | if not dp: |
|
899 | 901 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
900 | 902 | |
|
901 | 903 | try: |
|
902 | 904 | dp.add(f,priority) |
|
903 | 905 | except AttributeError: |
|
904 | 906 | # it was not commandchain, plain old func - replace |
|
905 | 907 | dp = f |
|
906 | 908 | |
|
907 | 909 | setattr(self.hooks,name, dp) |
|
908 | 910 | |
|
909 | 911 | #------------------------------------------------------------------------- |
|
910 | 912 | # Things related to events |
|
911 | 913 | #------------------------------------------------------------------------- |
|
912 | 914 | |
|
913 | 915 | def init_events(self): |
|
914 | 916 | self.events = EventManager(self, available_events) |
|
915 | 917 | |
|
916 | 918 | self.events.register("pre_execute", self._clear_warning_registry) |
|
917 | 919 | |
|
918 | 920 | def register_post_execute(self, func): |
|
919 | 921 | """DEPRECATED: Use ip.events.register('post_run_cell', func) |
|
920 | 922 | |
|
921 | 923 | Register a function for calling after code execution. |
|
922 | 924 | """ |
|
923 | 925 | warn("ip.register_post_execute is deprecated, use " |
|
924 | 926 | "ip.events.register('post_run_cell', func) instead.") |
|
925 | 927 | self.events.register('post_run_cell', func) |
|
926 | 928 | |
|
927 | 929 | def _clear_warning_registry(self): |
|
928 | 930 | # clear the warning registry, so that different code blocks with |
|
929 | 931 | # overlapping line number ranges don't cause spurious suppression of |
|
930 | 932 | # warnings (see gh-6611 for details) |
|
931 | 933 | if "__warningregistry__" in self.user_global_ns: |
|
932 | 934 | del self.user_global_ns["__warningregistry__"] |
|
933 | 935 | |
|
934 | 936 | #------------------------------------------------------------------------- |
|
935 | 937 | # Things related to the "main" module |
|
936 | 938 | #------------------------------------------------------------------------- |
|
937 | 939 | |
|
938 | 940 | def new_main_mod(self, filename, modname): |
|
939 | 941 | """Return a new 'main' module object for user code execution. |
|
940 | 942 | |
|
941 | 943 | ``filename`` should be the path of the script which will be run in the |
|
942 | 944 | module. Requests with the same filename will get the same module, with |
|
943 | 945 | its namespace cleared. |
|
944 | 946 | |
|
945 | 947 | ``modname`` should be the module name - normally either '__main__' or |
|
946 | 948 | the basename of the file without the extension. |
|
947 | 949 | |
|
948 | 950 | When scripts are executed via %run, we must keep a reference to their |
|
949 | 951 | __main__ module around so that Python doesn't |
|
950 | 952 | clear it, rendering references to module globals useless. |
|
951 | 953 | |
|
952 | 954 | This method keeps said reference in a private dict, keyed by the |
|
953 | 955 | absolute path of the script. This way, for multiple executions of the |
|
954 | 956 | same script we only keep one copy of the namespace (the last one), |
|
955 | 957 | thus preventing memory leaks from old references while allowing the |
|
956 | 958 | objects from the last execution to be accessible. |
|
957 | 959 | """ |
|
958 | 960 | filename = os.path.abspath(filename) |
|
959 | 961 | try: |
|
960 | 962 | main_mod = self._main_mod_cache[filename] |
|
961 | 963 | except KeyError: |
|
962 | 964 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
|
963 | 965 | py3compat.cast_bytes_py2(modname), |
|
964 | 966 | doc="Module created for script run in IPython") |
|
965 | 967 | else: |
|
966 | 968 | main_mod.__dict__.clear() |
|
967 | 969 | main_mod.__name__ = modname |
|
968 | 970 | |
|
969 | 971 | main_mod.__file__ = filename |
|
970 | 972 | # It seems pydoc (and perhaps others) needs any module instance to |
|
971 | 973 | # implement a __nonzero__ method |
|
972 | 974 | main_mod.__nonzero__ = lambda : True |
|
973 | 975 | |
|
974 | 976 | return main_mod |
|
975 | 977 | |
|
976 | 978 | def clear_main_mod_cache(self): |
|
977 | 979 | """Clear the cache of main modules. |
|
978 | 980 | |
|
979 | 981 | Mainly for use by utilities like %reset. |
|
980 | 982 | |
|
981 | 983 | Examples |
|
982 | 984 | -------- |
|
983 | 985 | |
|
984 | 986 | In [15]: import IPython |
|
985 | 987 | |
|
986 | 988 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
987 | 989 | |
|
988 | 990 | In [17]: len(_ip._main_mod_cache) > 0 |
|
989 | 991 | Out[17]: True |
|
990 | 992 | |
|
991 | 993 | In [18]: _ip.clear_main_mod_cache() |
|
992 | 994 | |
|
993 | 995 | In [19]: len(_ip._main_mod_cache) == 0 |
|
994 | 996 | Out[19]: True |
|
995 | 997 | """ |
|
996 | 998 | self._main_mod_cache.clear() |
|
997 | 999 | |
|
998 | 1000 | #------------------------------------------------------------------------- |
|
999 | 1001 | # Things related to debugging |
|
1000 | 1002 | #------------------------------------------------------------------------- |
|
1001 | 1003 | |
|
1002 | 1004 | def init_pdb(self): |
|
1003 | 1005 | # Set calling of pdb on exceptions |
|
1004 | 1006 | # self.call_pdb is a property |
|
1005 | 1007 | self.call_pdb = self.pdb |
|
1006 | 1008 | |
|
1007 | 1009 | def _get_call_pdb(self): |
|
1008 | 1010 | return self._call_pdb |
|
1009 | 1011 | |
|
1010 | 1012 | def _set_call_pdb(self,val): |
|
1011 | 1013 | |
|
1012 | 1014 | if val not in (0,1,False,True): |
|
1013 | 1015 | raise ValueError('new call_pdb value must be boolean') |
|
1014 | 1016 | |
|
1015 | 1017 | # store value in instance |
|
1016 | 1018 | self._call_pdb = val |
|
1017 | 1019 | |
|
1018 | 1020 | # notify the actual exception handlers |
|
1019 | 1021 | self.InteractiveTB.call_pdb = val |
|
1020 | 1022 | |
|
1021 | 1023 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1022 | 1024 | 'Control auto-activation of pdb at exceptions') |
|
1023 | 1025 | |
|
1024 | 1026 | def debugger(self,force=False): |
|
1025 | 1027 | """Call the pydb/pdb debugger. |
|
1026 | 1028 | |
|
1027 | 1029 | Keywords: |
|
1028 | 1030 | |
|
1029 | 1031 | - force(False): by default, this routine checks the instance call_pdb |
|
1030 | 1032 | flag and does not actually invoke the debugger if the flag is false. |
|
1031 | 1033 | The 'force' option forces the debugger to activate even if the flag |
|
1032 | 1034 | is false. |
|
1033 | 1035 | """ |
|
1034 | 1036 | |
|
1035 | 1037 | if not (force or self.call_pdb): |
|
1036 | 1038 | return |
|
1037 | 1039 | |
|
1038 | 1040 | if not hasattr(sys,'last_traceback'): |
|
1039 | 1041 | error('No traceback has been produced, nothing to debug.') |
|
1040 | 1042 | return |
|
1041 | 1043 | |
|
1042 | 1044 | # use pydb if available |
|
1043 | 1045 | if debugger.has_pydb: |
|
1044 | 1046 | from pydb import pm |
|
1045 | 1047 | else: |
|
1046 | 1048 | # fallback to our internal debugger |
|
1047 | 1049 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1048 | 1050 | |
|
1049 | 1051 | with self.readline_no_record: |
|
1050 | 1052 | pm() |
|
1051 | 1053 | |
|
1052 | 1054 | #------------------------------------------------------------------------- |
|
1053 | 1055 | # Things related to IPython's various namespaces |
|
1054 | 1056 | #------------------------------------------------------------------------- |
|
1055 | 1057 | default_user_namespaces = True |
|
1056 | 1058 | |
|
1057 | 1059 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
1058 | 1060 | # Create the namespace where the user will operate. user_ns is |
|
1059 | 1061 | # normally the only one used, and it is passed to the exec calls as |
|
1060 | 1062 | # the locals argument. But we do carry a user_global_ns namespace |
|
1061 | 1063 | # given as the exec 'globals' argument, This is useful in embedding |
|
1062 | 1064 | # situations where the ipython shell opens in a context where the |
|
1063 | 1065 | # distinction between locals and globals is meaningful. For |
|
1064 | 1066 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
1065 | 1067 | |
|
1066 | 1068 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
1067 | 1069 | # level as a dict instead of a module. This is a manual fix, but I |
|
1068 | 1070 | # should really track down where the problem is coming from. Alex |
|
1069 | 1071 | # Schmolck reported this problem first. |
|
1070 | 1072 | |
|
1071 | 1073 | # A useful post by Alex Martelli on this topic: |
|
1072 | 1074 | # Re: inconsistent value from __builtins__ |
|
1073 | 1075 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
1074 | 1076 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
1075 | 1077 | # Gruppen: comp.lang.python |
|
1076 | 1078 | |
|
1077 | 1079 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
1078 | 1080 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
1079 | 1081 | # > <type 'dict'> |
|
1080 | 1082 | # > >>> print type(__builtins__) |
|
1081 | 1083 | # > <type 'module'> |
|
1082 | 1084 | # > Is this difference in return value intentional? |
|
1083 | 1085 | |
|
1084 | 1086 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
1085 | 1087 | # or a module, and it's been that way for a long time. Whether it's |
|
1086 | 1088 | # intentional (or sensible), I don't know. In any case, the idea is |
|
1087 | 1089 | # that if you need to access the built-in namespace directly, you |
|
1088 | 1090 | # should start with "import __builtin__" (note, no 's') which will |
|
1089 | 1091 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
1090 | 1092 | |
|
1091 | 1093 | # These routines return a properly built module and dict as needed by |
|
1092 | 1094 | # the rest of the code, and can also be used by extension writers to |
|
1093 | 1095 | # generate properly initialized namespaces. |
|
1094 | 1096 | if (user_ns is not None) or (user_module is not None): |
|
1095 | 1097 | self.default_user_namespaces = False |
|
1096 | 1098 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
1097 | 1099 | |
|
1098 | 1100 | # A record of hidden variables we have added to the user namespace, so |
|
1099 | 1101 | # we can list later only variables defined in actual interactive use. |
|
1100 | 1102 | self.user_ns_hidden = {} |
|
1101 | 1103 | |
|
1102 | 1104 | # Now that FakeModule produces a real module, we've run into a nasty |
|
1103 | 1105 | # problem: after script execution (via %run), the module where the user |
|
1104 | 1106 | # code ran is deleted. Now that this object is a true module (needed |
|
1105 | 1107 | # so doctest and other tools work correctly), the Python module |
|
1106 | 1108 | # teardown mechanism runs over it, and sets to None every variable |
|
1107 | 1109 | # present in that module. Top-level references to objects from the |
|
1108 | 1110 | # script survive, because the user_ns is updated with them. However, |
|
1109 | 1111 | # calling functions defined in the script that use other things from |
|
1110 | 1112 | # the script will fail, because the function's closure had references |
|
1111 | 1113 | # to the original objects, which are now all None. So we must protect |
|
1112 | 1114 | # these modules from deletion by keeping a cache. |
|
1113 | 1115 | # |
|
1114 | 1116 | # To avoid keeping stale modules around (we only need the one from the |
|
1115 | 1117 | # last run), we use a dict keyed with the full path to the script, so |
|
1116 | 1118 | # only the last version of the module is held in the cache. Note, |
|
1117 | 1119 | # however, that we must cache the module *namespace contents* (their |
|
1118 | 1120 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1119 | 1121 | # (uncached) could be destroyed while still holding references (such as |
|
1120 | 1122 | # those held by GUI objects that tend to be long-lived)> |
|
1121 | 1123 | # |
|
1122 | 1124 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1123 | 1125 | # and clear_main_mod_cache() methods for details on use. |
|
1124 | 1126 | |
|
1125 | 1127 | # This is the cache used for 'main' namespaces |
|
1126 | 1128 | self._main_mod_cache = {} |
|
1127 | 1129 | |
|
1128 | 1130 | # A table holding all the namespaces IPython deals with, so that |
|
1129 | 1131 | # introspection facilities can search easily. |
|
1130 | 1132 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1131 | 1133 | 'user_local':self.user_ns, |
|
1132 | 1134 | 'builtin':builtin_mod.__dict__ |
|
1133 | 1135 | } |
|
1134 | 1136 | |
|
1135 | 1137 | @property |
|
1136 | 1138 | def user_global_ns(self): |
|
1137 | 1139 | return self.user_module.__dict__ |
|
1138 | 1140 | |
|
1139 | 1141 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1140 | 1142 | """Prepare the module and namespace in which user code will be run. |
|
1141 | 1143 | |
|
1142 | 1144 | When IPython is started normally, both parameters are None: a new module |
|
1143 | 1145 | is created automatically, and its __dict__ used as the namespace. |
|
1144 | 1146 | |
|
1145 | 1147 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1146 | 1148 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1147 | 1149 | becomes the global namespace. If both are provided (as they may be |
|
1148 | 1150 | when embedding), user_ns is the local namespace, and user_module |
|
1149 | 1151 | provides the global namespace. |
|
1150 | 1152 | |
|
1151 | 1153 | Parameters |
|
1152 | 1154 | ---------- |
|
1153 | 1155 | user_module : module, optional |
|
1154 | 1156 | The current user module in which IPython is being run. If None, |
|
1155 | 1157 | a clean module will be created. |
|
1156 | 1158 | user_ns : dict, optional |
|
1157 | 1159 | A namespace in which to run interactive commands. |
|
1158 | 1160 | |
|
1159 | 1161 | Returns |
|
1160 | 1162 | ------- |
|
1161 | 1163 | A tuple of user_module and user_ns, each properly initialised. |
|
1162 | 1164 | """ |
|
1163 | 1165 | if user_module is None and user_ns is not None: |
|
1164 | 1166 | user_ns.setdefault("__name__", "__main__") |
|
1165 | 1167 | user_module = DummyMod() |
|
1166 | 1168 | user_module.__dict__ = user_ns |
|
1167 | 1169 | |
|
1168 | 1170 | if user_module is None: |
|
1169 | 1171 | user_module = types.ModuleType("__main__", |
|
1170 | 1172 | doc="Automatically created module for IPython interactive environment") |
|
1171 | 1173 | |
|
1172 | 1174 | # We must ensure that __builtin__ (without the final 's') is always |
|
1173 | 1175 | # available and pointing to the __builtin__ *module*. For more details: |
|
1174 | 1176 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1175 | 1177 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1176 | 1178 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1177 | 1179 | |
|
1178 | 1180 | if user_ns is None: |
|
1179 | 1181 | user_ns = user_module.__dict__ |
|
1180 | 1182 | |
|
1181 | 1183 | return user_module, user_ns |
|
1182 | 1184 | |
|
1183 | 1185 | def init_sys_modules(self): |
|
1184 | 1186 | # We need to insert into sys.modules something that looks like a |
|
1185 | 1187 | # module but which accesses the IPython namespace, for shelve and |
|
1186 | 1188 | # pickle to work interactively. Normally they rely on getting |
|
1187 | 1189 | # everything out of __main__, but for embedding purposes each IPython |
|
1188 | 1190 | # instance has its own private namespace, so we can't go shoving |
|
1189 | 1191 | # everything into __main__. |
|
1190 | 1192 | |
|
1191 | 1193 | # note, however, that we should only do this for non-embedded |
|
1192 | 1194 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1193 | 1195 | # namespace. Embedded instances, on the other hand, should not do |
|
1194 | 1196 | # this because they need to manage the user local/global namespaces |
|
1195 | 1197 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1196 | 1198 | # shouldn't overtake the execution environment of the script they're |
|
1197 | 1199 | # embedded in). |
|
1198 | 1200 | |
|
1199 | 1201 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1200 | 1202 | main_name = self.user_module.__name__ |
|
1201 | 1203 | sys.modules[main_name] = self.user_module |
|
1202 | 1204 | |
|
1203 | 1205 | def init_user_ns(self): |
|
1204 | 1206 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1205 | 1207 | |
|
1206 | 1208 | Certain history lists are also initialized here, as they effectively |
|
1207 | 1209 | act as user namespaces. |
|
1208 | 1210 | |
|
1209 | 1211 | Notes |
|
1210 | 1212 | ----- |
|
1211 | 1213 | All data structures here are only filled in, they are NOT reset by this |
|
1212 | 1214 | method. If they were not empty before, data will simply be added to |
|
1213 | 1215 | therm. |
|
1214 | 1216 | """ |
|
1215 | 1217 | # This function works in two parts: first we put a few things in |
|
1216 | 1218 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1217 | 1219 | # initial variables aren't shown by %who. After the sync, we add the |
|
1218 | 1220 | # rest of what we *do* want the user to see with %who even on a new |
|
1219 | 1221 | # session (probably nothing, so they really only see their own stuff) |
|
1220 | 1222 | |
|
1221 | 1223 | # The user dict must *always* have a __builtin__ reference to the |
|
1222 | 1224 | # Python standard __builtin__ namespace, which must be imported. |
|
1223 | 1225 | # This is so that certain operations in prompt evaluation can be |
|
1224 | 1226 | # reliably executed with builtins. Note that we can NOT use |
|
1225 | 1227 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1226 | 1228 | # module, and can even mutate at runtime, depending on the context |
|
1227 | 1229 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1228 | 1230 | # always a module object, though it must be explicitly imported. |
|
1229 | 1231 | |
|
1230 | 1232 | # For more details: |
|
1231 | 1233 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1232 | 1234 | ns = dict() |
|
1233 | 1235 | |
|
1234 | 1236 | # make global variables for user access to the histories |
|
1235 | 1237 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1236 | 1238 | ns['_oh'] = self.history_manager.output_hist |
|
1237 | 1239 | ns['_dh'] = self.history_manager.dir_hist |
|
1238 | 1240 | |
|
1239 | 1241 | ns['_sh'] = shadowns |
|
1240 | 1242 | |
|
1241 | 1243 | # user aliases to input and output histories. These shouldn't show up |
|
1242 | 1244 | # in %who, as they can have very large reprs. |
|
1243 | 1245 | ns['In'] = self.history_manager.input_hist_parsed |
|
1244 | 1246 | ns['Out'] = self.history_manager.output_hist |
|
1245 | 1247 | |
|
1246 | 1248 | # Store myself as the public api!!! |
|
1247 | 1249 | ns['get_ipython'] = self.get_ipython |
|
1248 | 1250 | |
|
1249 | 1251 | ns['exit'] = self.exiter |
|
1250 | 1252 | ns['quit'] = self.exiter |
|
1251 | 1253 | |
|
1252 | 1254 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1253 | 1255 | # by %who |
|
1254 | 1256 | self.user_ns_hidden.update(ns) |
|
1255 | 1257 | |
|
1256 | 1258 | # Anything put into ns now would show up in %who. Think twice before |
|
1257 | 1259 | # putting anything here, as we really want %who to show the user their |
|
1258 | 1260 | # stuff, not our variables. |
|
1259 | 1261 | |
|
1260 | 1262 | # Finally, update the real user's namespace |
|
1261 | 1263 | self.user_ns.update(ns) |
|
1262 | 1264 | |
|
1263 | 1265 | @property |
|
1264 | 1266 | def all_ns_refs(self): |
|
1265 | 1267 | """Get a list of references to all the namespace dictionaries in which |
|
1266 | 1268 | IPython might store a user-created object. |
|
1267 | 1269 | |
|
1268 | 1270 | Note that this does not include the displayhook, which also caches |
|
1269 | 1271 | objects from the output.""" |
|
1270 | 1272 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1271 | 1273 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1272 | 1274 | |
|
1273 | 1275 | def reset(self, new_session=True): |
|
1274 | 1276 | """Clear all internal namespaces, and attempt to release references to |
|
1275 | 1277 | user objects. |
|
1276 | 1278 | |
|
1277 | 1279 | If new_session is True, a new history session will be opened. |
|
1278 | 1280 | """ |
|
1279 | 1281 | # Clear histories |
|
1280 | 1282 | self.history_manager.reset(new_session) |
|
1281 | 1283 | # Reset counter used to index all histories |
|
1282 | 1284 | if new_session: |
|
1283 | 1285 | self.execution_count = 1 |
|
1284 | 1286 | |
|
1285 | 1287 | # Flush cached output items |
|
1286 | 1288 | if self.displayhook.do_full_cache: |
|
1287 | 1289 | self.displayhook.flush() |
|
1288 | 1290 | |
|
1289 | 1291 | # The main execution namespaces must be cleared very carefully, |
|
1290 | 1292 | # skipping the deletion of the builtin-related keys, because doing so |
|
1291 | 1293 | # would cause errors in many object's __del__ methods. |
|
1292 | 1294 | if self.user_ns is not self.user_global_ns: |
|
1293 | 1295 | self.user_ns.clear() |
|
1294 | 1296 | ns = self.user_global_ns |
|
1295 | 1297 | drop_keys = set(ns.keys()) |
|
1296 | 1298 | drop_keys.discard('__builtin__') |
|
1297 | 1299 | drop_keys.discard('__builtins__') |
|
1298 | 1300 | drop_keys.discard('__name__') |
|
1299 | 1301 | for k in drop_keys: |
|
1300 | 1302 | del ns[k] |
|
1301 | 1303 | |
|
1302 | 1304 | self.user_ns_hidden.clear() |
|
1303 | 1305 | |
|
1304 | 1306 | # Restore the user namespaces to minimal usability |
|
1305 | 1307 | self.init_user_ns() |
|
1306 | 1308 | |
|
1307 | 1309 | # Restore the default and user aliases |
|
1308 | 1310 | self.alias_manager.clear_aliases() |
|
1309 | 1311 | self.alias_manager.init_aliases() |
|
1310 | 1312 | |
|
1311 | 1313 | # Flush the private list of module references kept for script |
|
1312 | 1314 | # execution protection |
|
1313 | 1315 | self.clear_main_mod_cache() |
|
1314 | 1316 | |
|
1315 | 1317 | def del_var(self, varname, by_name=False): |
|
1316 | 1318 | """Delete a variable from the various namespaces, so that, as |
|
1317 | 1319 | far as possible, we're not keeping any hidden references to it. |
|
1318 | 1320 | |
|
1319 | 1321 | Parameters |
|
1320 | 1322 | ---------- |
|
1321 | 1323 | varname : str |
|
1322 | 1324 | The name of the variable to delete. |
|
1323 | 1325 | by_name : bool |
|
1324 | 1326 | If True, delete variables with the given name in each |
|
1325 | 1327 | namespace. If False (default), find the variable in the user |
|
1326 | 1328 | namespace, and delete references to it. |
|
1327 | 1329 | """ |
|
1328 | 1330 | if varname in ('__builtin__', '__builtins__'): |
|
1329 | 1331 | raise ValueError("Refusing to delete %s" % varname) |
|
1330 | 1332 | |
|
1331 | 1333 | ns_refs = self.all_ns_refs |
|
1332 | 1334 | |
|
1333 | 1335 | if by_name: # Delete by name |
|
1334 | 1336 | for ns in ns_refs: |
|
1335 | 1337 | try: |
|
1336 | 1338 | del ns[varname] |
|
1337 | 1339 | except KeyError: |
|
1338 | 1340 | pass |
|
1339 | 1341 | else: # Delete by object |
|
1340 | 1342 | try: |
|
1341 | 1343 | obj = self.user_ns[varname] |
|
1342 | 1344 | except KeyError: |
|
1343 | 1345 | raise NameError("name '%s' is not defined" % varname) |
|
1344 | 1346 | # Also check in output history |
|
1345 | 1347 | ns_refs.append(self.history_manager.output_hist) |
|
1346 | 1348 | for ns in ns_refs: |
|
1347 | 1349 | to_delete = [n for n, o in iteritems(ns) if o is obj] |
|
1348 | 1350 | for name in to_delete: |
|
1349 | 1351 | del ns[name] |
|
1350 | 1352 | |
|
1351 | 1353 | # displayhook keeps extra references, but not in a dictionary |
|
1352 | 1354 | for name in ('_', '__', '___'): |
|
1353 | 1355 | if getattr(self.displayhook, name) is obj: |
|
1354 | 1356 | setattr(self.displayhook, name, None) |
|
1355 | 1357 | |
|
1356 | 1358 | def reset_selective(self, regex=None): |
|
1357 | 1359 | """Clear selective variables from internal namespaces based on a |
|
1358 | 1360 | specified regular expression. |
|
1359 | 1361 | |
|
1360 | 1362 | Parameters |
|
1361 | 1363 | ---------- |
|
1362 | 1364 | regex : string or compiled pattern, optional |
|
1363 | 1365 | A regular expression pattern that will be used in searching |
|
1364 | 1366 | variable names in the users namespaces. |
|
1365 | 1367 | """ |
|
1366 | 1368 | if regex is not None: |
|
1367 | 1369 | try: |
|
1368 | 1370 | m = re.compile(regex) |
|
1369 | 1371 | except TypeError: |
|
1370 | 1372 | raise TypeError('regex must be a string or compiled pattern') |
|
1371 | 1373 | # Search for keys in each namespace that match the given regex |
|
1372 | 1374 | # If a match is found, delete the key/value pair. |
|
1373 | 1375 | for ns in self.all_ns_refs: |
|
1374 | 1376 | for var in ns: |
|
1375 | 1377 | if m.search(var): |
|
1376 | 1378 | del ns[var] |
|
1377 | 1379 | |
|
1378 | 1380 | def push(self, variables, interactive=True): |
|
1379 | 1381 | """Inject a group of variables into the IPython user namespace. |
|
1380 | 1382 | |
|
1381 | 1383 | Parameters |
|
1382 | 1384 | ---------- |
|
1383 | 1385 | variables : dict, str or list/tuple of str |
|
1384 | 1386 | The variables to inject into the user's namespace. If a dict, a |
|
1385 | 1387 | simple update is done. If a str, the string is assumed to have |
|
1386 | 1388 | variable names separated by spaces. A list/tuple of str can also |
|
1387 | 1389 | be used to give the variable names. If just the variable names are |
|
1388 | 1390 | give (list/tuple/str) then the variable values looked up in the |
|
1389 | 1391 | callers frame. |
|
1390 | 1392 | interactive : bool |
|
1391 | 1393 | If True (default), the variables will be listed with the ``who`` |
|
1392 | 1394 | magic. |
|
1393 | 1395 | """ |
|
1394 | 1396 | vdict = None |
|
1395 | 1397 | |
|
1396 | 1398 | # We need a dict of name/value pairs to do namespace updates. |
|
1397 | 1399 | if isinstance(variables, dict): |
|
1398 | 1400 | vdict = variables |
|
1399 | 1401 | elif isinstance(variables, string_types+(list, tuple)): |
|
1400 | 1402 | if isinstance(variables, string_types): |
|
1401 | 1403 | vlist = variables.split() |
|
1402 | 1404 | else: |
|
1403 | 1405 | vlist = variables |
|
1404 | 1406 | vdict = {} |
|
1405 | 1407 | cf = sys._getframe(1) |
|
1406 | 1408 | for name in vlist: |
|
1407 | 1409 | try: |
|
1408 | 1410 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1409 | 1411 | except: |
|
1410 | 1412 | print('Could not get variable %s from %s' % |
|
1411 | 1413 | (name,cf.f_code.co_name)) |
|
1412 | 1414 | else: |
|
1413 | 1415 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1414 | 1416 | |
|
1415 | 1417 | # Propagate variables to user namespace |
|
1416 | 1418 | self.user_ns.update(vdict) |
|
1417 | 1419 | |
|
1418 | 1420 | # And configure interactive visibility |
|
1419 | 1421 | user_ns_hidden = self.user_ns_hidden |
|
1420 | 1422 | if interactive: |
|
1421 | 1423 | for name in vdict: |
|
1422 | 1424 | user_ns_hidden.pop(name, None) |
|
1423 | 1425 | else: |
|
1424 | 1426 | user_ns_hidden.update(vdict) |
|
1425 | 1427 | |
|
1426 | 1428 | def drop_by_id(self, variables): |
|
1427 | 1429 | """Remove a dict of variables from the user namespace, if they are the |
|
1428 | 1430 | same as the values in the dictionary. |
|
1429 | 1431 | |
|
1430 | 1432 | This is intended for use by extensions: variables that they've added can |
|
1431 | 1433 | be taken back out if they are unloaded, without removing any that the |
|
1432 | 1434 | user has overwritten. |
|
1433 | 1435 | |
|
1434 | 1436 | Parameters |
|
1435 | 1437 | ---------- |
|
1436 | 1438 | variables : dict |
|
1437 | 1439 | A dictionary mapping object names (as strings) to the objects. |
|
1438 | 1440 | """ |
|
1439 | 1441 | for name, obj in iteritems(variables): |
|
1440 | 1442 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1441 | 1443 | del self.user_ns[name] |
|
1442 | 1444 | self.user_ns_hidden.pop(name, None) |
|
1443 | 1445 | |
|
1444 | 1446 | #------------------------------------------------------------------------- |
|
1445 | 1447 | # Things related to object introspection |
|
1446 | 1448 | #------------------------------------------------------------------------- |
|
1447 | 1449 | |
|
1448 | 1450 | def _ofind(self, oname, namespaces=None): |
|
1449 | 1451 | """Find an object in the available namespaces. |
|
1450 | 1452 | |
|
1451 | 1453 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1452 | 1454 | |
|
1453 | 1455 | Has special code to detect magic functions. |
|
1454 | 1456 | """ |
|
1455 | 1457 | oname = oname.strip() |
|
1456 | 1458 | #print '1- oname: <%r>' % oname # dbg |
|
1457 | 1459 | if not oname.startswith(ESC_MAGIC) and \ |
|
1458 | 1460 | not oname.startswith(ESC_MAGIC2) and \ |
|
1459 | 1461 | not py3compat.isidentifier(oname, dotted=True): |
|
1460 | 1462 | return dict(found=False) |
|
1461 | 1463 | |
|
1462 | 1464 | if namespaces is None: |
|
1463 | 1465 | # Namespaces to search in: |
|
1464 | 1466 | # Put them in a list. The order is important so that we |
|
1465 | 1467 | # find things in the same order that Python finds them. |
|
1466 | 1468 | namespaces = [ ('Interactive', self.user_ns), |
|
1467 | 1469 | ('Interactive (global)', self.user_global_ns), |
|
1468 | 1470 | ('Python builtin', builtin_mod.__dict__), |
|
1469 | 1471 | ] |
|
1470 | 1472 | |
|
1471 | 1473 | # initialize results to 'null' |
|
1472 | 1474 | found = False; obj = None; ospace = None; |
|
1473 | 1475 | ismagic = False; isalias = False; parent = None |
|
1474 | 1476 | |
|
1475 | 1477 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1476 | 1478 | # function but should only be treated as one if print_function was |
|
1477 | 1479 | # loaded with a future import. In this case, just bail. |
|
1478 | 1480 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1479 | 1481 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1480 | 1482 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1481 | 1483 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1482 | 1484 | |
|
1483 | 1485 | # Look for the given name by splitting it in parts. If the head is |
|
1484 | 1486 | # found, then we look for all the remaining parts as members, and only |
|
1485 | 1487 | # declare success if we can find them all. |
|
1486 | 1488 | oname_parts = oname.split('.') |
|
1487 | 1489 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1488 | 1490 | for nsname,ns in namespaces: |
|
1489 | 1491 | try: |
|
1490 | 1492 | obj = ns[oname_head] |
|
1491 | 1493 | except KeyError: |
|
1492 | 1494 | continue |
|
1493 | 1495 | else: |
|
1494 | 1496 | #print 'oname_rest:', oname_rest # dbg |
|
1495 | 1497 | for idx, part in enumerate(oname_rest): |
|
1496 | 1498 | try: |
|
1497 | 1499 | parent = obj |
|
1498 | 1500 | # The last part is looked up in a special way to avoid |
|
1499 | 1501 | # descriptor invocation as it may raise or have side |
|
1500 | 1502 | # effects. |
|
1501 | 1503 | if idx == len(oname_rest) - 1: |
|
1502 | 1504 | obj = self._getattr_property(obj, part) |
|
1503 | 1505 | else: |
|
1504 | 1506 | obj = getattr(obj, part) |
|
1505 | 1507 | except: |
|
1506 | 1508 | # Blanket except b/c some badly implemented objects |
|
1507 | 1509 | # allow __getattr__ to raise exceptions other than |
|
1508 | 1510 | # AttributeError, which then crashes IPython. |
|
1509 | 1511 | break |
|
1510 | 1512 | else: |
|
1511 | 1513 | # If we finish the for loop (no break), we got all members |
|
1512 | 1514 | found = True |
|
1513 | 1515 | ospace = nsname |
|
1514 | 1516 | break # namespace loop |
|
1515 | 1517 | |
|
1516 | 1518 | # Try to see if it's magic |
|
1517 | 1519 | if not found: |
|
1518 | 1520 | obj = None |
|
1519 | 1521 | if oname.startswith(ESC_MAGIC2): |
|
1520 | 1522 | oname = oname.lstrip(ESC_MAGIC2) |
|
1521 | 1523 | obj = self.find_cell_magic(oname) |
|
1522 | 1524 | elif oname.startswith(ESC_MAGIC): |
|
1523 | 1525 | oname = oname.lstrip(ESC_MAGIC) |
|
1524 | 1526 | obj = self.find_line_magic(oname) |
|
1525 | 1527 | else: |
|
1526 | 1528 | # search without prefix, so run? will find %run? |
|
1527 | 1529 | obj = self.find_line_magic(oname) |
|
1528 | 1530 | if obj is None: |
|
1529 | 1531 | obj = self.find_cell_magic(oname) |
|
1530 | 1532 | if obj is not None: |
|
1531 | 1533 | found = True |
|
1532 | 1534 | ospace = 'IPython internal' |
|
1533 | 1535 | ismagic = True |
|
1534 | 1536 | isalias = isinstance(obj, Alias) |
|
1535 | 1537 | |
|
1536 | 1538 | # Last try: special-case some literals like '', [], {}, etc: |
|
1537 | 1539 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1538 | 1540 | obj = eval(oname_head) |
|
1539 | 1541 | found = True |
|
1540 | 1542 | ospace = 'Interactive' |
|
1541 | 1543 | |
|
1542 | 1544 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1543 | 1545 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1544 | 1546 | |
|
1545 | 1547 | @staticmethod |
|
1546 | 1548 | def _getattr_property(obj, attrname): |
|
1547 | 1549 | """Property-aware getattr to use in object finding. |
|
1548 | 1550 | |
|
1549 | 1551 | If attrname represents a property, return it unevaluated (in case it has |
|
1550 | 1552 | side effects or raises an error. |
|
1551 | 1553 | |
|
1552 | 1554 | """ |
|
1553 | 1555 | if not isinstance(obj, type): |
|
1554 | 1556 | try: |
|
1555 | 1557 | # `getattr(type(obj), attrname)` is not guaranteed to return |
|
1556 | 1558 | # `obj`, but does so for property: |
|
1557 | 1559 | # |
|
1558 | 1560 | # property.__get__(self, None, cls) -> self |
|
1559 | 1561 | # |
|
1560 | 1562 | # The universal alternative is to traverse the mro manually |
|
1561 | 1563 | # searching for attrname in class dicts. |
|
1562 | 1564 | attr = getattr(type(obj), attrname) |
|
1563 | 1565 | except AttributeError: |
|
1564 | 1566 | pass |
|
1565 | 1567 | else: |
|
1566 | 1568 | # This relies on the fact that data descriptors (with both |
|
1567 | 1569 | # __get__ & __set__ magic methods) take precedence over |
|
1568 | 1570 | # instance-level attributes: |
|
1569 | 1571 | # |
|
1570 | 1572 | # class A(object): |
|
1571 | 1573 | # @property |
|
1572 | 1574 | # def foobar(self): return 123 |
|
1573 | 1575 | # a = A() |
|
1574 | 1576 | # a.__dict__['foobar'] = 345 |
|
1575 | 1577 | # a.foobar # == 123 |
|
1576 | 1578 | # |
|
1577 | 1579 | # So, a property may be returned right away. |
|
1578 | 1580 | if isinstance(attr, property): |
|
1579 | 1581 | return attr |
|
1580 | 1582 | |
|
1581 | 1583 | # Nothing helped, fall back. |
|
1582 | 1584 | return getattr(obj, attrname) |
|
1583 | 1585 | |
|
1584 | 1586 | def _object_find(self, oname, namespaces=None): |
|
1585 | 1587 | """Find an object and return a struct with info about it.""" |
|
1586 | 1588 | return Struct(self._ofind(oname, namespaces)) |
|
1587 | 1589 | |
|
1588 | 1590 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1589 | 1591 | """Generic interface to the inspector system. |
|
1590 | 1592 | |
|
1591 | 1593 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1592 | 1594 | info = self._object_find(oname, namespaces) |
|
1593 | 1595 | if info.found: |
|
1594 | 1596 | pmethod = getattr(self.inspector, meth) |
|
1595 | 1597 | formatter = format_screen if info.ismagic else None |
|
1596 | 1598 | if meth == 'pdoc': |
|
1597 | 1599 | pmethod(info.obj, oname, formatter) |
|
1598 | 1600 | elif meth == 'pinfo': |
|
1599 | 1601 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1600 | 1602 | else: |
|
1601 | 1603 | pmethod(info.obj, oname) |
|
1602 | 1604 | else: |
|
1603 | 1605 | print('Object `%s` not found.' % oname) |
|
1604 | 1606 | return 'not found' # so callers can take other action |
|
1605 | 1607 | |
|
1606 | 1608 | def object_inspect(self, oname, detail_level=0): |
|
1607 | 1609 | """Get object info about oname""" |
|
1608 | 1610 | with self.builtin_trap: |
|
1609 | 1611 | info = self._object_find(oname) |
|
1610 | 1612 | if info.found: |
|
1611 | 1613 | return self.inspector.info(info.obj, oname, info=info, |
|
1612 | 1614 | detail_level=detail_level |
|
1613 | 1615 | ) |
|
1614 | 1616 | else: |
|
1615 | 1617 | return oinspect.object_info(name=oname, found=False) |
|
1616 | 1618 | |
|
1617 | 1619 | def object_inspect_text(self, oname, detail_level=0): |
|
1618 | 1620 | """Get object info as formatted text""" |
|
1619 | 1621 | with self.builtin_trap: |
|
1620 | 1622 | info = self._object_find(oname) |
|
1621 | 1623 | if info.found: |
|
1622 | 1624 | return self.inspector._format_info(info.obj, oname, info=info, |
|
1623 | 1625 | detail_level=detail_level |
|
1624 | 1626 | ) |
|
1625 | 1627 | else: |
|
1626 | 1628 | raise KeyError(oname) |
|
1627 | 1629 | |
|
1628 | 1630 | #------------------------------------------------------------------------- |
|
1629 | 1631 | # Things related to history management |
|
1630 | 1632 | #------------------------------------------------------------------------- |
|
1631 | 1633 | |
|
1632 | 1634 | def init_history(self): |
|
1633 | 1635 | """Sets up the command history, and starts regular autosaves.""" |
|
1634 | 1636 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1635 | 1637 | self.configurables.append(self.history_manager) |
|
1636 | 1638 | |
|
1637 | 1639 | #------------------------------------------------------------------------- |
|
1638 | 1640 | # Things related to exception handling and tracebacks (not debugging) |
|
1639 | 1641 | #------------------------------------------------------------------------- |
|
1640 | 1642 | |
|
1641 | 1643 | def init_traceback_handlers(self, custom_exceptions): |
|
1642 | 1644 | # Syntax error handler. |
|
1643 | 1645 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1644 | 1646 | |
|
1645 | 1647 | # The interactive one is initialized with an offset, meaning we always |
|
1646 | 1648 | # want to remove the topmost item in the traceback, which is our own |
|
1647 | 1649 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1648 | 1650 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1649 | 1651 | color_scheme='NoColor', |
|
1650 | 1652 | tb_offset = 1, |
|
1651 | 1653 | check_cache=check_linecache_ipython) |
|
1652 | 1654 | |
|
1653 | 1655 | # The instance will store a pointer to the system-wide exception hook, |
|
1654 | 1656 | # so that runtime code (such as magics) can access it. This is because |
|
1655 | 1657 | # during the read-eval loop, it may get temporarily overwritten. |
|
1656 | 1658 | self.sys_excepthook = sys.excepthook |
|
1657 | 1659 | |
|
1658 | 1660 | # and add any custom exception handlers the user may have specified |
|
1659 | 1661 | self.set_custom_exc(*custom_exceptions) |
|
1660 | 1662 | |
|
1661 | 1663 | # Set the exception mode |
|
1662 | 1664 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1663 | 1665 | |
|
1664 | 1666 | def set_custom_exc(self, exc_tuple, handler): |
|
1665 | 1667 | """set_custom_exc(exc_tuple,handler) |
|
1666 | 1668 | |
|
1667 | 1669 | Set a custom exception handler, which will be called if any of the |
|
1668 | 1670 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1669 | 1671 | run_code() method). |
|
1670 | 1672 | |
|
1671 | 1673 | Parameters |
|
1672 | 1674 | ---------- |
|
1673 | 1675 | |
|
1674 | 1676 | exc_tuple : tuple of exception classes |
|
1675 | 1677 | A *tuple* of exception classes, for which to call the defined |
|
1676 | 1678 | handler. It is very important that you use a tuple, and NOT A |
|
1677 | 1679 | LIST here, because of the way Python's except statement works. If |
|
1678 | 1680 | you only want to trap a single exception, use a singleton tuple:: |
|
1679 | 1681 | |
|
1680 | 1682 | exc_tuple == (MyCustomException,) |
|
1681 | 1683 | |
|
1682 | 1684 | handler : callable |
|
1683 | 1685 | handler must have the following signature:: |
|
1684 | 1686 | |
|
1685 | 1687 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1686 | 1688 | ... |
|
1687 | 1689 | return structured_traceback |
|
1688 | 1690 | |
|
1689 | 1691 | Your handler must return a structured traceback (a list of strings), |
|
1690 | 1692 | or None. |
|
1691 | 1693 | |
|
1692 | 1694 | This will be made into an instance method (via types.MethodType) |
|
1693 | 1695 | of IPython itself, and it will be called if any of the exceptions |
|
1694 | 1696 | listed in the exc_tuple are caught. If the handler is None, an |
|
1695 | 1697 | internal basic one is used, which just prints basic info. |
|
1696 | 1698 | |
|
1697 | 1699 | To protect IPython from crashes, if your handler ever raises an |
|
1698 | 1700 | exception or returns an invalid result, it will be immediately |
|
1699 | 1701 | disabled. |
|
1700 | 1702 | |
|
1701 | 1703 | WARNING: by putting in your own exception handler into IPython's main |
|
1702 | 1704 | execution loop, you run a very good chance of nasty crashes. This |
|
1703 | 1705 | facility should only be used if you really know what you are doing.""" |
|
1704 | 1706 | |
|
1705 | 1707 | assert type(exc_tuple)==type(()) , \ |
|
1706 | 1708 | "The custom exceptions must be given AS A TUPLE." |
|
1707 | 1709 | |
|
1708 | 1710 | def dummy_handler(self,etype,value,tb,tb_offset=None): |
|
1709 | 1711 | print('*** Simple custom exception handler ***') |
|
1710 | 1712 | print('Exception type :',etype) |
|
1711 | 1713 | print('Exception value:',value) |
|
1712 | 1714 | print('Traceback :',tb) |
|
1713 | 1715 | #print 'Source code :','\n'.join(self.buffer) |
|
1714 | 1716 | |
|
1715 | 1717 | def validate_stb(stb): |
|
1716 | 1718 | """validate structured traceback return type |
|
1717 | 1719 | |
|
1718 | 1720 | return type of CustomTB *should* be a list of strings, but allow |
|
1719 | 1721 | single strings or None, which are harmless. |
|
1720 | 1722 | |
|
1721 | 1723 | This function will *always* return a list of strings, |
|
1722 | 1724 | and will raise a TypeError if stb is inappropriate. |
|
1723 | 1725 | """ |
|
1724 | 1726 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1725 | 1727 | if stb is None: |
|
1726 | 1728 | return [] |
|
1727 | 1729 | elif isinstance(stb, string_types): |
|
1728 | 1730 | return [stb] |
|
1729 | 1731 | elif not isinstance(stb, list): |
|
1730 | 1732 | raise TypeError(msg) |
|
1731 | 1733 | # it's a list |
|
1732 | 1734 | for line in stb: |
|
1733 | 1735 | # check every element |
|
1734 | 1736 | if not isinstance(line, string_types): |
|
1735 | 1737 | raise TypeError(msg) |
|
1736 | 1738 | return stb |
|
1737 | 1739 | |
|
1738 | 1740 | if handler is None: |
|
1739 | 1741 | wrapped = dummy_handler |
|
1740 | 1742 | else: |
|
1741 | 1743 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1742 | 1744 | """wrap CustomTB handler, to protect IPython from user code |
|
1743 | 1745 | |
|
1744 | 1746 | This makes it harder (but not impossible) for custom exception |
|
1745 | 1747 | handlers to crash IPython. |
|
1746 | 1748 | """ |
|
1747 | 1749 | try: |
|
1748 | 1750 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1749 | 1751 | return validate_stb(stb) |
|
1750 | 1752 | except: |
|
1751 | 1753 | # clear custom handler immediately |
|
1752 | 1754 | self.set_custom_exc((), None) |
|
1753 | 1755 | print("Custom TB Handler failed, unregistering", file=io.stderr) |
|
1754 | 1756 | # show the exception in handler first |
|
1755 | 1757 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1756 | 1758 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1757 | 1759 | print("The original exception:", file=io.stdout) |
|
1758 | 1760 | stb = self.InteractiveTB.structured_traceback( |
|
1759 | 1761 | (etype,value,tb), tb_offset=tb_offset |
|
1760 | 1762 | ) |
|
1761 | 1763 | return stb |
|
1762 | 1764 | |
|
1763 | 1765 | self.CustomTB = types.MethodType(wrapped,self) |
|
1764 | 1766 | self.custom_exceptions = exc_tuple |
|
1765 | 1767 | |
|
1766 | 1768 | def excepthook(self, etype, value, tb): |
|
1767 | 1769 | """One more defense for GUI apps that call sys.excepthook. |
|
1768 | 1770 | |
|
1769 | 1771 | GUI frameworks like wxPython trap exceptions and call |
|
1770 | 1772 | sys.excepthook themselves. I guess this is a feature that |
|
1771 | 1773 | enables them to keep running after exceptions that would |
|
1772 | 1774 | otherwise kill their mainloop. This is a bother for IPython |
|
1773 | 1775 | which excepts to catch all of the program exceptions with a try: |
|
1774 | 1776 | except: statement. |
|
1775 | 1777 | |
|
1776 | 1778 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1777 | 1779 | any app directly invokes sys.excepthook, it will look to the user like |
|
1778 | 1780 | IPython crashed. In order to work around this, we can disable the |
|
1779 | 1781 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1780 | 1782 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1781 | 1783 | call sys.excepthook will generate a regular-looking exception from |
|
1782 | 1784 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1783 | 1785 | crashes. |
|
1784 | 1786 | |
|
1785 | 1787 | This hook should be used sparingly, only in places which are not likely |
|
1786 | 1788 | to be true IPython errors. |
|
1787 | 1789 | """ |
|
1788 | 1790 | self.showtraceback((etype, value, tb), tb_offset=0) |
|
1789 | 1791 | |
|
1790 | 1792 | def _get_exc_info(self, exc_tuple=None): |
|
1791 | 1793 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1792 | 1794 | |
|
1793 | 1795 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1794 | 1796 | from whichever source. |
|
1795 | 1797 | |
|
1796 | 1798 | raises ValueError if none of these contain any information |
|
1797 | 1799 | """ |
|
1798 | 1800 | if exc_tuple is None: |
|
1799 | 1801 | etype, value, tb = sys.exc_info() |
|
1800 | 1802 | else: |
|
1801 | 1803 | etype, value, tb = exc_tuple |
|
1802 | 1804 | |
|
1803 | 1805 | if etype is None: |
|
1804 | 1806 | if hasattr(sys, 'last_type'): |
|
1805 | 1807 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1806 | 1808 | sys.last_traceback |
|
1807 | 1809 | |
|
1808 | 1810 | if etype is None: |
|
1809 | 1811 | raise ValueError("No exception to find") |
|
1810 | 1812 | |
|
1811 | 1813 | # Now store the exception info in sys.last_type etc. |
|
1812 | 1814 | # WARNING: these variables are somewhat deprecated and not |
|
1813 | 1815 | # necessarily safe to use in a threaded environment, but tools |
|
1814 | 1816 | # like pdb depend on their existence, so let's set them. If we |
|
1815 | 1817 | # find problems in the field, we'll need to revisit their use. |
|
1816 | 1818 | sys.last_type = etype |
|
1817 | 1819 | sys.last_value = value |
|
1818 | 1820 | sys.last_traceback = tb |
|
1819 | 1821 | |
|
1820 | 1822 | return etype, value, tb |
|
1821 | 1823 | |
|
1822 | 1824 | def show_usage_error(self, exc): |
|
1823 | 1825 | """Show a short message for UsageErrors |
|
1824 | 1826 | |
|
1825 | 1827 | These are special exceptions that shouldn't show a traceback. |
|
1826 | 1828 | """ |
|
1827 | 1829 | self.write_err("UsageError: %s" % exc) |
|
1828 | 1830 | |
|
1829 | 1831 | def get_exception_only(self, exc_tuple=None): |
|
1830 | 1832 | """ |
|
1831 | 1833 | Return as a string (ending with a newline) the exception that |
|
1832 | 1834 | just occurred, without any traceback. |
|
1833 | 1835 | """ |
|
1834 | 1836 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1835 | 1837 | msg = traceback.format_exception_only(etype, value) |
|
1836 | 1838 | return ''.join(msg) |
|
1837 | 1839 | |
|
1838 | 1840 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, |
|
1839 | 1841 | exception_only=False): |
|
1840 | 1842 | """Display the exception that just occurred. |
|
1841 | 1843 | |
|
1842 | 1844 | If nothing is known about the exception, this is the method which |
|
1843 | 1845 | should be used throughout the code for presenting user tracebacks, |
|
1844 | 1846 | rather than directly invoking the InteractiveTB object. |
|
1845 | 1847 | |
|
1846 | 1848 | A specific showsyntaxerror() also exists, but this method can take |
|
1847 | 1849 | care of calling it if needed, so unless you are explicitly catching a |
|
1848 | 1850 | SyntaxError exception, don't try to analyze the stack manually and |
|
1849 | 1851 | simply call this method.""" |
|
1850 | 1852 | |
|
1851 | 1853 | try: |
|
1852 | 1854 | try: |
|
1853 | 1855 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1854 | 1856 | except ValueError: |
|
1855 | 1857 | self.write_err('No traceback available to show.\n') |
|
1856 | 1858 | return |
|
1857 | 1859 | |
|
1858 | 1860 | if issubclass(etype, SyntaxError): |
|
1859 | 1861 | # Though this won't be called by syntax errors in the input |
|
1860 | 1862 | # line, there may be SyntaxError cases with imported code. |
|
1861 | 1863 | self.showsyntaxerror(filename) |
|
1862 | 1864 | elif etype is UsageError: |
|
1863 | 1865 | self.show_usage_error(value) |
|
1864 | 1866 | else: |
|
1865 | 1867 | if exception_only: |
|
1866 | 1868 | stb = ['An exception has occurred, use %tb to see ' |
|
1867 | 1869 | 'the full traceback.\n'] |
|
1868 | 1870 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1869 | 1871 | value)) |
|
1870 | 1872 | else: |
|
1871 | 1873 | try: |
|
1872 | 1874 | # Exception classes can customise their traceback - we |
|
1873 | 1875 | # use this in IPython.parallel for exceptions occurring |
|
1874 | 1876 | # in the engines. This should return a list of strings. |
|
1875 | 1877 | stb = value._render_traceback_() |
|
1876 | 1878 | except Exception: |
|
1877 | 1879 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1878 | 1880 | value, tb, tb_offset=tb_offset) |
|
1879 | 1881 | |
|
1880 | 1882 | self._showtraceback(etype, value, stb) |
|
1881 | 1883 | if self.call_pdb: |
|
1882 | 1884 | # drop into debugger |
|
1883 | 1885 | self.debugger(force=True) |
|
1884 | 1886 | return |
|
1885 | 1887 | |
|
1886 | 1888 | # Actually show the traceback |
|
1887 | 1889 | self._showtraceback(etype, value, stb) |
|
1888 | 1890 | |
|
1889 | 1891 | except KeyboardInterrupt: |
|
1890 | 1892 | self.write_err('\n' + self.get_exception_only()) |
|
1891 | 1893 | |
|
1892 | 1894 | def _showtraceback(self, etype, evalue, stb): |
|
1893 | 1895 | """Actually show a traceback. |
|
1894 | 1896 | |
|
1895 | 1897 | Subclasses may override this method to put the traceback on a different |
|
1896 | 1898 | place, like a side channel. |
|
1897 | 1899 | """ |
|
1898 | 1900 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1899 | 1901 | |
|
1900 | 1902 | def showsyntaxerror(self, filename=None): |
|
1901 | 1903 | """Display the syntax error that just occurred. |
|
1902 | 1904 | |
|
1903 | 1905 | This doesn't display a stack trace because there isn't one. |
|
1904 | 1906 | |
|
1905 | 1907 | If a filename is given, it is stuffed in the exception instead |
|
1906 | 1908 | of what was there before (because Python's parser always uses |
|
1907 | 1909 | "<string>" when reading from a string). |
|
1908 | 1910 | """ |
|
1909 | 1911 | etype, value, last_traceback = self._get_exc_info() |
|
1910 | 1912 | |
|
1911 | 1913 | if filename and issubclass(etype, SyntaxError): |
|
1912 | 1914 | try: |
|
1913 | 1915 | value.filename = filename |
|
1914 | 1916 | except: |
|
1915 | 1917 | # Not the format we expect; leave it alone |
|
1916 | 1918 | pass |
|
1917 | 1919 | |
|
1918 | 1920 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1919 | 1921 | self._showtraceback(etype, value, stb) |
|
1920 | 1922 | |
|
1921 | 1923 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1922 | 1924 | # the %paste magic. |
|
1923 | 1925 | def showindentationerror(self): |
|
1924 | 1926 | """Called by run_cell when there's an IndentationError in code entered |
|
1925 | 1927 | at the prompt. |
|
1926 | 1928 | |
|
1927 | 1929 | This is overridden in TerminalInteractiveShell to show a message about |
|
1928 | 1930 | the %paste magic.""" |
|
1929 | 1931 | self.showsyntaxerror() |
|
1930 | 1932 | |
|
1931 | 1933 | #------------------------------------------------------------------------- |
|
1932 | 1934 | # Things related to readline |
|
1933 | 1935 | #------------------------------------------------------------------------- |
|
1934 | 1936 | |
|
1935 | 1937 | def init_readline(self): |
|
1936 | 1938 | """Command history completion/saving/reloading.""" |
|
1937 | 1939 | |
|
1938 | 1940 | if self.readline_use: |
|
1939 | 1941 | import IPython.utils.rlineimpl as readline |
|
1940 | 1942 | |
|
1941 | 1943 | self.rl_next_input = None |
|
1942 | 1944 | self.rl_do_indent = False |
|
1943 | 1945 | |
|
1944 | 1946 | if not self.readline_use or not readline.have_readline: |
|
1945 | 1947 | self.has_readline = False |
|
1946 | 1948 | self.readline = None |
|
1947 | 1949 | # Set a number of methods that depend on readline to be no-op |
|
1948 | 1950 | self.readline_no_record = no_op_context |
|
1949 | 1951 | self.set_readline_completer = no_op |
|
1950 | 1952 | self.set_custom_completer = no_op |
|
1951 | 1953 | if self.readline_use: |
|
1952 | 1954 | warn('Readline services not available or not loaded.') |
|
1953 | 1955 | else: |
|
1954 | 1956 | self.has_readline = True |
|
1955 | 1957 | self.readline = readline |
|
1956 | 1958 | sys.modules['readline'] = readline |
|
1957 | 1959 | |
|
1958 | 1960 | # Platform-specific configuration |
|
1959 | 1961 | if os.name == 'nt': |
|
1960 | 1962 | # FIXME - check with Frederick to see if we can harmonize |
|
1961 | 1963 | # naming conventions with pyreadline to avoid this |
|
1962 | 1964 | # platform-dependent check |
|
1963 | 1965 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1964 | 1966 | else: |
|
1965 | 1967 | self.readline_startup_hook = readline.set_startup_hook |
|
1966 | 1968 | |
|
1967 | 1969 | # Readline config order: |
|
1968 | 1970 | # - IPython config (default value) |
|
1969 | 1971 | # - custom inputrc |
|
1970 | 1972 | # - IPython config (user customized) |
|
1971 | 1973 | |
|
1972 | 1974 | # load IPython config before inputrc if default |
|
1973 | 1975 | # skip if libedit because parse_and_bind syntax is different |
|
1974 | 1976 | if not self._custom_readline_config and not readline.uses_libedit: |
|
1975 | 1977 | for rlcommand in self.readline_parse_and_bind: |
|
1976 | 1978 | readline.parse_and_bind(rlcommand) |
|
1977 | 1979 | |
|
1978 | 1980 | # Load user's initrc file (readline config) |
|
1979 | 1981 | # Or if libedit is used, load editrc. |
|
1980 | 1982 | inputrc_name = os.environ.get('INPUTRC') |
|
1981 | 1983 | if inputrc_name is None: |
|
1982 | 1984 | inputrc_name = '.inputrc' |
|
1983 | 1985 | if readline.uses_libedit: |
|
1984 | 1986 | inputrc_name = '.editrc' |
|
1985 | 1987 | inputrc_name = os.path.join(self.home_dir, inputrc_name) |
|
1986 | 1988 | if os.path.isfile(inputrc_name): |
|
1987 | 1989 | try: |
|
1988 | 1990 | readline.read_init_file(inputrc_name) |
|
1989 | 1991 | except: |
|
1990 | 1992 | warn('Problems reading readline initialization file <%s>' |
|
1991 | 1993 | % inputrc_name) |
|
1992 | 1994 | |
|
1993 | 1995 | # load IPython config after inputrc if user has customized |
|
1994 | 1996 | if self._custom_readline_config: |
|
1995 | 1997 | for rlcommand in self.readline_parse_and_bind: |
|
1996 | 1998 | readline.parse_and_bind(rlcommand) |
|
1997 | 1999 | |
|
1998 | 2000 | # Remove some chars from the delimiters list. If we encounter |
|
1999 | 2001 | # unicode chars, discard them. |
|
2000 | 2002 | delims = readline.get_completer_delims() |
|
2001 | 2003 | if not py3compat.PY3: |
|
2002 | 2004 | delims = delims.encode("ascii", "ignore") |
|
2003 | 2005 | for d in self.readline_remove_delims: |
|
2004 | 2006 | delims = delims.replace(d, "") |
|
2005 | 2007 | delims = delims.replace(ESC_MAGIC, '') |
|
2006 | 2008 | readline.set_completer_delims(delims) |
|
2007 | 2009 | # Store these so we can restore them if something like rpy2 modifies |
|
2008 | 2010 | # them. |
|
2009 | 2011 | self.readline_delims = delims |
|
2010 | 2012 | # otherwise we end up with a monster history after a while: |
|
2011 | 2013 | readline.set_history_length(self.history_length) |
|
2012 | 2014 | |
|
2013 | 2015 | self.refill_readline_hist() |
|
2014 | 2016 | self.readline_no_record = ReadlineNoRecord(self) |
|
2015 | 2017 | |
|
2016 | 2018 | # Configure auto-indent for all platforms |
|
2017 | 2019 | self.set_autoindent(self.autoindent) |
|
2018 | 2020 | |
|
2019 | 2021 | def refill_readline_hist(self): |
|
2020 | 2022 | # Load the last 1000 lines from history |
|
2021 | 2023 | self.readline.clear_history() |
|
2022 | 2024 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
2023 | 2025 | last_cell = u"" |
|
2024 | 2026 | for _, _, cell in self.history_manager.get_tail(self.history_load_length, |
|
2025 | 2027 | include_latest=True): |
|
2026 | 2028 | # Ignore blank lines and consecutive duplicates |
|
2027 | 2029 | cell = cell.rstrip() |
|
2028 | 2030 | if cell and (cell != last_cell): |
|
2029 | 2031 | try: |
|
2030 | 2032 | if self.multiline_history: |
|
2031 | 2033 | self.readline.add_history(py3compat.unicode_to_str(cell, |
|
2032 | 2034 | stdin_encoding)) |
|
2033 | 2035 | else: |
|
2034 | 2036 | for line in cell.splitlines(): |
|
2035 | 2037 | self.readline.add_history(py3compat.unicode_to_str(line, |
|
2036 | 2038 | stdin_encoding)) |
|
2037 | 2039 | last_cell = cell |
|
2038 | 2040 | |
|
2039 | 2041 | except TypeError: |
|
2040 | 2042 | # The history DB can get corrupted so it returns strings |
|
2041 | 2043 | # containing null bytes, which readline objects to. |
|
2042 | 2044 | continue |
|
2043 | 2045 | |
|
2044 | 2046 | @skip_doctest |
|
2045 | 2047 | def set_next_input(self, s, replace=False): |
|
2046 | 2048 | """ Sets the 'default' input string for the next command line. |
|
2047 | 2049 | |
|
2048 | 2050 | Requires readline. |
|
2049 | 2051 | |
|
2050 | 2052 | Example:: |
|
2051 | 2053 | |
|
2052 | 2054 | In [1]: _ip.set_next_input("Hello Word") |
|
2053 | 2055 | In [2]: Hello Word_ # cursor is here |
|
2054 | 2056 | """ |
|
2055 | 2057 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
2056 | 2058 | |
|
2057 | 2059 | # Maybe move this to the terminal subclass? |
|
2058 | 2060 | def pre_readline(self): |
|
2059 | 2061 | """readline hook to be used at the start of each line. |
|
2060 | 2062 | |
|
2061 | 2063 | Currently it handles auto-indent only.""" |
|
2062 | 2064 | |
|
2063 | 2065 | if self.rl_do_indent: |
|
2064 | 2066 | self.readline.insert_text(self._indent_current_str()) |
|
2065 | 2067 | if self.rl_next_input is not None: |
|
2066 | 2068 | self.readline.insert_text(self.rl_next_input) |
|
2067 | 2069 | self.rl_next_input = None |
|
2068 | 2070 | |
|
2069 | 2071 | def _indent_current_str(self): |
|
2070 | 2072 | """return the current level of indentation as a string""" |
|
2071 | 2073 | return self.input_splitter.indent_spaces * ' ' |
|
2072 | 2074 | |
|
2073 | 2075 | #------------------------------------------------------------------------- |
|
2074 | 2076 | # Things related to text completion |
|
2075 | 2077 | #------------------------------------------------------------------------- |
|
2076 | 2078 | |
|
2077 | 2079 | def init_completer(self): |
|
2078 | 2080 | """Initialize the completion machinery. |
|
2079 | 2081 | |
|
2080 | 2082 | This creates completion machinery that can be used by client code, |
|
2081 | 2083 | either interactively in-process (typically triggered by the readline |
|
2082 | 2084 | library), programmatically (such as in test suites) or out-of-process |
|
2083 | 2085 | (typically over the network by remote frontends). |
|
2084 | 2086 | """ |
|
2085 | 2087 | from IPython.core.completer import IPCompleter |
|
2086 | 2088 | from IPython.core.completerlib import (module_completer, |
|
2087 | 2089 | magic_run_completer, cd_completer, reset_completer) |
|
2088 | 2090 | |
|
2089 | 2091 | self.Completer = IPCompleter(shell=self, |
|
2090 | 2092 | namespace=self.user_ns, |
|
2091 | 2093 | global_namespace=self.user_global_ns, |
|
2092 | 2094 | use_readline=self.has_readline, |
|
2093 | 2095 | parent=self, |
|
2094 | 2096 | ) |
|
2095 | 2097 | self.configurables.append(self.Completer) |
|
2096 | 2098 | |
|
2097 | 2099 | # Add custom completers to the basic ones built into IPCompleter |
|
2098 | 2100 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
2099 | 2101 | self.strdispatchers['complete_command'] = sdisp |
|
2100 | 2102 | self.Completer.custom_completers = sdisp |
|
2101 | 2103 | |
|
2102 | 2104 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
2103 | 2105 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
2104 | 2106 | self.set_hook('complete_command', module_completer, str_key = '%aimport') |
|
2105 | 2107 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
2106 | 2108 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
2107 | 2109 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
2108 | 2110 | |
|
2109 | 2111 | # Only configure readline if we truly are using readline. IPython can |
|
2110 | 2112 | # do tab-completion over the network, in GUIs, etc, where readline |
|
2111 | 2113 | # itself may be absent |
|
2112 | 2114 | if self.has_readline: |
|
2113 | 2115 | self.set_readline_completer() |
|
2114 | 2116 | |
|
2115 | 2117 | def complete(self, text, line=None, cursor_pos=None): |
|
2116 | 2118 | """Return the completed text and a list of completions. |
|
2117 | 2119 | |
|
2118 | 2120 | Parameters |
|
2119 | 2121 | ---------- |
|
2120 | 2122 | |
|
2121 | 2123 | text : string |
|
2122 | 2124 | A string of text to be completed on. It can be given as empty and |
|
2123 | 2125 | instead a line/position pair are given. In this case, the |
|
2124 | 2126 | completer itself will split the line like readline does. |
|
2125 | 2127 | |
|
2126 | 2128 | line : string, optional |
|
2127 | 2129 | The complete line that text is part of. |
|
2128 | 2130 | |
|
2129 | 2131 | cursor_pos : int, optional |
|
2130 | 2132 | The position of the cursor on the input line. |
|
2131 | 2133 | |
|
2132 | 2134 | Returns |
|
2133 | 2135 | ------- |
|
2134 | 2136 | text : string |
|
2135 | 2137 | The actual text that was completed. |
|
2136 | 2138 | |
|
2137 | 2139 | matches : list |
|
2138 | 2140 | A sorted list with all possible completions. |
|
2139 | 2141 | |
|
2140 | 2142 | The optional arguments allow the completion to take more context into |
|
2141 | 2143 | account, and are part of the low-level completion API. |
|
2142 | 2144 | |
|
2143 | 2145 | This is a wrapper around the completion mechanism, similar to what |
|
2144 | 2146 | readline does at the command line when the TAB key is hit. By |
|
2145 | 2147 | exposing it as a method, it can be used by other non-readline |
|
2146 | 2148 | environments (such as GUIs) for text completion. |
|
2147 | 2149 | |
|
2148 | 2150 | Simple usage example: |
|
2149 | 2151 | |
|
2150 | 2152 | In [1]: x = 'hello' |
|
2151 | 2153 | |
|
2152 | 2154 | In [2]: _ip.complete('x.l') |
|
2153 | 2155 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
2154 | 2156 | """ |
|
2155 | 2157 | |
|
2156 | 2158 | # Inject names into __builtin__ so we can complete on the added names. |
|
2157 | 2159 | with self.builtin_trap: |
|
2158 | 2160 | return self.Completer.complete(text, line, cursor_pos) |
|
2159 | 2161 | |
|
2160 | 2162 | def set_custom_completer(self, completer, pos=0): |
|
2161 | 2163 | """Adds a new custom completer function. |
|
2162 | 2164 | |
|
2163 | 2165 | The position argument (defaults to 0) is the index in the completers |
|
2164 | 2166 | list where you want the completer to be inserted.""" |
|
2165 | 2167 | |
|
2166 | 2168 | newcomp = types.MethodType(completer,self.Completer) |
|
2167 | 2169 | self.Completer.matchers.insert(pos,newcomp) |
|
2168 | 2170 | |
|
2169 | 2171 | def set_readline_completer(self): |
|
2170 | 2172 | """Reset readline's completer to be our own.""" |
|
2171 | 2173 | self.readline.set_completer(self.Completer.rlcomplete) |
|
2172 | 2174 | |
|
2173 | 2175 | def set_completer_frame(self, frame=None): |
|
2174 | 2176 | """Set the frame of the completer.""" |
|
2175 | 2177 | if frame: |
|
2176 | 2178 | self.Completer.namespace = frame.f_locals |
|
2177 | 2179 | self.Completer.global_namespace = frame.f_globals |
|
2178 | 2180 | else: |
|
2179 | 2181 | self.Completer.namespace = self.user_ns |
|
2180 | 2182 | self.Completer.global_namespace = self.user_global_ns |
|
2181 | 2183 | |
|
2182 | 2184 | #------------------------------------------------------------------------- |
|
2183 | 2185 | # Things related to magics |
|
2184 | 2186 | #------------------------------------------------------------------------- |
|
2185 | 2187 | |
|
2186 | 2188 | def init_magics(self): |
|
2187 | 2189 | from IPython.core import magics as m |
|
2188 | 2190 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2189 | 2191 | parent=self, |
|
2190 | 2192 | user_magics=m.UserMagics(self)) |
|
2191 | 2193 | self.configurables.append(self.magics_manager) |
|
2192 | 2194 | |
|
2193 | 2195 | # Expose as public API from the magics manager |
|
2194 | 2196 | self.register_magics = self.magics_manager.register |
|
2195 | 2197 | self.define_magic = self.magics_manager.define_magic |
|
2196 | 2198 | |
|
2197 | 2199 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2198 | 2200 | m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2199 | 2201 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2200 | 2202 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2201 | 2203 | ) |
|
2202 | 2204 | |
|
2203 | 2205 | # Register Magic Aliases |
|
2204 | 2206 | mman = self.magics_manager |
|
2205 | 2207 | # FIXME: magic aliases should be defined by the Magics classes |
|
2206 | 2208 | # or in MagicsManager, not here |
|
2207 | 2209 | mman.register_alias('ed', 'edit') |
|
2208 | 2210 | mman.register_alias('hist', 'history') |
|
2209 | 2211 | mman.register_alias('rep', 'recall') |
|
2210 | 2212 | mman.register_alias('SVG', 'svg', 'cell') |
|
2211 | 2213 | mman.register_alias('HTML', 'html', 'cell') |
|
2212 | 2214 | mman.register_alias('file', 'writefile', 'cell') |
|
2213 | 2215 | |
|
2214 | 2216 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2215 | 2217 | # should be split into a prompt manager and displayhook. We probably |
|
2216 | 2218 | # even need a centralize colors management object. |
|
2217 | 2219 | self.magic('colors %s' % self.colors) |
|
2218 | 2220 | |
|
2219 | 2221 | # Defined here so that it's included in the documentation |
|
2220 | 2222 | @functools.wraps(magic.MagicsManager.register_function) |
|
2221 | 2223 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2222 | 2224 | self.magics_manager.register_function(func, |
|
2223 | 2225 | magic_kind=magic_kind, magic_name=magic_name) |
|
2224 | 2226 | |
|
2225 | 2227 | def run_line_magic(self, magic_name, line): |
|
2226 | 2228 | """Execute the given line magic. |
|
2227 | 2229 | |
|
2228 | 2230 | Parameters |
|
2229 | 2231 | ---------- |
|
2230 | 2232 | magic_name : str |
|
2231 | 2233 | Name of the desired magic function, without '%' prefix. |
|
2232 | 2234 | |
|
2233 | 2235 | line : str |
|
2234 | 2236 | The rest of the input line as a single string. |
|
2235 | 2237 | """ |
|
2236 | 2238 | fn = self.find_line_magic(magic_name) |
|
2237 | 2239 | if fn is None: |
|
2238 | 2240 | cm = self.find_cell_magic(magic_name) |
|
2239 | 2241 | etpl = "Line magic function `%%%s` not found%s." |
|
2240 | 2242 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2241 | 2243 | 'did you mean that instead?)' % magic_name ) |
|
2242 | 2244 | error(etpl % (magic_name, extra)) |
|
2243 | 2245 | else: |
|
2244 | 2246 | # Note: this is the distance in the stack to the user's frame. |
|
2245 | 2247 | # This will need to be updated if the internal calling logic gets |
|
2246 | 2248 | # refactored, or else we'll be expanding the wrong variables. |
|
2247 | 2249 | stack_depth = 2 |
|
2248 | 2250 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2249 | 2251 | # Put magic args in a list so we can call with f(*a) syntax |
|
2250 | 2252 | args = [magic_arg_s] |
|
2251 | 2253 | kwargs = {} |
|
2252 | 2254 | # Grab local namespace if we need it: |
|
2253 | 2255 | if getattr(fn, "needs_local_scope", False): |
|
2254 | 2256 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2255 | 2257 | with self.builtin_trap: |
|
2256 | 2258 | result = fn(*args,**kwargs) |
|
2257 | 2259 | return result |
|
2258 | 2260 | |
|
2259 | 2261 | def run_cell_magic(self, magic_name, line, cell): |
|
2260 | 2262 | """Execute the given cell magic. |
|
2261 | 2263 | |
|
2262 | 2264 | Parameters |
|
2263 | 2265 | ---------- |
|
2264 | 2266 | magic_name : str |
|
2265 | 2267 | Name of the desired magic function, without '%' prefix. |
|
2266 | 2268 | |
|
2267 | 2269 | line : str |
|
2268 | 2270 | The rest of the first input line as a single string. |
|
2269 | 2271 | |
|
2270 | 2272 | cell : str |
|
2271 | 2273 | The body of the cell as a (possibly multiline) string. |
|
2272 | 2274 | """ |
|
2273 | 2275 | fn = self.find_cell_magic(magic_name) |
|
2274 | 2276 | if fn is None: |
|
2275 | 2277 | lm = self.find_line_magic(magic_name) |
|
2276 | 2278 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2277 | 2279 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2278 | 2280 | 'did you mean that instead?)'.format(magic_name)) |
|
2279 | 2281 | error(etpl.format(magic_name, extra)) |
|
2280 | 2282 | elif cell == '': |
|
2281 | 2283 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2282 | 2284 | if self.find_line_magic(magic_name) is not None: |
|
2283 | 2285 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2284 | 2286 | raise UsageError(message) |
|
2285 | 2287 | else: |
|
2286 | 2288 | # Note: this is the distance in the stack to the user's frame. |
|
2287 | 2289 | # This will need to be updated if the internal calling logic gets |
|
2288 | 2290 | # refactored, or else we'll be expanding the wrong variables. |
|
2289 | 2291 | stack_depth = 2 |
|
2290 | 2292 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2291 | 2293 | with self.builtin_trap: |
|
2292 | 2294 | result = fn(magic_arg_s, cell) |
|
2293 | 2295 | return result |
|
2294 | 2296 | |
|
2295 | 2297 | def find_line_magic(self, magic_name): |
|
2296 | 2298 | """Find and return a line magic by name. |
|
2297 | 2299 | |
|
2298 | 2300 | Returns None if the magic isn't found.""" |
|
2299 | 2301 | return self.magics_manager.magics['line'].get(magic_name) |
|
2300 | 2302 | |
|
2301 | 2303 | def find_cell_magic(self, magic_name): |
|
2302 | 2304 | """Find and return a cell magic by name. |
|
2303 | 2305 | |
|
2304 | 2306 | Returns None if the magic isn't found.""" |
|
2305 | 2307 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2306 | 2308 | |
|
2307 | 2309 | def find_magic(self, magic_name, magic_kind='line'): |
|
2308 | 2310 | """Find and return a magic of the given type by name. |
|
2309 | 2311 | |
|
2310 | 2312 | Returns None if the magic isn't found.""" |
|
2311 | 2313 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2312 | 2314 | |
|
2313 | 2315 | def magic(self, arg_s): |
|
2314 | 2316 | """DEPRECATED. Use run_line_magic() instead. |
|
2315 | 2317 | |
|
2316 | 2318 | Call a magic function by name. |
|
2317 | 2319 | |
|
2318 | 2320 | Input: a string containing the name of the magic function to call and |
|
2319 | 2321 | any additional arguments to be passed to the magic. |
|
2320 | 2322 | |
|
2321 | 2323 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2322 | 2324 | prompt: |
|
2323 | 2325 | |
|
2324 | 2326 | In[1]: %name -opt foo bar |
|
2325 | 2327 | |
|
2326 | 2328 | To call a magic without arguments, simply use magic('name'). |
|
2327 | 2329 | |
|
2328 | 2330 | This provides a proper Python function to call IPython's magics in any |
|
2329 | 2331 | valid Python code you can type at the interpreter, including loops and |
|
2330 | 2332 | compound statements. |
|
2331 | 2333 | """ |
|
2332 | 2334 | # TODO: should we issue a loud deprecation warning here? |
|
2333 | 2335 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2334 | 2336 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2335 | 2337 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2336 | 2338 | |
|
2337 | 2339 | #------------------------------------------------------------------------- |
|
2338 | 2340 | # Things related to macros |
|
2339 | 2341 | #------------------------------------------------------------------------- |
|
2340 | 2342 | |
|
2341 | 2343 | def define_macro(self, name, themacro): |
|
2342 | 2344 | """Define a new macro |
|
2343 | 2345 | |
|
2344 | 2346 | Parameters |
|
2345 | 2347 | ---------- |
|
2346 | 2348 | name : str |
|
2347 | 2349 | The name of the macro. |
|
2348 | 2350 | themacro : str or Macro |
|
2349 | 2351 | The action to do upon invoking the macro. If a string, a new |
|
2350 | 2352 | Macro object is created by passing the string to it. |
|
2351 | 2353 | """ |
|
2352 | 2354 | |
|
2353 | 2355 | from IPython.core import macro |
|
2354 | 2356 | |
|
2355 | 2357 | if isinstance(themacro, string_types): |
|
2356 | 2358 | themacro = macro.Macro(themacro) |
|
2357 | 2359 | if not isinstance(themacro, macro.Macro): |
|
2358 | 2360 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2359 | 2361 | self.user_ns[name] = themacro |
|
2360 | 2362 | |
|
2361 | 2363 | #------------------------------------------------------------------------- |
|
2362 | 2364 | # Things related to the running of system commands |
|
2363 | 2365 | #------------------------------------------------------------------------- |
|
2364 | 2366 | |
|
2365 | 2367 | def system_piped(self, cmd): |
|
2366 | 2368 | """Call the given cmd in a subprocess, piping stdout/err |
|
2367 | 2369 | |
|
2368 | 2370 | Parameters |
|
2369 | 2371 | ---------- |
|
2370 | 2372 | cmd : str |
|
2371 | 2373 | Command to execute (can not end in '&', as background processes are |
|
2372 | 2374 | not supported. Should not be a command that expects input |
|
2373 | 2375 | other than simple text. |
|
2374 | 2376 | """ |
|
2375 | 2377 | if cmd.rstrip().endswith('&'): |
|
2376 | 2378 | # this is *far* from a rigorous test |
|
2377 | 2379 | # We do not support backgrounding processes because we either use |
|
2378 | 2380 | # pexpect or pipes to read from. Users can always just call |
|
2379 | 2381 | # os.system() or use ip.system=ip.system_raw |
|
2380 | 2382 | # if they really want a background process. |
|
2381 | 2383 | raise OSError("Background processes not supported.") |
|
2382 | 2384 | |
|
2383 | 2385 | # we explicitly do NOT return the subprocess status code, because |
|
2384 | 2386 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2385 | 2387 | # Instead, we store the exit_code in user_ns. |
|
2386 | 2388 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2387 | 2389 | |
|
2388 | 2390 | def system_raw(self, cmd): |
|
2389 | 2391 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2390 | 2392 | subprocess.call using the system shell on other platforms. |
|
2391 | 2393 | |
|
2392 | 2394 | Parameters |
|
2393 | 2395 | ---------- |
|
2394 | 2396 | cmd : str |
|
2395 | 2397 | Command to execute. |
|
2396 | 2398 | """ |
|
2397 | 2399 | cmd = self.var_expand(cmd, depth=1) |
|
2398 | 2400 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2399 | 2401 | if sys.platform == 'win32': |
|
2400 | 2402 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2401 | 2403 | with AvoidUNCPath() as path: |
|
2402 | 2404 | if path is not None: |
|
2403 | 2405 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2404 | 2406 | cmd = py3compat.unicode_to_str(cmd) |
|
2405 | 2407 | try: |
|
2406 | 2408 | ec = os.system(cmd) |
|
2407 | 2409 | except KeyboardInterrupt: |
|
2408 | 2410 | self.write_err('\n' + self.get_exception_only()) |
|
2409 | 2411 | ec = -2 |
|
2410 | 2412 | else: |
|
2411 | 2413 | cmd = py3compat.unicode_to_str(cmd) |
|
2412 | 2414 | # For posix the result of the subprocess.call() below is an exit |
|
2413 | 2415 | # code, which by convention is zero for success, positive for |
|
2414 | 2416 | # program failure. Exit codes above 128 are reserved for signals, |
|
2415 | 2417 | # and the formula for converting a signal to an exit code is usually |
|
2416 | 2418 | # signal_number+128. To more easily differentiate between exit |
|
2417 | 2419 | # codes and signals, ipython uses negative numbers. For instance |
|
2418 | 2420 | # since control-c is signal 2 but exit code 130, ipython's |
|
2419 | 2421 | # _exit_code variable will read -2. Note that some shells like |
|
2420 | 2422 | # csh and fish don't follow sh/bash conventions for exit codes. |
|
2421 | 2423 | executable = os.environ.get('SHELL', None) |
|
2422 | 2424 | try: |
|
2423 | 2425 | # Use env shell instead of default /bin/sh |
|
2424 | 2426 | ec = subprocess.call(cmd, shell=True, executable=executable) |
|
2425 | 2427 | except KeyboardInterrupt: |
|
2426 | 2428 | # intercept control-C; a long traceback is not useful here |
|
2427 | 2429 | self.write_err('\n' + self.get_exception_only()) |
|
2428 | 2430 | ec = 130 |
|
2429 | 2431 | if ec > 128: |
|
2430 | 2432 | ec = -(ec - 128) |
|
2431 | 2433 | |
|
2432 | 2434 | # We explicitly do NOT return the subprocess status code, because |
|
2433 | 2435 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2434 | 2436 | # Instead, we store the exit_code in user_ns. Note the semantics |
|
2435 | 2437 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, |
|
2436 | 2438 | # but raising SystemExit(_exit_code) will give status 254! |
|
2437 | 2439 | self.user_ns['_exit_code'] = ec |
|
2438 | 2440 | |
|
2439 | 2441 | # use piped system by default, because it is better behaved |
|
2440 | 2442 | system = system_piped |
|
2441 | 2443 | |
|
2442 | 2444 | def getoutput(self, cmd, split=True, depth=0): |
|
2443 | 2445 | """Get output (possibly including stderr) from a subprocess. |
|
2444 | 2446 | |
|
2445 | 2447 | Parameters |
|
2446 | 2448 | ---------- |
|
2447 | 2449 | cmd : str |
|
2448 | 2450 | Command to execute (can not end in '&', as background processes are |
|
2449 | 2451 | not supported. |
|
2450 | 2452 | split : bool, optional |
|
2451 | 2453 | If True, split the output into an IPython SList. Otherwise, an |
|
2452 | 2454 | IPython LSString is returned. These are objects similar to normal |
|
2453 | 2455 | lists and strings, with a few convenience attributes for easier |
|
2454 | 2456 | manipulation of line-based output. You can use '?' on them for |
|
2455 | 2457 | details. |
|
2456 | 2458 | depth : int, optional |
|
2457 | 2459 | How many frames above the caller are the local variables which should |
|
2458 | 2460 | be expanded in the command string? The default (0) assumes that the |
|
2459 | 2461 | expansion variables are in the stack frame calling this function. |
|
2460 | 2462 | """ |
|
2461 | 2463 | if cmd.rstrip().endswith('&'): |
|
2462 | 2464 | # this is *far* from a rigorous test |
|
2463 | 2465 | raise OSError("Background processes not supported.") |
|
2464 | 2466 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2465 | 2467 | if split: |
|
2466 | 2468 | out = SList(out.splitlines()) |
|
2467 | 2469 | else: |
|
2468 | 2470 | out = LSString(out) |
|
2469 | 2471 | return out |
|
2470 | 2472 | |
|
2471 | 2473 | #------------------------------------------------------------------------- |
|
2472 | 2474 | # Things related to aliases |
|
2473 | 2475 | #------------------------------------------------------------------------- |
|
2474 | 2476 | |
|
2475 | 2477 | def init_alias(self): |
|
2476 | 2478 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2477 | 2479 | self.configurables.append(self.alias_manager) |
|
2478 | 2480 | |
|
2479 | 2481 | #------------------------------------------------------------------------- |
|
2480 | 2482 | # Things related to extensions |
|
2481 | 2483 | #------------------------------------------------------------------------- |
|
2482 | 2484 | |
|
2483 | 2485 | def init_extension_manager(self): |
|
2484 | 2486 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2485 | 2487 | self.configurables.append(self.extension_manager) |
|
2486 | 2488 | |
|
2487 | 2489 | #------------------------------------------------------------------------- |
|
2488 | 2490 | # Things related to payloads |
|
2489 | 2491 | #------------------------------------------------------------------------- |
|
2490 | 2492 | |
|
2491 | 2493 | def init_payload(self): |
|
2492 | 2494 | self.payload_manager = PayloadManager(parent=self) |
|
2493 | 2495 | self.configurables.append(self.payload_manager) |
|
2494 | 2496 | |
|
2495 | 2497 | #------------------------------------------------------------------------- |
|
2496 | 2498 | # Things related to the prefilter |
|
2497 | 2499 | #------------------------------------------------------------------------- |
|
2498 | 2500 | |
|
2499 | 2501 | def init_prefilter(self): |
|
2500 | 2502 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2501 | 2503 | self.configurables.append(self.prefilter_manager) |
|
2502 | 2504 | # Ultimately this will be refactored in the new interpreter code, but |
|
2503 | 2505 | # for now, we should expose the main prefilter method (there's legacy |
|
2504 | 2506 | # code out there that may rely on this). |
|
2505 | 2507 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2506 | 2508 | |
|
2507 | 2509 | def auto_rewrite_input(self, cmd): |
|
2508 | 2510 | """Print to the screen the rewritten form of the user's command. |
|
2509 | 2511 | |
|
2510 | 2512 | This shows visual feedback by rewriting input lines that cause |
|
2511 | 2513 | automatic calling to kick in, like:: |
|
2512 | 2514 | |
|
2513 | 2515 | /f x |
|
2514 | 2516 | |
|
2515 | 2517 | into:: |
|
2516 | 2518 | |
|
2517 | 2519 | ------> f(x) |
|
2518 | 2520 | |
|
2519 | 2521 | after the user's input prompt. This helps the user understand that the |
|
2520 | 2522 | input line was transformed automatically by IPython. |
|
2521 | 2523 | """ |
|
2522 | 2524 | if not self.show_rewritten_input: |
|
2523 | 2525 | return |
|
2524 | 2526 | |
|
2525 | 2527 | rw = self.prompt_manager.render('rewrite') + cmd |
|
2526 | 2528 | |
|
2527 | 2529 | try: |
|
2528 | 2530 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2529 | 2531 | # we use it and only print uncolored rewrite if we have unicode |
|
2530 | 2532 | rw = str(rw) |
|
2531 | 2533 | print(rw, file=io.stdout) |
|
2532 | 2534 | except UnicodeEncodeError: |
|
2533 | 2535 | print("------> " + cmd) |
|
2534 | 2536 | |
|
2535 | 2537 | #------------------------------------------------------------------------- |
|
2536 | 2538 | # Things related to extracting values/expressions from kernel and user_ns |
|
2537 | 2539 | #------------------------------------------------------------------------- |
|
2538 | 2540 | |
|
2539 | 2541 | def _user_obj_error(self): |
|
2540 | 2542 | """return simple exception dict |
|
2541 | 2543 | |
|
2542 | 2544 | for use in user_expressions |
|
2543 | 2545 | """ |
|
2544 | 2546 | |
|
2545 | 2547 | etype, evalue, tb = self._get_exc_info() |
|
2546 | 2548 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2547 | 2549 | |
|
2548 | 2550 | exc_info = { |
|
2549 | 2551 | u'status' : 'error', |
|
2550 | 2552 | u'traceback' : stb, |
|
2551 | 2553 | u'ename' : unicode_type(etype.__name__), |
|
2552 | 2554 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2553 | 2555 | } |
|
2554 | 2556 | |
|
2555 | 2557 | return exc_info |
|
2556 | 2558 | |
|
2557 | 2559 | def _format_user_obj(self, obj): |
|
2558 | 2560 | """format a user object to display dict |
|
2559 | 2561 | |
|
2560 | 2562 | for use in user_expressions |
|
2561 | 2563 | """ |
|
2562 | 2564 | |
|
2563 | 2565 | data, md = self.display_formatter.format(obj) |
|
2564 | 2566 | value = { |
|
2565 | 2567 | 'status' : 'ok', |
|
2566 | 2568 | 'data' : data, |
|
2567 | 2569 | 'metadata' : md, |
|
2568 | 2570 | } |
|
2569 | 2571 | return value |
|
2570 | 2572 | |
|
2571 | 2573 | def user_expressions(self, expressions): |
|
2572 | 2574 | """Evaluate a dict of expressions in the user's namespace. |
|
2573 | 2575 | |
|
2574 | 2576 | Parameters |
|
2575 | 2577 | ---------- |
|
2576 | 2578 | expressions : dict |
|
2577 | 2579 | A dict with string keys and string values. The expression values |
|
2578 | 2580 | should be valid Python expressions, each of which will be evaluated |
|
2579 | 2581 | in the user namespace. |
|
2580 | 2582 | |
|
2581 | 2583 | Returns |
|
2582 | 2584 | ------- |
|
2583 | 2585 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2584 | 2586 | display_data of each value. |
|
2585 | 2587 | """ |
|
2586 | 2588 | out = {} |
|
2587 | 2589 | user_ns = self.user_ns |
|
2588 | 2590 | global_ns = self.user_global_ns |
|
2589 | 2591 | |
|
2590 | 2592 | for key, expr in iteritems(expressions): |
|
2591 | 2593 | try: |
|
2592 | 2594 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2593 | 2595 | except: |
|
2594 | 2596 | value = self._user_obj_error() |
|
2595 | 2597 | out[key] = value |
|
2596 | 2598 | return out |
|
2597 | 2599 | |
|
2598 | 2600 | #------------------------------------------------------------------------- |
|
2599 | 2601 | # Things related to the running of code |
|
2600 | 2602 | #------------------------------------------------------------------------- |
|
2601 | 2603 | |
|
2602 | 2604 | def ex(self, cmd): |
|
2603 | 2605 | """Execute a normal python statement in user namespace.""" |
|
2604 | 2606 | with self.builtin_trap: |
|
2605 | 2607 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2606 | 2608 | |
|
2607 | 2609 | def ev(self, expr): |
|
2608 | 2610 | """Evaluate python expression expr in user namespace. |
|
2609 | 2611 | |
|
2610 | 2612 | Returns the result of evaluation |
|
2611 | 2613 | """ |
|
2612 | 2614 | with self.builtin_trap: |
|
2613 | 2615 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2614 | 2616 | |
|
2615 | 2617 | def safe_execfile(self, fname, *where, **kw): |
|
2616 | 2618 | """A safe version of the builtin execfile(). |
|
2617 | 2619 | |
|
2618 | 2620 | This version will never throw an exception, but instead print |
|
2619 | 2621 | helpful error messages to the screen. This only works on pure |
|
2620 | 2622 | Python files with the .py extension. |
|
2621 | 2623 | |
|
2622 | 2624 | Parameters |
|
2623 | 2625 | ---------- |
|
2624 | 2626 | fname : string |
|
2625 | 2627 | The name of the file to be executed. |
|
2626 | 2628 | where : tuple |
|
2627 | 2629 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2628 | 2630 | If only one is given, it is passed as both. |
|
2629 | 2631 | exit_ignore : bool (False) |
|
2630 | 2632 | If True, then silence SystemExit for non-zero status (it is always |
|
2631 | 2633 | silenced for zero status, as it is so common). |
|
2632 | 2634 | raise_exceptions : bool (False) |
|
2633 | 2635 | If True raise exceptions everywhere. Meant for testing. |
|
2634 | 2636 | shell_futures : bool (False) |
|
2635 | 2637 | If True, the code will share future statements with the interactive |
|
2636 | 2638 | shell. It will both be affected by previous __future__ imports, and |
|
2637 | 2639 | any __future__ imports in the code will affect the shell. If False, |
|
2638 | 2640 | __future__ imports are not shared in either direction. |
|
2639 | 2641 | |
|
2640 | 2642 | """ |
|
2641 | 2643 | kw.setdefault('exit_ignore', False) |
|
2642 | 2644 | kw.setdefault('raise_exceptions', False) |
|
2643 | 2645 | kw.setdefault('shell_futures', False) |
|
2644 | 2646 | |
|
2645 | 2647 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2646 | 2648 | |
|
2647 | 2649 | # Make sure we can open the file |
|
2648 | 2650 | try: |
|
2649 | 2651 | with open(fname): |
|
2650 | 2652 | pass |
|
2651 | 2653 | except: |
|
2652 | 2654 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2653 | 2655 | return |
|
2654 | 2656 | |
|
2655 | 2657 | # Find things also in current directory. This is needed to mimic the |
|
2656 | 2658 | # behavior of running a script from the system command line, where |
|
2657 | 2659 | # Python inserts the script's directory into sys.path |
|
2658 | 2660 | dname = os.path.dirname(fname) |
|
2659 | 2661 | |
|
2660 | 2662 | with prepended_to_syspath(dname): |
|
2661 | 2663 | try: |
|
2662 | 2664 | glob, loc = (where + (None, ))[:2] |
|
2663 | 2665 | py3compat.execfile( |
|
2664 | 2666 | fname, glob, loc, |
|
2665 | 2667 | self.compile if kw['shell_futures'] else None) |
|
2666 | 2668 | except SystemExit as status: |
|
2667 | 2669 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2668 | 2670 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2669 | 2671 | # these are considered normal by the OS: |
|
2670 | 2672 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2671 | 2673 | # 0 |
|
2672 | 2674 | # > python -c'import sys;sys.exit()'; echo $? |
|
2673 | 2675 | # 0 |
|
2674 | 2676 | # For other exit status, we show the exception unless |
|
2675 | 2677 | # explicitly silenced, but only in short form. |
|
2676 | 2678 | if status.code: |
|
2677 | 2679 | if kw['raise_exceptions']: |
|
2678 | 2680 | raise |
|
2679 | 2681 | if not kw['exit_ignore']: |
|
2680 | 2682 | self.showtraceback(exception_only=True) |
|
2681 | 2683 | except: |
|
2682 | 2684 | if kw['raise_exceptions']: |
|
2683 | 2685 | raise |
|
2684 | 2686 | # tb offset is 2 because we wrap execfile |
|
2685 | 2687 | self.showtraceback(tb_offset=2) |
|
2686 | 2688 | |
|
2687 | 2689 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
|
2688 | 2690 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
|
2689 | 2691 | |
|
2690 | 2692 | Parameters |
|
2691 | 2693 | ---------- |
|
2692 | 2694 | fname : str |
|
2693 | 2695 | The name of the file to execute. The filename must have a |
|
2694 | 2696 | .ipy or .ipynb extension. |
|
2695 | 2697 | shell_futures : bool (False) |
|
2696 | 2698 | If True, the code will share future statements with the interactive |
|
2697 | 2699 | shell. It will both be affected by previous __future__ imports, and |
|
2698 | 2700 | any __future__ imports in the code will affect the shell. If False, |
|
2699 | 2701 | __future__ imports are not shared in either direction. |
|
2700 | 2702 | raise_exceptions : bool (False) |
|
2701 | 2703 | If True raise exceptions everywhere. Meant for testing. |
|
2702 | 2704 | """ |
|
2703 | 2705 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2704 | 2706 | |
|
2705 | 2707 | # Make sure we can open the file |
|
2706 | 2708 | try: |
|
2707 | 2709 | with open(fname): |
|
2708 | 2710 | pass |
|
2709 | 2711 | except: |
|
2710 | 2712 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2711 | 2713 | return |
|
2712 | 2714 | |
|
2713 | 2715 | # Find things also in current directory. This is needed to mimic the |
|
2714 | 2716 | # behavior of running a script from the system command line, where |
|
2715 | 2717 | # Python inserts the script's directory into sys.path |
|
2716 | 2718 | dname = os.path.dirname(fname) |
|
2717 | 2719 | |
|
2718 | 2720 | def get_cells(): |
|
2719 | 2721 | """generator for sequence of code blocks to run""" |
|
2720 | 2722 | if fname.endswith('.ipynb'): |
|
2721 | 2723 | from nbformat import read |
|
2722 | 2724 | with io_open(fname) as f: |
|
2723 | 2725 | nb = read(f, as_version=4) |
|
2724 | 2726 | if not nb.cells: |
|
2725 | 2727 | return |
|
2726 | 2728 | for cell in nb.cells: |
|
2727 | 2729 | if cell.cell_type == 'code': |
|
2728 | 2730 | yield cell.source |
|
2729 | 2731 | else: |
|
2730 | 2732 | with open(fname) as f: |
|
2731 | 2733 | yield f.read() |
|
2732 | 2734 | |
|
2733 | 2735 | with prepended_to_syspath(dname): |
|
2734 | 2736 | try: |
|
2735 | 2737 | for cell in get_cells(): |
|
2736 | 2738 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
|
2737 | 2739 | if raise_exceptions: |
|
2738 | 2740 | result.raise_error() |
|
2739 | 2741 | elif not result.success: |
|
2740 | 2742 | break |
|
2741 | 2743 | except: |
|
2742 | 2744 | if raise_exceptions: |
|
2743 | 2745 | raise |
|
2744 | 2746 | self.showtraceback() |
|
2745 | 2747 | warn('Unknown failure executing file: <%s>' % fname) |
|
2746 | 2748 | |
|
2747 | 2749 | def safe_run_module(self, mod_name, where): |
|
2748 | 2750 | """A safe version of runpy.run_module(). |
|
2749 | 2751 | |
|
2750 | 2752 | This version will never throw an exception, but instead print |
|
2751 | 2753 | helpful error messages to the screen. |
|
2752 | 2754 | |
|
2753 | 2755 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2754 | 2756 | |
|
2755 | 2757 | Parameters |
|
2756 | 2758 | ---------- |
|
2757 | 2759 | mod_name : string |
|
2758 | 2760 | The name of the module to be executed. |
|
2759 | 2761 | where : dict |
|
2760 | 2762 | The globals namespace. |
|
2761 | 2763 | """ |
|
2762 | 2764 | try: |
|
2763 | 2765 | try: |
|
2764 | 2766 | where.update( |
|
2765 | 2767 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2766 | 2768 | alter_sys=True) |
|
2767 | 2769 | ) |
|
2768 | 2770 | except SystemExit as status: |
|
2769 | 2771 | if status.code: |
|
2770 | 2772 | raise |
|
2771 | 2773 | except: |
|
2772 | 2774 | self.showtraceback() |
|
2773 | 2775 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2774 | 2776 | |
|
2775 | 2777 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2776 | 2778 | """Run a complete IPython cell. |
|
2777 | 2779 | |
|
2778 | 2780 | Parameters |
|
2779 | 2781 | ---------- |
|
2780 | 2782 | raw_cell : str |
|
2781 | 2783 | The code (including IPython code such as %magic functions) to run. |
|
2782 | 2784 | store_history : bool |
|
2783 | 2785 | If True, the raw and translated cell will be stored in IPython's |
|
2784 | 2786 | history. For user code calling back into IPython's machinery, this |
|
2785 | 2787 | should be set to False. |
|
2786 | 2788 | silent : bool |
|
2787 | 2789 | If True, avoid side-effects, such as implicit displayhooks and |
|
2788 | 2790 | and logging. silent=True forces store_history=False. |
|
2789 | 2791 | shell_futures : bool |
|
2790 | 2792 | If True, the code will share future statements with the interactive |
|
2791 | 2793 | shell. It will both be affected by previous __future__ imports, and |
|
2792 | 2794 | any __future__ imports in the code will affect the shell. If False, |
|
2793 | 2795 | __future__ imports are not shared in either direction. |
|
2794 | 2796 | |
|
2795 | 2797 | Returns |
|
2796 | 2798 | ------- |
|
2797 | 2799 | result : :class:`ExecutionResult` |
|
2798 | 2800 | """ |
|
2799 | 2801 | result = ExecutionResult() |
|
2800 | 2802 | |
|
2801 | 2803 | if (not raw_cell) or raw_cell.isspace(): |
|
2802 | 2804 | return result |
|
2803 | 2805 | |
|
2804 | 2806 | if silent: |
|
2805 | 2807 | store_history = False |
|
2806 | 2808 | |
|
2807 | 2809 | if store_history: |
|
2808 | 2810 | result.execution_count = self.execution_count |
|
2809 | 2811 | |
|
2810 | 2812 | def error_before_exec(value): |
|
2811 | 2813 | result.error_before_exec = value |
|
2812 | 2814 | return result |
|
2813 | 2815 | |
|
2814 | 2816 | self.events.trigger('pre_execute') |
|
2815 | 2817 | if not silent: |
|
2816 | 2818 | self.events.trigger('pre_run_cell') |
|
2817 | 2819 | |
|
2818 | 2820 | # If any of our input transformation (input_transformer_manager or |
|
2819 | 2821 | # prefilter_manager) raises an exception, we store it in this variable |
|
2820 | 2822 | # so that we can display the error after logging the input and storing |
|
2821 | 2823 | # it in the history. |
|
2822 | 2824 | preprocessing_exc_tuple = None |
|
2823 | 2825 | try: |
|
2824 | 2826 | # Static input transformations |
|
2825 | 2827 | cell = self.input_transformer_manager.transform_cell(raw_cell) |
|
2826 | 2828 | except SyntaxError: |
|
2827 | 2829 | preprocessing_exc_tuple = sys.exc_info() |
|
2828 | 2830 | cell = raw_cell # cell has to exist so it can be stored/logged |
|
2829 | 2831 | else: |
|
2830 | 2832 | if len(cell.splitlines()) == 1: |
|
2831 | 2833 | # Dynamic transformations - only applied for single line commands |
|
2832 | 2834 | with self.builtin_trap: |
|
2833 | 2835 | try: |
|
2834 | 2836 | # use prefilter_lines to handle trailing newlines |
|
2835 | 2837 | # restore trailing newline for ast.parse |
|
2836 | 2838 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2837 | 2839 | except Exception: |
|
2838 | 2840 | # don't allow prefilter errors to crash IPython |
|
2839 | 2841 | preprocessing_exc_tuple = sys.exc_info() |
|
2840 | 2842 | |
|
2841 | 2843 | # Store raw and processed history |
|
2842 | 2844 | if store_history: |
|
2843 | 2845 | self.history_manager.store_inputs(self.execution_count, |
|
2844 | 2846 | cell, raw_cell) |
|
2845 | 2847 | if not silent: |
|
2846 | 2848 | self.logger.log(cell, raw_cell) |
|
2847 | 2849 | |
|
2848 | 2850 | # Display the exception if input processing failed. |
|
2849 | 2851 | if preprocessing_exc_tuple is not None: |
|
2850 | 2852 | self.showtraceback(preprocessing_exc_tuple) |
|
2851 | 2853 | if store_history: |
|
2852 | 2854 | self.execution_count += 1 |
|
2853 | 2855 | return error_before_exec(preprocessing_exc_tuple[2]) |
|
2854 | 2856 | |
|
2855 | 2857 | # Our own compiler remembers the __future__ environment. If we want to |
|
2856 | 2858 | # run code with a separate __future__ environment, use the default |
|
2857 | 2859 | # compiler |
|
2858 | 2860 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2859 | 2861 | |
|
2860 | 2862 | with self.builtin_trap: |
|
2861 | 2863 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2862 | 2864 | |
|
2863 | 2865 | with self.display_trap: |
|
2864 | 2866 | # Compile to bytecode |
|
2865 | 2867 | try: |
|
2866 | 2868 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2867 | 2869 | except IndentationError as e: |
|
2868 | 2870 | self.showindentationerror() |
|
2869 | 2871 | if store_history: |
|
2870 | 2872 | self.execution_count += 1 |
|
2871 | 2873 | return error_before_exec(e) |
|
2872 | 2874 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2873 | 2875 | MemoryError) as e: |
|
2874 | 2876 | self.showsyntaxerror() |
|
2875 | 2877 | if store_history: |
|
2876 | 2878 | self.execution_count += 1 |
|
2877 | 2879 | return error_before_exec(e) |
|
2878 | 2880 | |
|
2879 | 2881 | # Apply AST transformations |
|
2880 | 2882 | try: |
|
2881 | 2883 | code_ast = self.transform_ast(code_ast) |
|
2882 | 2884 | except InputRejected as e: |
|
2883 | 2885 | self.showtraceback() |
|
2884 | 2886 | if store_history: |
|
2885 | 2887 | self.execution_count += 1 |
|
2886 | 2888 | return error_before_exec(e) |
|
2887 | 2889 | |
|
2888 | 2890 | # Give the displayhook a reference to our ExecutionResult so it |
|
2889 | 2891 | # can fill in the output value. |
|
2890 | 2892 | self.displayhook.exec_result = result |
|
2891 | 2893 | |
|
2892 | 2894 | # Execute the user code |
|
2893 | 2895 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2894 | 2896 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2895 | 2897 | interactivity=interactivity, compiler=compiler, result=result) |
|
2896 | 2898 | |
|
2897 | 2899 | # Reset this so later displayed values do not modify the |
|
2898 | 2900 | # ExecutionResult |
|
2899 | 2901 | self.displayhook.exec_result = None |
|
2900 | 2902 | |
|
2901 | 2903 | self.events.trigger('post_execute') |
|
2902 | 2904 | if not silent: |
|
2903 | 2905 | self.events.trigger('post_run_cell') |
|
2904 | 2906 | |
|
2905 | 2907 | if store_history: |
|
2906 | 2908 | # Write output to the database. Does nothing unless |
|
2907 | 2909 | # history output logging is enabled. |
|
2908 | 2910 | self.history_manager.store_output(self.execution_count) |
|
2909 | 2911 | # Each cell is a *single* input, regardless of how many lines it has |
|
2910 | 2912 | self.execution_count += 1 |
|
2911 | 2913 | |
|
2912 | 2914 | return result |
|
2913 | 2915 | |
|
2914 | 2916 | def transform_ast(self, node): |
|
2915 | 2917 | """Apply the AST transformations from self.ast_transformers |
|
2916 | 2918 | |
|
2917 | 2919 | Parameters |
|
2918 | 2920 | ---------- |
|
2919 | 2921 | node : ast.Node |
|
2920 | 2922 | The root node to be transformed. Typically called with the ast.Module |
|
2921 | 2923 | produced by parsing user input. |
|
2922 | 2924 | |
|
2923 | 2925 | Returns |
|
2924 | 2926 | ------- |
|
2925 | 2927 | An ast.Node corresponding to the node it was called with. Note that it |
|
2926 | 2928 | may also modify the passed object, so don't rely on references to the |
|
2927 | 2929 | original AST. |
|
2928 | 2930 | """ |
|
2929 | 2931 | for transformer in self.ast_transformers: |
|
2930 | 2932 | try: |
|
2931 | 2933 | node = transformer.visit(node) |
|
2932 | 2934 | except InputRejected: |
|
2933 | 2935 | # User-supplied AST transformers can reject an input by raising |
|
2934 | 2936 | # an InputRejected. Short-circuit in this case so that we |
|
2935 | 2937 | # don't unregister the transform. |
|
2936 | 2938 | raise |
|
2937 | 2939 | except Exception: |
|
2938 | 2940 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2939 | 2941 | self.ast_transformers.remove(transformer) |
|
2940 | 2942 | |
|
2941 | 2943 | if self.ast_transformers: |
|
2942 | 2944 | ast.fix_missing_locations(node) |
|
2943 | 2945 | return node |
|
2944 | 2946 | |
|
2945 | 2947 | |
|
2946 | 2948 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', |
|
2947 | 2949 | compiler=compile, result=None): |
|
2948 | 2950 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2949 | 2951 | interactivity parameter. |
|
2950 | 2952 | |
|
2951 | 2953 | Parameters |
|
2952 | 2954 | ---------- |
|
2953 | 2955 | nodelist : list |
|
2954 | 2956 | A sequence of AST nodes to run. |
|
2955 | 2957 | cell_name : str |
|
2956 | 2958 | Will be passed to the compiler as the filename of the cell. Typically |
|
2957 | 2959 | the value returned by ip.compile.cache(cell). |
|
2958 | 2960 | interactivity : str |
|
2959 | 2961 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2960 | 2962 | run interactively (displaying output from expressions). 'last_expr' |
|
2961 | 2963 | will run the last node interactively only if it is an expression (i.e. |
|
2962 | 2964 | expressions in loops or other blocks are not displayed. Other values |
|
2963 | 2965 | for this parameter will raise a ValueError. |
|
2964 | 2966 | compiler : callable |
|
2965 | 2967 | A function with the same interface as the built-in compile(), to turn |
|
2966 | 2968 | the AST nodes into code objects. Default is the built-in compile(). |
|
2967 | 2969 | result : ExecutionResult, optional |
|
2968 | 2970 | An object to store exceptions that occur during execution. |
|
2969 | 2971 | |
|
2970 | 2972 | Returns |
|
2971 | 2973 | ------- |
|
2972 | 2974 | True if an exception occurred while running code, False if it finished |
|
2973 | 2975 | running. |
|
2974 | 2976 | """ |
|
2975 | 2977 | if not nodelist: |
|
2976 | 2978 | return |
|
2977 | 2979 | |
|
2978 | 2980 | if interactivity == 'last_expr': |
|
2979 | 2981 | if isinstance(nodelist[-1], ast.Expr): |
|
2980 | 2982 | interactivity = "last" |
|
2981 | 2983 | else: |
|
2982 | 2984 | interactivity = "none" |
|
2983 | 2985 | |
|
2984 | 2986 | if interactivity == 'none': |
|
2985 | 2987 | to_run_exec, to_run_interactive = nodelist, [] |
|
2986 | 2988 | elif interactivity == 'last': |
|
2987 | 2989 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2988 | 2990 | elif interactivity == 'all': |
|
2989 | 2991 | to_run_exec, to_run_interactive = [], nodelist |
|
2990 | 2992 | else: |
|
2991 | 2993 | raise ValueError("Interactivity was %r" % interactivity) |
|
2992 | 2994 | |
|
2993 | 2995 | try: |
|
2994 | 2996 | for i, node in enumerate(to_run_exec): |
|
2995 | 2997 | mod = ast.Module([node]) |
|
2996 | 2998 | code = compiler(mod, cell_name, "exec") |
|
2997 | 2999 | if self.run_code(code, result): |
|
2998 | 3000 | return True |
|
2999 | 3001 | |
|
3000 | 3002 | for i, node in enumerate(to_run_interactive): |
|
3001 | 3003 | mod = ast.Interactive([node]) |
|
3002 | 3004 | code = compiler(mod, cell_name, "single") |
|
3003 | 3005 | if self.run_code(code, result): |
|
3004 | 3006 | return True |
|
3005 | 3007 | |
|
3006 | 3008 | # Flush softspace |
|
3007 | 3009 | if softspace(sys.stdout, 0): |
|
3008 | 3010 | print() |
|
3009 | 3011 | |
|
3010 | 3012 | except: |
|
3011 | 3013 | # It's possible to have exceptions raised here, typically by |
|
3012 | 3014 | # compilation of odd code (such as a naked 'return' outside a |
|
3013 | 3015 | # function) that did parse but isn't valid. Typically the exception |
|
3014 | 3016 | # is a SyntaxError, but it's safest just to catch anything and show |
|
3015 | 3017 | # the user a traceback. |
|
3016 | 3018 | |
|
3017 | 3019 | # We do only one try/except outside the loop to minimize the impact |
|
3018 | 3020 | # on runtime, and also because if any node in the node list is |
|
3019 | 3021 | # broken, we should stop execution completely. |
|
3020 | 3022 | if result: |
|
3021 | 3023 | result.error_before_exec = sys.exc_info()[1] |
|
3022 | 3024 | self.showtraceback() |
|
3023 | 3025 | return True |
|
3024 | 3026 | |
|
3025 | 3027 | return False |
|
3026 | 3028 | |
|
3027 | 3029 | def run_code(self, code_obj, result=None): |
|
3028 | 3030 | """Execute a code object. |
|
3029 | 3031 | |
|
3030 | 3032 | When an exception occurs, self.showtraceback() is called to display a |
|
3031 | 3033 | traceback. |
|
3032 | 3034 | |
|
3033 | 3035 | Parameters |
|
3034 | 3036 | ---------- |
|
3035 | 3037 | code_obj : code object |
|
3036 | 3038 | A compiled code object, to be executed |
|
3037 | 3039 | result : ExecutionResult, optional |
|
3038 | 3040 | An object to store exceptions that occur during execution. |
|
3039 | 3041 | |
|
3040 | 3042 | Returns |
|
3041 | 3043 | ------- |
|
3042 | 3044 | False : successful execution. |
|
3043 | 3045 | True : an error occurred. |
|
3044 | 3046 | """ |
|
3045 | 3047 | # Set our own excepthook in case the user code tries to call it |
|
3046 | 3048 | # directly, so that the IPython crash handler doesn't get triggered |
|
3047 | 3049 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook |
|
3048 | 3050 | |
|
3049 | 3051 | # we save the original sys.excepthook in the instance, in case config |
|
3050 | 3052 | # code (such as magics) needs access to it. |
|
3051 | 3053 | self.sys_excepthook = old_excepthook |
|
3052 | 3054 | outflag = 1 # happens in more places, so it's easier as default |
|
3053 | 3055 | try: |
|
3054 | 3056 | try: |
|
3055 | 3057 | self.hooks.pre_run_code_hook() |
|
3056 | 3058 | #rprint('Running code', repr(code_obj)) # dbg |
|
3057 | 3059 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
3058 | 3060 | finally: |
|
3059 | 3061 | # Reset our crash handler in place |
|
3060 | 3062 | sys.excepthook = old_excepthook |
|
3061 | 3063 | except SystemExit as e: |
|
3062 | 3064 | if result is not None: |
|
3063 | 3065 | result.error_in_exec = e |
|
3064 | 3066 | self.showtraceback(exception_only=True) |
|
3065 | 3067 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
3066 | 3068 | except self.custom_exceptions: |
|
3067 | 3069 | etype, value, tb = sys.exc_info() |
|
3068 | 3070 | if result is not None: |
|
3069 | 3071 | result.error_in_exec = value |
|
3070 | 3072 | self.CustomTB(etype, value, tb) |
|
3071 | 3073 | except: |
|
3072 | 3074 | if result is not None: |
|
3073 | 3075 | result.error_in_exec = sys.exc_info()[1] |
|
3074 | 3076 | self.showtraceback() |
|
3075 | 3077 | else: |
|
3076 | 3078 | outflag = 0 |
|
3077 | 3079 | return outflag |
|
3078 | 3080 | |
|
3079 | 3081 | # For backwards compatibility |
|
3080 | 3082 | runcode = run_code |
|
3081 | 3083 | |
|
3082 | 3084 | #------------------------------------------------------------------------- |
|
3083 | 3085 | # Things related to GUI support and pylab |
|
3084 | 3086 | #------------------------------------------------------------------------- |
|
3085 | 3087 | |
|
3086 | 3088 | def enable_gui(self, gui=None): |
|
3087 | 3089 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
3088 | 3090 | |
|
3089 | 3091 | def enable_matplotlib(self, gui=None): |
|
3090 | 3092 | """Enable interactive matplotlib and inline figure support. |
|
3091 | 3093 | |
|
3092 | 3094 | This takes the following steps: |
|
3093 | 3095 | |
|
3094 | 3096 | 1. select the appropriate eventloop and matplotlib backend |
|
3095 | 3097 | 2. set up matplotlib for interactive use with that backend |
|
3096 | 3098 | 3. configure formatters for inline figure display |
|
3097 | 3099 | 4. enable the selected gui eventloop |
|
3098 | 3100 | |
|
3099 | 3101 | Parameters |
|
3100 | 3102 | ---------- |
|
3101 | 3103 | gui : optional, string |
|
3102 | 3104 | If given, dictates the choice of matplotlib GUI backend to use |
|
3103 | 3105 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
3104 | 3106 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
3105 | 3107 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
3106 | 3108 | user's matplotlibrc configuration file). Note that not all backends |
|
3107 | 3109 | make sense in all contexts, for example a terminal ipython can't |
|
3108 | 3110 | display figures inline. |
|
3109 | 3111 | """ |
|
3110 | 3112 | from IPython.core import pylabtools as pt |
|
3111 | 3113 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
3112 | 3114 | |
|
3113 | 3115 | if gui != 'inline': |
|
3114 | 3116 | # If we have our first gui selection, store it |
|
3115 | 3117 | if self.pylab_gui_select is None: |
|
3116 | 3118 | self.pylab_gui_select = gui |
|
3117 | 3119 | # Otherwise if they are different |
|
3118 | 3120 | elif gui != self.pylab_gui_select: |
|
3119 | 3121 | print ('Warning: Cannot change to a different GUI toolkit: %s.' |
|
3120 | 3122 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
3121 | 3123 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
3122 | 3124 | |
|
3123 | 3125 | pt.activate_matplotlib(backend) |
|
3124 | 3126 | pt.configure_inline_support(self, backend) |
|
3125 | 3127 | |
|
3126 | 3128 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
3127 | 3129 | # plot updates into account |
|
3128 | 3130 | self.enable_gui(gui) |
|
3129 | 3131 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
3130 | 3132 | pt.mpl_runner(self.safe_execfile) |
|
3131 | 3133 | |
|
3132 | 3134 | return gui, backend |
|
3133 | 3135 | |
|
3134 | 3136 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
3135 | 3137 | """Activate pylab support at runtime. |
|
3136 | 3138 | |
|
3137 | 3139 | This turns on support for matplotlib, preloads into the interactive |
|
3138 | 3140 | namespace all of numpy and pylab, and configures IPython to correctly |
|
3139 | 3141 | interact with the GUI event loop. The GUI backend to be used can be |
|
3140 | 3142 | optionally selected with the optional ``gui`` argument. |
|
3141 | 3143 | |
|
3142 | 3144 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
3143 | 3145 | |
|
3144 | 3146 | Parameters |
|
3145 | 3147 | ---------- |
|
3146 | 3148 | gui : optional, string |
|
3147 | 3149 | If given, dictates the choice of matplotlib GUI backend to use |
|
3148 | 3150 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
3149 | 3151 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
3150 | 3152 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
3151 | 3153 | user's matplotlibrc configuration file). Note that not all backends |
|
3152 | 3154 | make sense in all contexts, for example a terminal ipython can't |
|
3153 | 3155 | display figures inline. |
|
3154 | 3156 | import_all : optional, bool, default: True |
|
3155 | 3157 | Whether to do `from numpy import *` and `from pylab import *` |
|
3156 | 3158 | in addition to module imports. |
|
3157 | 3159 | welcome_message : deprecated |
|
3158 | 3160 | This argument is ignored, no welcome message will be displayed. |
|
3159 | 3161 | """ |
|
3160 | 3162 | from IPython.core.pylabtools import import_pylab |
|
3161 | 3163 | |
|
3162 | 3164 | gui, backend = self.enable_matplotlib(gui) |
|
3163 | 3165 | |
|
3164 | 3166 | # We want to prevent the loading of pylab to pollute the user's |
|
3165 | 3167 | # namespace as shown by the %who* magics, so we execute the activation |
|
3166 | 3168 | # code in an empty namespace, and we update *both* user_ns and |
|
3167 | 3169 | # user_ns_hidden with this information. |
|
3168 | 3170 | ns = {} |
|
3169 | 3171 | import_pylab(ns, import_all) |
|
3170 | 3172 | # warn about clobbered names |
|
3171 | 3173 | ignored = {"__builtins__"} |
|
3172 | 3174 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
3173 | 3175 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
3174 | 3176 | self.user_ns.update(ns) |
|
3175 | 3177 | self.user_ns_hidden.update(ns) |
|
3176 | 3178 | return gui, backend, clobbered |
|
3177 | 3179 | |
|
3178 | 3180 | #------------------------------------------------------------------------- |
|
3179 | 3181 | # Utilities |
|
3180 | 3182 | #------------------------------------------------------------------------- |
|
3181 | 3183 | |
|
3182 | 3184 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
3183 | 3185 | """Expand python variables in a string. |
|
3184 | 3186 | |
|
3185 | 3187 | The depth argument indicates how many frames above the caller should |
|
3186 | 3188 | be walked to look for the local namespace where to expand variables. |
|
3187 | 3189 | |
|
3188 | 3190 | The global namespace for expansion is always the user's interactive |
|
3189 | 3191 | namespace. |
|
3190 | 3192 | """ |
|
3191 | 3193 | ns = self.user_ns.copy() |
|
3192 | 3194 | try: |
|
3193 | 3195 | frame = sys._getframe(depth+1) |
|
3194 | 3196 | except ValueError: |
|
3195 | 3197 | # This is thrown if there aren't that many frames on the stack, |
|
3196 | 3198 | # e.g. if a script called run_line_magic() directly. |
|
3197 | 3199 | pass |
|
3198 | 3200 | else: |
|
3199 | 3201 | ns.update(frame.f_locals) |
|
3200 | 3202 | |
|
3201 | 3203 | try: |
|
3202 | 3204 | # We have to use .vformat() here, because 'self' is a valid and common |
|
3203 | 3205 | # name, and expanding **ns for .format() would make it collide with |
|
3204 | 3206 | # the 'self' argument of the method. |
|
3205 | 3207 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
3206 | 3208 | except Exception: |
|
3207 | 3209 | # if formatter couldn't format, just let it go untransformed |
|
3208 | 3210 | pass |
|
3209 | 3211 | return cmd |
|
3210 | 3212 | |
|
3211 | 3213 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
3212 | 3214 | """Make a new tempfile and return its filename. |
|
3213 | 3215 | |
|
3214 | 3216 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), |
|
3215 | 3217 | but it registers the created filename internally so ipython cleans it up |
|
3216 | 3218 | at exit time. |
|
3217 | 3219 | |
|
3218 | 3220 | Optional inputs: |
|
3219 | 3221 | |
|
3220 | 3222 | - data(None): if data is given, it gets written out to the temp file |
|
3221 | 3223 | immediately, and the file is closed again.""" |
|
3222 | 3224 | |
|
3223 | 3225 | dirname = tempfile.mkdtemp(prefix=prefix) |
|
3224 | 3226 | self.tempdirs.append(dirname) |
|
3225 | 3227 | |
|
3226 | 3228 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) |
|
3227 | 3229 | os.close(handle) # On Windows, there can only be one open handle on a file |
|
3228 | 3230 | self.tempfiles.append(filename) |
|
3229 | 3231 | |
|
3230 | 3232 | if data: |
|
3231 | 3233 | tmp_file = open(filename,'w') |
|
3232 | 3234 | tmp_file.write(data) |
|
3233 | 3235 | tmp_file.close() |
|
3234 | 3236 | return filename |
|
3235 | 3237 | |
|
3236 | 3238 | # TODO: This should be removed when Term is refactored. |
|
3237 | 3239 | def write(self,data): |
|
3238 | 3240 | """Write a string to the default output""" |
|
3239 | 3241 | io.stdout.write(data) |
|
3240 | 3242 | |
|
3241 | 3243 | # TODO: This should be removed when Term is refactored. |
|
3242 | 3244 | def write_err(self,data): |
|
3243 | 3245 | """Write a string to the default error output""" |
|
3244 | 3246 | io.stderr.write(data) |
|
3245 | 3247 | |
|
3246 | 3248 | def ask_yes_no(self, prompt, default=None, interrupt=None): |
|
3247 | 3249 | if self.quiet: |
|
3248 | 3250 | return True |
|
3249 | 3251 | return ask_yes_no(prompt,default,interrupt) |
|
3250 | 3252 | |
|
3251 | 3253 | def show_usage(self): |
|
3252 | 3254 | """Show a usage message""" |
|
3253 | 3255 | page.page(IPython.core.usage.interactive_usage) |
|
3254 | 3256 | |
|
3255 | 3257 | def extract_input_lines(self, range_str, raw=False): |
|
3256 | 3258 | """Return as a string a set of input history slices. |
|
3257 | 3259 | |
|
3258 | 3260 | Parameters |
|
3259 | 3261 | ---------- |
|
3260 | 3262 | range_str : string |
|
3261 | 3263 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3262 | 3264 | since this function is for use by magic functions which get their |
|
3263 | 3265 | arguments as strings. The number before the / is the session |
|
3264 | 3266 | number: ~n goes n back from the current session. |
|
3265 | 3267 | |
|
3266 | 3268 | raw : bool, optional |
|
3267 | 3269 | By default, the processed input is used. If this is true, the raw |
|
3268 | 3270 | input history is used instead. |
|
3269 | 3271 | |
|
3270 | 3272 | Notes |
|
3271 | 3273 | ----- |
|
3272 | 3274 | |
|
3273 | 3275 | Slices can be described with two notations: |
|
3274 | 3276 | |
|
3275 | 3277 | * ``N:M`` -> standard python form, means including items N...(M-1). |
|
3276 | 3278 | * ``N-M`` -> include items N..M (closed endpoint). |
|
3277 | 3279 | """ |
|
3278 | 3280 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3279 | 3281 | return "\n".join(x for _, _, x in lines) |
|
3280 | 3282 | |
|
3281 | 3283 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
|
3282 | 3284 | """Get a code string from history, file, url, or a string or macro. |
|
3283 | 3285 | |
|
3284 | 3286 | This is mainly used by magic functions. |
|
3285 | 3287 | |
|
3286 | 3288 | Parameters |
|
3287 | 3289 | ---------- |
|
3288 | 3290 | |
|
3289 | 3291 | target : str |
|
3290 | 3292 | |
|
3291 | 3293 | A string specifying code to retrieve. This will be tried respectively |
|
3292 | 3294 | as: ranges of input history (see %history for syntax), url, |
|
3293 | 3295 | corresponding .py file, filename, or an expression evaluating to a |
|
3294 | 3296 | string or Macro in the user namespace. |
|
3295 | 3297 | |
|
3296 | 3298 | raw : bool |
|
3297 | 3299 | If true (default), retrieve raw history. Has no effect on the other |
|
3298 | 3300 | retrieval mechanisms. |
|
3299 | 3301 | |
|
3300 | 3302 | py_only : bool (default False) |
|
3301 | 3303 | Only try to fetch python code, do not try alternative methods to decode file |
|
3302 | 3304 | if unicode fails. |
|
3303 | 3305 | |
|
3304 | 3306 | Returns |
|
3305 | 3307 | ------- |
|
3306 | 3308 | A string of code. |
|
3307 | 3309 | |
|
3308 | 3310 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3309 | 3311 | to an object of another type. In each case, .args[0] is a printable |
|
3310 | 3312 | message. |
|
3311 | 3313 | """ |
|
3312 | 3314 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3313 | 3315 | if code: |
|
3314 | 3316 | return code |
|
3315 | 3317 | utarget = unquote_filename(target) |
|
3316 | 3318 | try: |
|
3317 | 3319 | if utarget.startswith(('http://', 'https://')): |
|
3318 | 3320 | return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie) |
|
3319 | 3321 | except UnicodeDecodeError: |
|
3320 | 3322 | if not py_only : |
|
3321 | 3323 | # Deferred import |
|
3322 | 3324 | try: |
|
3323 | 3325 | from urllib.request import urlopen # Py3 |
|
3324 | 3326 | except ImportError: |
|
3325 | 3327 | from urllib import urlopen |
|
3326 | 3328 | response = urlopen(target) |
|
3327 | 3329 | return response.read().decode('latin1') |
|
3328 | 3330 | raise ValueError(("'%s' seem to be unreadable.") % utarget) |
|
3329 | 3331 | |
|
3330 | 3332 | potential_target = [target] |
|
3331 | 3333 | try : |
|
3332 | 3334 | potential_target.insert(0,get_py_filename(target)) |
|
3333 | 3335 | except IOError: |
|
3334 | 3336 | pass |
|
3335 | 3337 | |
|
3336 | 3338 | for tgt in potential_target : |
|
3337 | 3339 | if os.path.isfile(tgt): # Read file |
|
3338 | 3340 | try : |
|
3339 | 3341 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3340 | 3342 | except UnicodeDecodeError : |
|
3341 | 3343 | if not py_only : |
|
3342 | 3344 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3343 | 3345 | return f.read() |
|
3344 | 3346 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3345 | 3347 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3346 | 3348 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3347 | 3349 | |
|
3348 | 3350 | if search_ns: |
|
3349 | 3351 | # Inspect namespace to load object source |
|
3350 | 3352 | object_info = self.object_inspect(target, detail_level=1) |
|
3351 | 3353 | if object_info['found'] and object_info['source']: |
|
3352 | 3354 | return object_info['source'] |
|
3353 | 3355 | |
|
3354 | 3356 | try: # User namespace |
|
3355 | 3357 | codeobj = eval(target, self.user_ns) |
|
3356 | 3358 | except Exception: |
|
3357 | 3359 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3358 | 3360 | "nor in the user namespace.") % target) |
|
3359 | 3361 | |
|
3360 | 3362 | if isinstance(codeobj, string_types): |
|
3361 | 3363 | return codeobj |
|
3362 | 3364 | elif isinstance(codeobj, Macro): |
|
3363 | 3365 | return codeobj.value |
|
3364 | 3366 | |
|
3365 | 3367 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3366 | 3368 | codeobj) |
|
3367 | 3369 | |
|
3368 | 3370 | #------------------------------------------------------------------------- |
|
3369 | 3371 | # Things related to IPython exiting |
|
3370 | 3372 | #------------------------------------------------------------------------- |
|
3371 | 3373 | def atexit_operations(self): |
|
3372 | 3374 | """This will be executed at the time of exit. |
|
3373 | 3375 | |
|
3374 | 3376 | Cleanup operations and saving of persistent data that is done |
|
3375 | 3377 | unconditionally by IPython should be performed here. |
|
3376 | 3378 | |
|
3377 | 3379 | For things that may depend on startup flags or platform specifics (such |
|
3378 | 3380 | as having readline or not), register a separate atexit function in the |
|
3379 | 3381 | code that has the appropriate information, rather than trying to |
|
3380 | 3382 | clutter |
|
3381 | 3383 | """ |
|
3382 | 3384 | # Close the history session (this stores the end time and line count) |
|
3383 | 3385 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3384 | 3386 | # history db |
|
3385 | 3387 | self.history_manager.end_session() |
|
3386 | 3388 | |
|
3387 | 3389 | # Cleanup all tempfiles and folders left around |
|
3388 | 3390 | for tfile in self.tempfiles: |
|
3389 | 3391 | try: |
|
3390 | 3392 | os.unlink(tfile) |
|
3391 | 3393 | except OSError: |
|
3392 | 3394 | pass |
|
3393 | 3395 | |
|
3394 | 3396 | for tdir in self.tempdirs: |
|
3395 | 3397 | try: |
|
3396 | 3398 | os.rmdir(tdir) |
|
3397 | 3399 | except OSError: |
|
3398 | 3400 | pass |
|
3399 | 3401 | |
|
3400 | 3402 | # Clear all user namespaces to release all references cleanly. |
|
3401 | 3403 | self.reset(new_session=False) |
|
3402 | 3404 | |
|
3403 | 3405 | # Run user hooks |
|
3404 | 3406 | self.hooks.shutdown_hook() |
|
3405 | 3407 | |
|
3406 | 3408 | def cleanup(self): |
|
3407 | 3409 | self.restore_sys_module_state() |
|
3408 | 3410 | |
|
3409 | 3411 | |
|
3410 | 3412 | class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)): |
|
3411 | 3413 | """An abstract base class for InteractiveShell.""" |
|
3412 | 3414 | |
|
3413 | 3415 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,702 +1,704 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | from __future__ import print_function |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
8 | 8 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> |
|
9 | 9 | # Copyright (C) 2008 The IPython Development Team |
|
10 | 10 | |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | 12 | # the file COPYING, distributed as part of this software. |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Imports |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | # Stdlib |
|
19 | 19 | import os |
|
20 | 20 | import re |
|
21 | 21 | import sys |
|
22 | 22 | import types |
|
23 | 23 | from getopt import getopt, GetoptError |
|
24 | 24 | |
|
25 | 25 | # Our own |
|
26 | 26 | from traitlets.config.configurable import Configurable |
|
27 | 27 | from IPython.core import oinspect |
|
28 | 28 | from IPython.core.error import UsageError |
|
29 | 29 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 |
|
30 | 30 | from decorator import decorator |
|
31 | 31 | from IPython.utils.ipstruct import Struct |
|
32 | 32 | from IPython.utils.process import arg_split |
|
33 | 33 | from IPython.utils.py3compat import string_types, iteritems |
|
34 | 34 | from IPython.utils.text import dedent |
|
35 | 35 | from traitlets import Bool, Dict, Instance |
|
36 | 36 | from IPython.utils.warn import error |
|
37 | 37 | |
|
38 | 38 | #----------------------------------------------------------------------------- |
|
39 | 39 | # Globals |
|
40 | 40 | #----------------------------------------------------------------------------- |
|
41 | 41 | |
|
42 | 42 | # A dict we'll use for each class that has magics, used as temporary storage to |
|
43 | 43 | # pass information between the @line/cell_magic method decorators and the |
|
44 | 44 | # @magics_class class decorator, because the method decorators have no |
|
45 | 45 | # access to the class when they run. See for more details: |
|
46 | 46 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class |
|
47 | 47 | |
|
48 | 48 | magics = dict(line={}, cell={}) |
|
49 | 49 | |
|
50 | 50 | magic_kinds = ('line', 'cell') |
|
51 | 51 | magic_spec = ('line', 'cell', 'line_cell') |
|
52 | 52 | magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2) |
|
53 | 53 | |
|
54 | 54 | #----------------------------------------------------------------------------- |
|
55 | 55 | # Utility classes and functions |
|
56 | 56 | #----------------------------------------------------------------------------- |
|
57 | 57 | |
|
58 | 58 | class Bunch: pass |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | def on_off(tag): |
|
62 | 62 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
63 | 63 | return ['OFF','ON'][tag] |
|
64 | 64 | |
|
65 | 65 | |
|
66 | 66 | def compress_dhist(dh): |
|
67 | 67 | """Compress a directory history into a new one with at most 20 entries. |
|
68 | 68 | |
|
69 | 69 | Return a new list made from the first and last 10 elements of dhist after |
|
70 | 70 | removal of duplicates. |
|
71 | 71 | """ |
|
72 | 72 | head, tail = dh[:-10], dh[-10:] |
|
73 | 73 | |
|
74 | 74 | newhead = [] |
|
75 | 75 | done = set() |
|
76 | 76 | for h in head: |
|
77 | 77 | if h in done: |
|
78 | 78 | continue |
|
79 | 79 | newhead.append(h) |
|
80 | 80 | done.add(h) |
|
81 | 81 | |
|
82 | 82 | return newhead + tail |
|
83 | 83 | |
|
84 | 84 | |
|
85 | 85 | def needs_local_scope(func): |
|
86 | 86 | """Decorator to mark magic functions which need to local scope to run.""" |
|
87 | 87 | func.needs_local_scope = True |
|
88 | 88 | return func |
|
89 | 89 | |
|
90 | 90 | #----------------------------------------------------------------------------- |
|
91 | 91 | # Class and method decorators for registering magics |
|
92 | 92 | #----------------------------------------------------------------------------- |
|
93 | 93 | |
|
94 | 94 | def magics_class(cls): |
|
95 | 95 | """Class decorator for all subclasses of the main Magics class. |
|
96 | 96 | |
|
97 | 97 | Any class that subclasses Magics *must* also apply this decorator, to |
|
98 | 98 | ensure that all the methods that have been decorated as line/cell magics |
|
99 | 99 | get correctly registered in the class instance. This is necessary because |
|
100 | 100 | when method decorators run, the class does not exist yet, so they |
|
101 | 101 | temporarily store their information into a module global. Application of |
|
102 | 102 | this class decorator copies that global data to the class instance and |
|
103 | 103 | clears the global. |
|
104 | 104 | |
|
105 | 105 | Obviously, this mechanism is not thread-safe, which means that the |
|
106 | 106 | *creation* of subclasses of Magic should only be done in a single-thread |
|
107 | 107 | context. Instantiation of the classes has no restrictions. Given that |
|
108 | 108 | these classes are typically created at IPython startup time and before user |
|
109 | 109 | application code becomes active, in practice this should not pose any |
|
110 | 110 | problems. |
|
111 | 111 | """ |
|
112 | 112 | cls.registered = True |
|
113 | 113 | cls.magics = dict(line = magics['line'], |
|
114 | 114 | cell = magics['cell']) |
|
115 | 115 | magics['line'] = {} |
|
116 | 116 | magics['cell'] = {} |
|
117 | 117 | return cls |
|
118 | 118 | |
|
119 | 119 | |
|
120 | 120 | def record_magic(dct, magic_kind, magic_name, func): |
|
121 | 121 | """Utility function to store a function as a magic of a specific kind. |
|
122 | 122 | |
|
123 | 123 | Parameters |
|
124 | 124 | ---------- |
|
125 | 125 | dct : dict |
|
126 | 126 | A dictionary with 'line' and 'cell' subdicts. |
|
127 | 127 | |
|
128 | 128 | magic_kind : str |
|
129 | 129 | Kind of magic to be stored. |
|
130 | 130 | |
|
131 | 131 | magic_name : str |
|
132 | 132 | Key to store the magic as. |
|
133 | 133 | |
|
134 | 134 | func : function |
|
135 | 135 | Callable object to store. |
|
136 | 136 | """ |
|
137 | 137 | if magic_kind == 'line_cell': |
|
138 | 138 | dct['line'][magic_name] = dct['cell'][magic_name] = func |
|
139 | 139 | else: |
|
140 | 140 | dct[magic_kind][magic_name] = func |
|
141 | 141 | |
|
142 | 142 | |
|
143 | 143 | def validate_type(magic_kind): |
|
144 | 144 | """Ensure that the given magic_kind is valid. |
|
145 | 145 | |
|
146 | 146 | Check that the given magic_kind is one of the accepted spec types (stored |
|
147 | 147 | in the global `magic_spec`), raise ValueError otherwise. |
|
148 | 148 | """ |
|
149 | 149 | if magic_kind not in magic_spec: |
|
150 | 150 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
151 | 151 | magic_kinds, magic_kind) |
|
152 | 152 | |
|
153 | 153 | |
|
154 | 154 | # The docstrings for the decorator below will be fairly similar for the two |
|
155 | 155 | # types (method and function), so we generate them here once and reuse the |
|
156 | 156 | # templates below. |
|
157 | 157 | _docstring_template = \ |
|
158 | 158 | """Decorate the given {0} as {1} magic. |
|
159 | 159 | |
|
160 | 160 | The decorator can be used with or without arguments, as follows. |
|
161 | 161 | |
|
162 | 162 | i) without arguments: it will create a {1} magic named as the {0} being |
|
163 | 163 | decorated:: |
|
164 | 164 | |
|
165 | 165 | @deco |
|
166 | 166 | def foo(...) |
|
167 | 167 | |
|
168 | 168 | will create a {1} magic named `foo`. |
|
169 | 169 | |
|
170 | 170 | ii) with one string argument: which will be used as the actual name of the |
|
171 | 171 | resulting magic:: |
|
172 | 172 | |
|
173 | 173 | @deco('bar') |
|
174 | 174 | def foo(...) |
|
175 | 175 | |
|
176 | 176 | will create a {1} magic named `bar`. |
|
177 | 177 | """ |
|
178 | 178 | |
|
179 | 179 | # These two are decorator factories. While they are conceptually very similar, |
|
180 | 180 | # there are enough differences in the details that it's simpler to have them |
|
181 | 181 | # written as completely standalone functions rather than trying to share code |
|
182 | 182 | # and make a single one with convoluted logic. |
|
183 | 183 | |
|
184 | 184 | def _method_magic_marker(magic_kind): |
|
185 | 185 | """Decorator factory for methods in Magics subclasses. |
|
186 | 186 | """ |
|
187 | 187 | |
|
188 | 188 | validate_type(magic_kind) |
|
189 | 189 | |
|
190 | 190 | # This is a closure to capture the magic_kind. We could also use a class, |
|
191 | 191 | # but it's overkill for just that one bit of state. |
|
192 | 192 | def magic_deco(arg): |
|
193 | 193 | call = lambda f, *a, **k: f(*a, **k) |
|
194 | 194 | |
|
195 | 195 | if callable(arg): |
|
196 | 196 | # "Naked" decorator call (just @foo, no args) |
|
197 | 197 | func = arg |
|
198 | 198 | name = func.__name__ |
|
199 | 199 | retval = decorator(call, func) |
|
200 | 200 | record_magic(magics, magic_kind, name, name) |
|
201 | 201 | elif isinstance(arg, string_types): |
|
202 | 202 | # Decorator called with arguments (@foo('bar')) |
|
203 | 203 | name = arg |
|
204 | 204 | def mark(func, *a, **kw): |
|
205 | 205 | record_magic(magics, magic_kind, name, func.__name__) |
|
206 | 206 | return decorator(call, func) |
|
207 | 207 | retval = mark |
|
208 | 208 | else: |
|
209 | 209 | raise TypeError("Decorator can only be called with " |
|
210 | 210 | "string or function") |
|
211 | 211 | return retval |
|
212 | 212 | |
|
213 | 213 | # Ensure the resulting decorator has a usable docstring |
|
214 | 214 | magic_deco.__doc__ = _docstring_template.format('method', magic_kind) |
|
215 | 215 | return magic_deco |
|
216 | 216 | |
|
217 | 217 | |
|
218 | 218 | def _function_magic_marker(magic_kind): |
|
219 | 219 | """Decorator factory for standalone functions. |
|
220 | 220 | """ |
|
221 | 221 | validate_type(magic_kind) |
|
222 | 222 | |
|
223 | 223 | # This is a closure to capture the magic_kind. We could also use a class, |
|
224 | 224 | # but it's overkill for just that one bit of state. |
|
225 | 225 | def magic_deco(arg): |
|
226 | 226 | call = lambda f, *a, **k: f(*a, **k) |
|
227 | 227 | |
|
228 | 228 | # Find get_ipython() in the caller's namespace |
|
229 | 229 | caller = sys._getframe(1) |
|
230 | 230 | for ns in ['f_locals', 'f_globals', 'f_builtins']: |
|
231 | 231 | get_ipython = getattr(caller, ns).get('get_ipython') |
|
232 | 232 | if get_ipython is not None: |
|
233 | 233 | break |
|
234 | 234 | else: |
|
235 | 235 | raise NameError('Decorator can only run in context where ' |
|
236 | 236 | '`get_ipython` exists') |
|
237 | 237 | |
|
238 | 238 | ip = get_ipython() |
|
239 | 239 | |
|
240 | 240 | if callable(arg): |
|
241 | 241 | # "Naked" decorator call (just @foo, no args) |
|
242 | 242 | func = arg |
|
243 | 243 | name = func.__name__ |
|
244 | 244 | ip.register_magic_function(func, magic_kind, name) |
|
245 | 245 | retval = decorator(call, func) |
|
246 | 246 | elif isinstance(arg, string_types): |
|
247 | 247 | # Decorator called with arguments (@foo('bar')) |
|
248 | 248 | name = arg |
|
249 | 249 | def mark(func, *a, **kw): |
|
250 | 250 | ip.register_magic_function(func, magic_kind, name) |
|
251 | 251 | return decorator(call, func) |
|
252 | 252 | retval = mark |
|
253 | 253 | else: |
|
254 | 254 | raise TypeError("Decorator can only be called with " |
|
255 | 255 | "string or function") |
|
256 | 256 | return retval |
|
257 | 257 | |
|
258 | 258 | # Ensure the resulting decorator has a usable docstring |
|
259 | 259 | ds = _docstring_template.format('function', magic_kind) |
|
260 | 260 | |
|
261 | 261 | ds += dedent(""" |
|
262 | 262 | Note: this decorator can only be used in a context where IPython is already |
|
263 | 263 | active, so that the `get_ipython()` call succeeds. You can therefore use |
|
264 | 264 | it in your startup files loaded after IPython initializes, but *not* in the |
|
265 | 265 | IPython configuration file itself, which is executed before IPython is |
|
266 | 266 | fully up and running. Any file located in the `startup` subdirectory of |
|
267 | 267 | your configuration profile will be OK in this sense. |
|
268 | 268 | """) |
|
269 | 269 | |
|
270 | 270 | magic_deco.__doc__ = ds |
|
271 | 271 | return magic_deco |
|
272 | 272 | |
|
273 | 273 | |
|
274 | 274 | # Create the actual decorators for public use |
|
275 | 275 | |
|
276 | 276 | # These three are used to decorate methods in class definitions |
|
277 | 277 | line_magic = _method_magic_marker('line') |
|
278 | 278 | cell_magic = _method_magic_marker('cell') |
|
279 | 279 | line_cell_magic = _method_magic_marker('line_cell') |
|
280 | 280 | |
|
281 | 281 | # These three decorate standalone functions and perform the decoration |
|
282 | 282 | # immediately. They can only run where get_ipython() works |
|
283 | 283 | register_line_magic = _function_magic_marker('line') |
|
284 | 284 | register_cell_magic = _function_magic_marker('cell') |
|
285 | 285 | register_line_cell_magic = _function_magic_marker('line_cell') |
|
286 | 286 | |
|
287 | 287 | #----------------------------------------------------------------------------- |
|
288 | 288 | # Core Magic classes |
|
289 | 289 | #----------------------------------------------------------------------------- |
|
290 | 290 | |
|
291 | 291 | class MagicsManager(Configurable): |
|
292 | 292 | """Object that handles all magic-related functionality for IPython. |
|
293 | 293 | """ |
|
294 | 294 | # Non-configurable class attributes |
|
295 | 295 | |
|
296 | 296 | # A two-level dict, first keyed by magic type, then by magic function, and |
|
297 | 297 | # holding the actual callable object as value. This is the dict used for |
|
298 | 298 | # magic function dispatch |
|
299 | 299 | magics = Dict() |
|
300 | 300 | |
|
301 | 301 | # A registry of the original objects that we've been given holding magics. |
|
302 | 302 | registry = Dict() |
|
303 | 303 | |
|
304 | 304 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) |
|
305 | 305 | |
|
306 | 306 | auto_magic = Bool(True, config=True, help= |
|
307 | 307 | "Automatically call line magics without requiring explicit % prefix") |
|
308 | 308 | |
|
309 | 309 | def _auto_magic_changed(self, name, value): |
|
310 | 310 | self.shell.automagic = value |
|
311 | 311 | |
|
312 | 312 | _auto_status = [ |
|
313 | 313 | 'Automagic is OFF, % prefix IS needed for line magics.', |
|
314 | 314 | 'Automagic is ON, % prefix IS NOT needed for line magics.'] |
|
315 | 315 | |
|
316 | 316 | user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True) |
|
317 | 317 | |
|
318 | 318 | def __init__(self, shell=None, config=None, user_magics=None, **traits): |
|
319 | 319 | |
|
320 | 320 | super(MagicsManager, self).__init__(shell=shell, config=config, |
|
321 | 321 | user_magics=user_magics, **traits) |
|
322 | 322 | self.magics = dict(line={}, cell={}) |
|
323 | 323 | # Let's add the user_magics to the registry for uniformity, so *all* |
|
324 | 324 | # registered magic containers can be found there. |
|
325 | 325 | self.registry[user_magics.__class__.__name__] = user_magics |
|
326 | 326 | |
|
327 | 327 | def auto_status(self): |
|
328 | 328 | """Return descriptive string with automagic status.""" |
|
329 | 329 | return self._auto_status[self.auto_magic] |
|
330 | 330 | |
|
331 | 331 | def lsmagic(self): |
|
332 | 332 | """Return a dict of currently available magic functions. |
|
333 | 333 | |
|
334 | 334 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
335 | 335 | two types of magics we support. Each value is a list of names. |
|
336 | 336 | """ |
|
337 | 337 | return self.magics |
|
338 | 338 | |
|
339 | 339 | def lsmagic_docs(self, brief=False, missing=''): |
|
340 | 340 | """Return dict of documentation of magic functions. |
|
341 | 341 | |
|
342 | 342 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
343 | 343 | two types of magics we support. Each value is a dict keyed by magic |
|
344 | 344 | name whose value is the function docstring. If a docstring is |
|
345 | 345 | unavailable, the value of `missing` is used instead. |
|
346 | 346 | |
|
347 | 347 | If brief is True, only the first line of each docstring will be returned. |
|
348 | 348 | """ |
|
349 | 349 | docs = {} |
|
350 | 350 | for m_type in self.magics: |
|
351 | 351 | m_docs = {} |
|
352 | 352 | for m_name, m_func in iteritems(self.magics[m_type]): |
|
353 | 353 | if m_func.__doc__: |
|
354 | 354 | if brief: |
|
355 | 355 | m_docs[m_name] = m_func.__doc__.split('\n', 1)[0] |
|
356 | 356 | else: |
|
357 | 357 | m_docs[m_name] = m_func.__doc__.rstrip() |
|
358 | 358 | else: |
|
359 | 359 | m_docs[m_name] = missing |
|
360 | 360 | docs[m_type] = m_docs |
|
361 | 361 | return docs |
|
362 | 362 | |
|
363 | 363 | def register(self, *magic_objects): |
|
364 | 364 | """Register one or more instances of Magics. |
|
365 | 365 | |
|
366 | 366 | Take one or more classes or instances of classes that subclass the main |
|
367 | 367 | `core.Magic` class, and register them with IPython to use the magic |
|
368 | 368 | functions they provide. The registration process will then ensure that |
|
369 | 369 | any methods that have decorated to provide line and/or cell magics will |
|
370 | 370 | be recognized with the `%x`/`%%x` syntax as a line/cell magic |
|
371 | 371 | respectively. |
|
372 | 372 | |
|
373 | 373 | If classes are given, they will be instantiated with the default |
|
374 | 374 | constructor. If your classes need a custom constructor, you should |
|
375 | 375 | instanitate them first and pass the instance. |
|
376 | 376 | |
|
377 | 377 | The provided arguments can be an arbitrary mix of classes and instances. |
|
378 | 378 | |
|
379 | 379 | Parameters |
|
380 | 380 | ---------- |
|
381 | 381 | magic_objects : one or more classes or instances |
|
382 | 382 | """ |
|
383 | 383 | # Start by validating them to ensure they have all had their magic |
|
384 | 384 | # methods registered at the instance level |
|
385 | 385 | for m in magic_objects: |
|
386 | 386 | if not m.registered: |
|
387 | 387 | raise ValueError("Class of magics %r was constructed without " |
|
388 | 388 | "the @register_magics class decorator") |
|
389 | 389 | if isinstance(m, type): |
|
390 | 390 | # If we're given an uninstantiated class |
|
391 | 391 | m = m(shell=self.shell) |
|
392 | 392 | |
|
393 | 393 | # Now that we have an instance, we can register it and update the |
|
394 | 394 | # table of callables |
|
395 | 395 | self.registry[m.__class__.__name__] = m |
|
396 | 396 | for mtype in magic_kinds: |
|
397 | 397 | self.magics[mtype].update(m.magics[mtype]) |
|
398 | 398 | |
|
399 | 399 | def register_function(self, func, magic_kind='line', magic_name=None): |
|
400 | 400 | """Expose a standalone function as magic function for IPython. |
|
401 | 401 | |
|
402 | 402 | This will create an IPython magic (line, cell or both) from a |
|
403 | 403 | standalone function. The functions should have the following |
|
404 | 404 | signatures: |
|
405 | 405 | |
|
406 | 406 | * For line magics: `def f(line)` |
|
407 | 407 | * For cell magics: `def f(line, cell)` |
|
408 | 408 | * For a function that does both: `def f(line, cell=None)` |
|
409 | 409 | |
|
410 | 410 | In the latter case, the function will be called with `cell==None` when |
|
411 | 411 | invoked as `%f`, and with cell as a string when invoked as `%%f`. |
|
412 | 412 | |
|
413 | 413 | Parameters |
|
414 | 414 | ---------- |
|
415 | 415 | func : callable |
|
416 | 416 | Function to be registered as a magic. |
|
417 | 417 | |
|
418 | 418 | magic_kind : str |
|
419 | 419 | Kind of magic, one of 'line', 'cell' or 'line_cell' |
|
420 | 420 | |
|
421 | 421 | magic_name : optional str |
|
422 | 422 | If given, the name the magic will have in the IPython namespace. By |
|
423 | 423 | default, the name of the function itself is used. |
|
424 | 424 | """ |
|
425 | 425 | |
|
426 | 426 | # Create the new method in the user_magics and register it in the |
|
427 | 427 | # global table |
|
428 | 428 | validate_type(magic_kind) |
|
429 | 429 | magic_name = func.__name__ if magic_name is None else magic_name |
|
430 | 430 | setattr(self.user_magics, magic_name, func) |
|
431 | 431 | record_magic(self.magics, magic_kind, magic_name, func) |
|
432 | 432 | |
|
433 | 433 | def define_magic(self, name, func): |
|
434 | 434 | """[Deprecated] Expose own function as magic function for IPython. |
|
435 | 435 | |
|
436 | Will be removed in IPython 5.0 | |
|
437 | ||
|
436 | 438 | Example:: |
|
437 | 439 | |
|
438 | 440 | def foo_impl(self, parameter_s=''): |
|
439 | 441 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
440 | 442 | print 'Magic function. Passed parameter is between < >:' |
|
441 | 443 | print '<%s>' % parameter_s |
|
442 | 444 | print 'The self object is:', self |
|
443 | 445 | |
|
444 | 446 | ip.define_magic('foo',foo_impl) |
|
445 | 447 | """ |
|
446 | 448 | meth = types.MethodType(func, self.user_magics) |
|
447 | 449 | setattr(self.user_magics, name, meth) |
|
448 | 450 | record_magic(self.magics, 'line', name, meth) |
|
449 | 451 | |
|
450 | 452 | def register_alias(self, alias_name, magic_name, magic_kind='line'): |
|
451 | 453 | """Register an alias to a magic function. |
|
452 | 454 | |
|
453 | 455 | The alias is an instance of :class:`MagicAlias`, which holds the |
|
454 | 456 | name and kind of the magic it should call. Binding is done at |
|
455 | 457 | call time, so if the underlying magic function is changed the alias |
|
456 | 458 | will call the new function. |
|
457 | 459 | |
|
458 | 460 | Parameters |
|
459 | 461 | ---------- |
|
460 | 462 | alias_name : str |
|
461 | 463 | The name of the magic to be registered. |
|
462 | 464 | |
|
463 | 465 | magic_name : str |
|
464 | 466 | The name of an existing magic. |
|
465 | 467 | |
|
466 | 468 | magic_kind : str |
|
467 | 469 | Kind of magic, one of 'line' or 'cell' |
|
468 | 470 | """ |
|
469 | 471 | |
|
470 | 472 | # `validate_type` is too permissive, as it allows 'line_cell' |
|
471 | 473 | # which we do not handle. |
|
472 | 474 | if magic_kind not in magic_kinds: |
|
473 | 475 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
474 | 476 | magic_kinds, magic_kind) |
|
475 | 477 | |
|
476 | 478 | alias = MagicAlias(self.shell, magic_name, magic_kind) |
|
477 | 479 | setattr(self.user_magics, alias_name, alias) |
|
478 | 480 | record_magic(self.magics, magic_kind, alias_name, alias) |
|
479 | 481 | |
|
480 | 482 | # Key base class that provides the central functionality for magics. |
|
481 | 483 | |
|
482 | 484 | |
|
483 | 485 | class Magics(Configurable): |
|
484 | 486 | """Base class for implementing magic functions. |
|
485 | 487 | |
|
486 | 488 | Shell functions which can be reached as %function_name. All magic |
|
487 | 489 | functions should accept a string, which they can parse for their own |
|
488 | 490 | needs. This can make some functions easier to type, eg `%cd ../` |
|
489 | 491 | vs. `%cd("../")` |
|
490 | 492 | |
|
491 | 493 | Classes providing magic functions need to subclass this class, and they |
|
492 | 494 | MUST: |
|
493 | 495 | |
|
494 | 496 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate |
|
495 | 497 | individual methods as magic functions, AND |
|
496 | 498 | |
|
497 | 499 | - Use the class decorator `@magics_class` to ensure that the magic |
|
498 | 500 | methods are properly registered at the instance level upon instance |
|
499 | 501 | initialization. |
|
500 | 502 | |
|
501 | 503 | See :mod:`magic_functions` for examples of actual implementation classes. |
|
502 | 504 | """ |
|
503 | 505 | # Dict holding all command-line options for each magic. |
|
504 | 506 | options_table = None |
|
505 | 507 | # Dict for the mapping of magic names to methods, set by class decorator |
|
506 | 508 | magics = None |
|
507 | 509 | # Flag to check that the class decorator was properly applied |
|
508 | 510 | registered = False |
|
509 | 511 | # Instance of IPython shell |
|
510 | 512 | shell = None |
|
511 | 513 | |
|
512 | 514 | def __init__(self, shell=None, **kwargs): |
|
513 | 515 | if not(self.__class__.registered): |
|
514 | 516 | raise ValueError('Magics subclass without registration - ' |
|
515 | 517 | 'did you forget to apply @magics_class?') |
|
516 | 518 | if shell is not None: |
|
517 | 519 | if hasattr(shell, 'configurables'): |
|
518 | 520 | shell.configurables.append(self) |
|
519 | 521 | if hasattr(shell, 'config'): |
|
520 | 522 | kwargs.setdefault('parent', shell) |
|
521 | 523 | kwargs['shell'] = shell |
|
522 | 524 | |
|
523 | 525 | self.shell = shell |
|
524 | 526 | self.options_table = {} |
|
525 | 527 | # The method decorators are run when the instance doesn't exist yet, so |
|
526 | 528 | # they can only record the names of the methods they are supposed to |
|
527 | 529 | # grab. Only now, that the instance exists, can we create the proper |
|
528 | 530 | # mapping to bound methods. So we read the info off the original names |
|
529 | 531 | # table and replace each method name by the actual bound method. |
|
530 | 532 | # But we mustn't clobber the *class* mapping, in case of multiple instances. |
|
531 | 533 | class_magics = self.magics |
|
532 | 534 | self.magics = {} |
|
533 | 535 | for mtype in magic_kinds: |
|
534 | 536 | tab = self.magics[mtype] = {} |
|
535 | 537 | cls_tab = class_magics[mtype] |
|
536 | 538 | for magic_name, meth_name in iteritems(cls_tab): |
|
537 | 539 | if isinstance(meth_name, string_types): |
|
538 | 540 | # it's a method name, grab it |
|
539 | 541 | tab[magic_name] = getattr(self, meth_name) |
|
540 | 542 | else: |
|
541 | 543 | # it's the real thing |
|
542 | 544 | tab[magic_name] = meth_name |
|
543 | 545 | # Configurable **needs** to be initiated at the end or the config |
|
544 | 546 | # magics get screwed up. |
|
545 | 547 | super(Magics, self).__init__(**kwargs) |
|
546 | 548 | |
|
547 | 549 | def arg_err(self,func): |
|
548 | 550 | """Print docstring if incorrect arguments were passed""" |
|
549 | 551 | print('Error in arguments:') |
|
550 | 552 | print(oinspect.getdoc(func)) |
|
551 | 553 | |
|
552 | 554 | def format_latex(self, strng): |
|
553 | 555 | """Format a string for latex inclusion.""" |
|
554 | 556 | |
|
555 | 557 | # Characters that need to be escaped for latex: |
|
556 | 558 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
557 | 559 | # Magic command names as headers: |
|
558 | 560 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
559 | 561 | re.MULTILINE) |
|
560 | 562 | # Magic commands |
|
561 | 563 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
562 | 564 | re.MULTILINE) |
|
563 | 565 | # Paragraph continue |
|
564 | 566 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
565 | 567 | |
|
566 | 568 | # The "\n" symbol |
|
567 | 569 | newline_re = re.compile(r'\\n') |
|
568 | 570 | |
|
569 | 571 | # Now build the string for output: |
|
570 | 572 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
571 | 573 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
572 | 574 | strng) |
|
573 | 575 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
574 | 576 | strng = par_re.sub(r'\\\\',strng) |
|
575 | 577 | strng = escape_re.sub(r'\\\1',strng) |
|
576 | 578 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
577 | 579 | return strng |
|
578 | 580 | |
|
579 | 581 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): |
|
580 | 582 | """Parse options passed to an argument string. |
|
581 | 583 | |
|
582 | 584 | The interface is similar to that of :func:`getopt.getopt`, but it |
|
583 | 585 | returns a :class:`~IPython.utils.struct.Struct` with the options as keys |
|
584 | 586 | and the stripped argument string still as a string. |
|
585 | 587 | |
|
586 | 588 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
587 | 589 | This allows us to easily expand variables, glob files, quote |
|
588 | 590 | arguments, etc. |
|
589 | 591 | |
|
590 | 592 | Parameters |
|
591 | 593 | ---------- |
|
592 | 594 | |
|
593 | 595 | arg_str : str |
|
594 | 596 | The arguments to parse. |
|
595 | 597 | |
|
596 | 598 | opt_str : str |
|
597 | 599 | The options specification. |
|
598 | 600 | |
|
599 | 601 | mode : str, default 'string' |
|
600 | 602 | If given as 'list', the argument string is returned as a list (split |
|
601 | 603 | on whitespace) instead of a string. |
|
602 | 604 | |
|
603 | 605 | list_all : bool, default False |
|
604 | 606 | Put all option values in lists. Normally only options |
|
605 | 607 | appearing more than once are put in a list. |
|
606 | 608 | |
|
607 | 609 | posix : bool, default True |
|
608 | 610 | Whether to split the input line in POSIX mode or not, as per the |
|
609 | 611 | conventions outlined in the :mod:`shlex` module from the standard |
|
610 | 612 | library. |
|
611 | 613 | """ |
|
612 | 614 | |
|
613 | 615 | # inject default options at the beginning of the input line |
|
614 | 616 | caller = sys._getframe(1).f_code.co_name |
|
615 | 617 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
616 | 618 | |
|
617 | 619 | mode = kw.get('mode','string') |
|
618 | 620 | if mode not in ['string','list']: |
|
619 | 621 | raise ValueError('incorrect mode given: %s' % mode) |
|
620 | 622 | # Get options |
|
621 | 623 | list_all = kw.get('list_all',0) |
|
622 | 624 | posix = kw.get('posix', os.name == 'posix') |
|
623 | 625 | strict = kw.get('strict', True) |
|
624 | 626 | |
|
625 | 627 | # Check if we have more than one argument to warrant extra processing: |
|
626 | 628 | odict = {} # Dictionary with options |
|
627 | 629 | args = arg_str.split() |
|
628 | 630 | if len(args) >= 1: |
|
629 | 631 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
630 | 632 | # need to look for options |
|
631 | 633 | argv = arg_split(arg_str, posix, strict) |
|
632 | 634 | # Do regular option processing |
|
633 | 635 | try: |
|
634 | 636 | opts,args = getopt(argv, opt_str, long_opts) |
|
635 | 637 | except GetoptError as e: |
|
636 | 638 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
637 | 639 | " ".join(long_opts))) |
|
638 | 640 | for o,a in opts: |
|
639 | 641 | if o.startswith('--'): |
|
640 | 642 | o = o[2:] |
|
641 | 643 | else: |
|
642 | 644 | o = o[1:] |
|
643 | 645 | try: |
|
644 | 646 | odict[o].append(a) |
|
645 | 647 | except AttributeError: |
|
646 | 648 | odict[o] = [odict[o],a] |
|
647 | 649 | except KeyError: |
|
648 | 650 | if list_all: |
|
649 | 651 | odict[o] = [a] |
|
650 | 652 | else: |
|
651 | 653 | odict[o] = a |
|
652 | 654 | |
|
653 | 655 | # Prepare opts,args for return |
|
654 | 656 | opts = Struct(odict) |
|
655 | 657 | if mode == 'string': |
|
656 | 658 | args = ' '.join(args) |
|
657 | 659 | |
|
658 | 660 | return opts,args |
|
659 | 661 | |
|
660 | 662 | def default_option(self, fn, optstr): |
|
661 | 663 | """Make an entry in the options_table for fn, with value optstr""" |
|
662 | 664 | |
|
663 | 665 | if fn not in self.lsmagic(): |
|
664 | 666 | error("%s is not a magic function" % fn) |
|
665 | 667 | self.options_table[fn] = optstr |
|
666 | 668 | |
|
667 | 669 | |
|
668 | 670 | class MagicAlias(object): |
|
669 | 671 | """An alias to another magic function. |
|
670 | 672 | |
|
671 | 673 | An alias is determined by its magic name and magic kind. Lookup |
|
672 | 674 | is done at call time, so if the underlying magic changes the alias |
|
673 | 675 | will call the new function. |
|
674 | 676 | |
|
675 | 677 | Use the :meth:`MagicsManager.register_alias` method or the |
|
676 | 678 | `%alias_magic` magic function to create and register a new alias. |
|
677 | 679 | """ |
|
678 | 680 | def __init__(self, shell, magic_name, magic_kind): |
|
679 | 681 | self.shell = shell |
|
680 | 682 | self.magic_name = magic_name |
|
681 | 683 | self.magic_kind = magic_kind |
|
682 | 684 | |
|
683 | 685 | self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name) |
|
684 | 686 | self.__doc__ = "Alias for `%s`." % self.pretty_target |
|
685 | 687 | |
|
686 | 688 | self._in_call = False |
|
687 | 689 | |
|
688 | 690 | def __call__(self, *args, **kwargs): |
|
689 | 691 | """Call the magic alias.""" |
|
690 | 692 | fn = self.shell.find_magic(self.magic_name, self.magic_kind) |
|
691 | 693 | if fn is None: |
|
692 | 694 | raise UsageError("Magic `%s` not found." % self.pretty_target) |
|
693 | 695 | |
|
694 | 696 | # Protect against infinite recursion. |
|
695 | 697 | if self._in_call: |
|
696 | 698 | raise UsageError("Infinite recursion detected; " |
|
697 | 699 | "magic aliases cannot call themselves.") |
|
698 | 700 | self._in_call = True |
|
699 | 701 | try: |
|
700 | 702 | return fn(*args, **kwargs) |
|
701 | 703 | finally: |
|
702 | 704 | self._in_call = False |
@@ -1,46 +1,47 b'' | |||
|
1 | 1 | """Deprecated Magic functions. |
|
2 | 2 | """ |
|
3 | 3 | from __future__ import print_function |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (c) 2012 The IPython Development Team. |
|
6 | 6 | # |
|
7 | 7 | # Distributed under the terms of the Modified BSD License. |
|
8 | 8 | # |
|
9 | 9 | # The full license is in the file COPYING.txt, distributed with this software. |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | # Imports |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | |
|
16 | 16 | # Our own packages |
|
17 | 17 | from IPython.core.magic import Magics, magics_class, line_magic |
|
18 | import warnings | |
|
18 | 19 | |
|
19 | 20 | #----------------------------------------------------------------------------- |
|
20 | 21 | # Magic implementation classes |
|
21 | 22 | #----------------------------------------------------------------------------- |
|
22 | 23 | |
|
23 | 24 | @magics_class |
|
24 | 25 | class DeprecatedMagics(Magics): |
|
25 | 26 | """Magics slated for later removal.""" |
|
26 | 27 | |
|
27 | 28 | @line_magic |
|
28 | 29 | def install_profiles(self, parameter_s=''): |
|
29 | 30 | """%install_profiles has been deprecated.""" |
|
30 | 31 | print('\n'.join([ |
|
31 | "%install_profiles has been deprecated.", | |
|
32 | "%install_profiles has been deprecated and will be removed in IPython 5.0.", | |
|
32 | 33 | "Use `ipython profile list` to view available profiles.", |
|
33 | 34 | "Requesting a profile with `ipython profile create <name>`", |
|
34 | 35 | "or `ipython --profile=<name>` will start with the bundled", |
|
35 | 36 | "profile of that name if it exists." |
|
36 | 37 | ])) |
|
37 | 38 | |
|
38 | 39 | @line_magic |
|
39 | 40 | def install_default_config(self, parameter_s=''): |
|
40 | """%install_default_config has been deprecated.""" | |
|
41 | """%install_default_config has been deprecate and will be removed in IPython 5.0.""" | |
|
41 | 42 | print('\n'.join([ |
|
42 | 43 | "%install_default_config has been deprecated.", |
|
43 | 44 | "Use `ipython profile create <name>` to initialize a profile", |
|
44 | 45 | "with the default config files.", |
|
45 | 46 | "Add `--reset` to overwrite already existing config files with defaults." |
|
46 | 47 | ])) |
@@ -1,433 +1,435 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | A mixin for :class:`~IPython.core.application.Application` classes that |
|
4 | 4 | launch InteractiveShell instances, load extensions, etc. |
|
5 | 5 | """ |
|
6 | 6 | |
|
7 | 7 | # Copyright (c) IPython Development Team. |
|
8 | 8 | # Distributed under the terms of the Modified BSD License. |
|
9 | 9 | |
|
10 | 10 | from __future__ import absolute_import |
|
11 | 11 | from __future__ import print_function |
|
12 | 12 | |
|
13 | 13 | import glob |
|
14 | 14 | import os |
|
15 | 15 | import sys |
|
16 | 16 | |
|
17 | 17 | from traitlets.config.application import boolean_flag |
|
18 | 18 | from traitlets.config.configurable import Configurable |
|
19 | 19 | from traitlets.config.loader import Config |
|
20 | 20 | from IPython.core import pylabtools |
|
21 | 21 | from IPython.utils import py3compat |
|
22 | 22 | from IPython.utils.contexts import preserve_keys |
|
23 | 23 | from IPython.utils.path import filefind |
|
24 | 24 | from traitlets import ( |
|
25 | 25 | Unicode, Instance, List, Bool, CaselessStrEnum |
|
26 | 26 | ) |
|
27 | 27 | from IPython.lib.inputhook import guis |
|
28 | 28 | |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | # Aliases and Flags |
|
31 | 31 | #----------------------------------------------------------------------------- |
|
32 | 32 | |
|
33 | 33 | gui_keys = tuple(sorted([ key for key in guis if key is not None ])) |
|
34 | 34 | |
|
35 | 35 | backend_keys = sorted(pylabtools.backends.keys()) |
|
36 | 36 | backend_keys.insert(0, 'auto') |
|
37 | 37 | |
|
38 | 38 | shell_flags = {} |
|
39 | 39 | |
|
40 | 40 | addflag = lambda *args: shell_flags.update(boolean_flag(*args)) |
|
41 | 41 | addflag('autoindent', 'InteractiveShell.autoindent', |
|
42 | 42 | 'Turn on autoindenting.', 'Turn off autoindenting.' |
|
43 | 43 | ) |
|
44 | 44 | addflag('automagic', 'InteractiveShell.automagic', |
|
45 | 45 | """Turn on the auto calling of magic commands. Type %%magic at the |
|
46 | 46 | IPython prompt for more information.""", |
|
47 | 47 | 'Turn off the auto calling of magic commands.' |
|
48 | 48 | ) |
|
49 | 49 | addflag('pdb', 'InteractiveShell.pdb', |
|
50 | 50 | "Enable auto calling the pdb debugger after every exception.", |
|
51 | 51 | "Disable auto calling the pdb debugger after every exception." |
|
52 | 52 | ) |
|
53 | 53 | # pydb flag doesn't do any config, as core.debugger switches on import, |
|
54 | 54 | # which is before parsing. This just allows the flag to be passed. |
|
55 | 55 | shell_flags.update(dict( |
|
56 | 56 | pydb = ({}, |
|
57 | 57 | """Use the third party 'pydb' package as debugger, instead of pdb. |
|
58 | 58 | Requires that pydb is installed.""" |
|
59 | 59 | ) |
|
60 | 60 | )) |
|
61 | 61 | addflag('pprint', 'PlainTextFormatter.pprint', |
|
62 | 62 | "Enable auto pretty printing of results.", |
|
63 | 63 | "Disable auto pretty printing of results." |
|
64 | 64 | ) |
|
65 | 65 | addflag('color-info', 'InteractiveShell.color_info', |
|
66 | 66 | """IPython can display information about objects via a set of functions, |
|
67 | 67 | and optionally can use colors for this, syntax highlighting |
|
68 | 68 | source code and various other elements. This is on by default, but can cause |
|
69 | 69 | problems with some pagers. If you see such problems, you can disable the |
|
70 | 70 | colours.""", |
|
71 | 71 | "Disable using colors for info related things." |
|
72 | 72 | ) |
|
73 | 73 | addflag('deep-reload', 'InteractiveShell.deep_reload', |
|
74 | """ **Deprecated** Enable deep (recursive) reloading by default. IPython can use the | |
|
74 | """ **Deprecated** and will be removed in IPython 5.0. | |
|
75 | ||
|
76 | Enable deep (recursive) reloading by default. IPython can use the | |
|
75 | 77 | deep_reload module which reloads changes in modules recursively (it |
|
76 | 78 | replaces the reload() function, so you don't need to change anything to |
|
77 | 79 | use it). deep_reload() forces a full reload of modules whose code may |
|
78 | 80 | have changed, which the default reload() function does not. When |
|
79 | 81 | deep_reload is off, IPython will use the normal reload(), but |
|
80 | 82 | deep_reload will still be available as dreload(). This feature is off |
|
81 | 83 | by default [which means that you have both normal reload() and |
|
82 | 84 | dreload()].""", |
|
83 | 85 | "Disable deep (recursive) reloading by default." |
|
84 | 86 | ) |
|
85 | 87 | nosep_config = Config() |
|
86 | 88 | nosep_config.InteractiveShell.separate_in = '' |
|
87 | 89 | nosep_config.InteractiveShell.separate_out = '' |
|
88 | 90 | nosep_config.InteractiveShell.separate_out2 = '' |
|
89 | 91 | |
|
90 | 92 | shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.") |
|
91 | 93 | shell_flags['pylab'] = ( |
|
92 | 94 | {'InteractiveShellApp' : {'pylab' : 'auto'}}, |
|
93 | 95 | """Pre-load matplotlib and numpy for interactive use with |
|
94 | 96 | the default matplotlib backend.""" |
|
95 | 97 | ) |
|
96 | 98 | shell_flags['matplotlib'] = ( |
|
97 | 99 | {'InteractiveShellApp' : {'matplotlib' : 'auto'}}, |
|
98 | 100 | """Configure matplotlib for interactive use with |
|
99 | 101 | the default matplotlib backend.""" |
|
100 | 102 | ) |
|
101 | 103 | |
|
102 | 104 | # it's possible we don't want short aliases for *all* of these: |
|
103 | 105 | shell_aliases = dict( |
|
104 | 106 | autocall='InteractiveShell.autocall', |
|
105 | 107 | colors='InteractiveShell.colors', |
|
106 | 108 | logfile='InteractiveShell.logfile', |
|
107 | 109 | logappend='InteractiveShell.logappend', |
|
108 | 110 | c='InteractiveShellApp.code_to_run', |
|
109 | 111 | m='InteractiveShellApp.module_to_run', |
|
110 | 112 | ext='InteractiveShellApp.extra_extension', |
|
111 | 113 | gui='InteractiveShellApp.gui', |
|
112 | 114 | pylab='InteractiveShellApp.pylab', |
|
113 | 115 | matplotlib='InteractiveShellApp.matplotlib', |
|
114 | 116 | ) |
|
115 | 117 | shell_aliases['cache-size'] = 'InteractiveShell.cache_size' |
|
116 | 118 | |
|
117 | 119 | #----------------------------------------------------------------------------- |
|
118 | 120 | # Main classes and functions |
|
119 | 121 | #----------------------------------------------------------------------------- |
|
120 | 122 | |
|
121 | 123 | class InteractiveShellApp(Configurable): |
|
122 | 124 | """A Mixin for applications that start InteractiveShell instances. |
|
123 | 125 | |
|
124 | 126 | Provides configurables for loading extensions and executing files |
|
125 | 127 | as part of configuring a Shell environment. |
|
126 | 128 | |
|
127 | 129 | The following methods should be called by the :meth:`initialize` method |
|
128 | 130 | of the subclass: |
|
129 | 131 | |
|
130 | 132 | - :meth:`init_path` |
|
131 | 133 | - :meth:`init_shell` (to be implemented by the subclass) |
|
132 | 134 | - :meth:`init_gui_pylab` |
|
133 | 135 | - :meth:`init_extensions` |
|
134 | 136 | - :meth:`init_code` |
|
135 | 137 | """ |
|
136 | 138 | extensions = List(Unicode(), config=True, |
|
137 | 139 | help="A list of dotted module names of IPython extensions to load." |
|
138 | 140 | ) |
|
139 | 141 | extra_extension = Unicode('', config=True, |
|
140 | 142 | help="dotted module name of an IPython extension to load." |
|
141 | 143 | ) |
|
142 | 144 | |
|
143 | 145 | reraise_ipython_extension_failures = Bool( |
|
144 | 146 | False, |
|
145 | 147 | config=True, |
|
146 | 148 | help="Reraise exceptions encountered loading IPython extensions?", |
|
147 | 149 | ) |
|
148 | 150 | |
|
149 | 151 | # Extensions that are always loaded (not configurable) |
|
150 | 152 | default_extensions = List(Unicode(), [u'storemagic'], config=False) |
|
151 | 153 | |
|
152 | 154 | hide_initial_ns = Bool(True, config=True, |
|
153 | 155 | help="""Should variables loaded at startup (by startup files, exec_lines, etc.) |
|
154 | 156 | be hidden from tools like %who?""" |
|
155 | 157 | ) |
|
156 | 158 | |
|
157 | 159 | exec_files = List(Unicode(), config=True, |
|
158 | 160 | help="""List of files to run at IPython startup.""" |
|
159 | 161 | ) |
|
160 | 162 | exec_PYTHONSTARTUP = Bool(True, config=True, |
|
161 | 163 | help="""Run the file referenced by the PYTHONSTARTUP environment |
|
162 | 164 | variable at IPython startup.""" |
|
163 | 165 | ) |
|
164 | 166 | file_to_run = Unicode('', config=True, |
|
165 | 167 | help="""A file to be run""") |
|
166 | 168 | |
|
167 | 169 | exec_lines = List(Unicode(), config=True, |
|
168 | 170 | help="""lines of code to run at IPython startup.""" |
|
169 | 171 | ) |
|
170 | 172 | code_to_run = Unicode('', config=True, |
|
171 | 173 | help="Execute the given command string." |
|
172 | 174 | ) |
|
173 | 175 | module_to_run = Unicode('', config=True, |
|
174 | 176 | help="Run the module as a script." |
|
175 | 177 | ) |
|
176 | 178 | gui = CaselessStrEnum(gui_keys, config=True, allow_none=True, |
|
177 | 179 | help="Enable GUI event loop integration with any of {0}.".format(gui_keys) |
|
178 | 180 | ) |
|
179 | 181 | matplotlib = CaselessStrEnum(backend_keys, allow_none=True, |
|
180 | 182 | config=True, |
|
181 | 183 | help="""Configure matplotlib for interactive use with |
|
182 | 184 | the default matplotlib backend.""" |
|
183 | 185 | ) |
|
184 | 186 | pylab = CaselessStrEnum(backend_keys, allow_none=True, |
|
185 | 187 | config=True, |
|
186 | 188 | help="""Pre-load matplotlib and numpy for interactive use, |
|
187 | 189 | selecting a particular matplotlib backend and loop integration. |
|
188 | 190 | """ |
|
189 | 191 | ) |
|
190 | 192 | pylab_import_all = Bool(True, config=True, |
|
191 | 193 | help="""If true, IPython will populate the user namespace with numpy, pylab, etc. |
|
192 | 194 | and an ``import *`` is done from numpy and pylab, when using pylab mode. |
|
193 | 195 | |
|
194 | 196 | When False, pylab mode should not import any names into the user namespace. |
|
195 | 197 | """ |
|
196 | 198 | ) |
|
197 | 199 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', |
|
198 | 200 | allow_none=True) |
|
199 | 201 | |
|
200 | 202 | user_ns = Instance(dict, args=None, allow_none=True) |
|
201 | 203 | def _user_ns_changed(self, name, old, new): |
|
202 | 204 | if self.shell is not None: |
|
203 | 205 | self.shell.user_ns = new |
|
204 | 206 | self.shell.init_user_ns() |
|
205 | 207 | |
|
206 | 208 | def init_path(self): |
|
207 | 209 | """Add current working directory, '', to sys.path""" |
|
208 | 210 | if sys.path[0] != '': |
|
209 | 211 | sys.path.insert(0, '') |
|
210 | 212 | |
|
211 | 213 | def init_shell(self): |
|
212 | 214 | raise NotImplementedError("Override in subclasses") |
|
213 | 215 | |
|
214 | 216 | def init_gui_pylab(self): |
|
215 | 217 | """Enable GUI event loop integration, taking pylab into account.""" |
|
216 | 218 | enable = False |
|
217 | 219 | shell = self.shell |
|
218 | 220 | if self.pylab: |
|
219 | 221 | enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all) |
|
220 | 222 | key = self.pylab |
|
221 | 223 | elif self.matplotlib: |
|
222 | 224 | enable = shell.enable_matplotlib |
|
223 | 225 | key = self.matplotlib |
|
224 | 226 | elif self.gui: |
|
225 | 227 | enable = shell.enable_gui |
|
226 | 228 | key = self.gui |
|
227 | 229 | |
|
228 | 230 | if not enable: |
|
229 | 231 | return |
|
230 | 232 | |
|
231 | 233 | try: |
|
232 | 234 | r = enable(key) |
|
233 | 235 | except ImportError: |
|
234 | 236 | self.log.warn("Eventloop or matplotlib integration failed. Is matplotlib installed?") |
|
235 | 237 | self.shell.showtraceback() |
|
236 | 238 | return |
|
237 | 239 | except Exception: |
|
238 | 240 | self.log.warn("GUI event loop or pylab initialization failed") |
|
239 | 241 | self.shell.showtraceback() |
|
240 | 242 | return |
|
241 | 243 | |
|
242 | 244 | if isinstance(r, tuple): |
|
243 | 245 | gui, backend = r[:2] |
|
244 | 246 | self.log.info("Enabling GUI event loop integration, " |
|
245 | 247 | "eventloop=%s, matplotlib=%s", gui, backend) |
|
246 | 248 | if key == "auto": |
|
247 | 249 | print("Using matplotlib backend: %s" % backend) |
|
248 | 250 | else: |
|
249 | 251 | gui = r |
|
250 | 252 | self.log.info("Enabling GUI event loop integration, " |
|
251 | 253 | "eventloop=%s", gui) |
|
252 | 254 | |
|
253 | 255 | def init_extensions(self): |
|
254 | 256 | """Load all IPython extensions in IPythonApp.extensions. |
|
255 | 257 | |
|
256 | 258 | This uses the :meth:`ExtensionManager.load_extensions` to load all |
|
257 | 259 | the extensions listed in ``self.extensions``. |
|
258 | 260 | """ |
|
259 | 261 | try: |
|
260 | 262 | self.log.debug("Loading IPython extensions...") |
|
261 | 263 | extensions = self.default_extensions + self.extensions |
|
262 | 264 | if self.extra_extension: |
|
263 | 265 | extensions.append(self.extra_extension) |
|
264 | 266 | for ext in extensions: |
|
265 | 267 | try: |
|
266 | 268 | self.log.info("Loading IPython extension: %s" % ext) |
|
267 | 269 | self.shell.extension_manager.load_extension(ext) |
|
268 | 270 | except: |
|
269 | 271 | if self.reraise_ipython_extension_failures: |
|
270 | 272 | raise |
|
271 | 273 | msg = ("Error in loading extension: {ext}\n" |
|
272 | 274 | "Check your config files in {location}".format( |
|
273 | 275 | ext=ext, |
|
274 | 276 | location=self.profile_dir.location |
|
275 | 277 | )) |
|
276 | 278 | self.log.warn(msg, exc_info=True) |
|
277 | 279 | except: |
|
278 | 280 | if self.reraise_ipython_extension_failures: |
|
279 | 281 | raise |
|
280 | 282 | self.log.warn("Unknown error in loading extensions:", exc_info=True) |
|
281 | 283 | |
|
282 | 284 | def init_code(self): |
|
283 | 285 | """run the pre-flight code, specified via exec_lines""" |
|
284 | 286 | self._run_startup_files() |
|
285 | 287 | self._run_exec_lines() |
|
286 | 288 | self._run_exec_files() |
|
287 | 289 | |
|
288 | 290 | # Hide variables defined here from %who etc. |
|
289 | 291 | if self.hide_initial_ns: |
|
290 | 292 | self.shell.user_ns_hidden.update(self.shell.user_ns) |
|
291 | 293 | |
|
292 | 294 | # command-line execution (ipython -i script.py, ipython -m module) |
|
293 | 295 | # should *not* be excluded from %whos |
|
294 | 296 | self._run_cmd_line_code() |
|
295 | 297 | self._run_module() |
|
296 | 298 | |
|
297 | 299 | # flush output, so itwon't be attached to the first cell |
|
298 | 300 | sys.stdout.flush() |
|
299 | 301 | sys.stderr.flush() |
|
300 | 302 | |
|
301 | 303 | def _run_exec_lines(self): |
|
302 | 304 | """Run lines of code in IPythonApp.exec_lines in the user's namespace.""" |
|
303 | 305 | if not self.exec_lines: |
|
304 | 306 | return |
|
305 | 307 | try: |
|
306 | 308 | self.log.debug("Running code from IPythonApp.exec_lines...") |
|
307 | 309 | for line in self.exec_lines: |
|
308 | 310 | try: |
|
309 | 311 | self.log.info("Running code in user namespace: %s" % |
|
310 | 312 | line) |
|
311 | 313 | self.shell.run_cell(line, store_history=False) |
|
312 | 314 | except: |
|
313 | 315 | self.log.warn("Error in executing line in user " |
|
314 | 316 | "namespace: %s" % line) |
|
315 | 317 | self.shell.showtraceback() |
|
316 | 318 | except: |
|
317 | 319 | self.log.warn("Unknown error in handling IPythonApp.exec_lines:") |
|
318 | 320 | self.shell.showtraceback() |
|
319 | 321 | |
|
320 | 322 | def _exec_file(self, fname, shell_futures=False): |
|
321 | 323 | try: |
|
322 | 324 | full_filename = filefind(fname, [u'.', self.ipython_dir]) |
|
323 | 325 | except IOError as e: |
|
324 | 326 | self.log.warn("File not found: %r"%fname) |
|
325 | 327 | return |
|
326 | 328 | # Make sure that the running script gets a proper sys.argv as if it |
|
327 | 329 | # were run from a system shell. |
|
328 | 330 | save_argv = sys.argv |
|
329 | 331 | sys.argv = [full_filename] + self.extra_args[1:] |
|
330 | 332 | # protect sys.argv from potential unicode strings on Python 2: |
|
331 | 333 | if not py3compat.PY3: |
|
332 | 334 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
333 | 335 | try: |
|
334 | 336 | if os.path.isfile(full_filename): |
|
335 | 337 | self.log.info("Running file in user namespace: %s" % |
|
336 | 338 | full_filename) |
|
337 | 339 | # Ensure that __file__ is always defined to match Python |
|
338 | 340 | # behavior. |
|
339 | 341 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
340 | 342 | self.shell.user_ns['__file__'] = fname |
|
341 | 343 | if full_filename.endswith('.ipy'): |
|
342 | 344 | self.shell.safe_execfile_ipy(full_filename, |
|
343 | 345 | shell_futures=shell_futures) |
|
344 | 346 | else: |
|
345 | 347 | # default to python, even without extension |
|
346 | 348 | self.shell.safe_execfile(full_filename, |
|
347 | 349 | self.shell.user_ns, |
|
348 | 350 | shell_futures=shell_futures, |
|
349 | 351 | raise_exceptions=True) |
|
350 | 352 | finally: |
|
351 | 353 | sys.argv = save_argv |
|
352 | 354 | |
|
353 | 355 | def _run_startup_files(self): |
|
354 | 356 | """Run files from profile startup directory""" |
|
355 | 357 | startup_dir = self.profile_dir.startup_dir |
|
356 | 358 | startup_files = [] |
|
357 | 359 | |
|
358 | 360 | if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \ |
|
359 | 361 | not (self.file_to_run or self.code_to_run or self.module_to_run): |
|
360 | 362 | python_startup = os.environ['PYTHONSTARTUP'] |
|
361 | 363 | self.log.debug("Running PYTHONSTARTUP file %s...", python_startup) |
|
362 | 364 | try: |
|
363 | 365 | self._exec_file(python_startup) |
|
364 | 366 | except: |
|
365 | 367 | self.log.warn("Unknown error in handling PYTHONSTARTUP file %s:", python_startup) |
|
366 | 368 | self.shell.showtraceback() |
|
367 | 369 | finally: |
|
368 | 370 | # Many PYTHONSTARTUP files set up the readline completions, |
|
369 | 371 | # but this is often at odds with IPython's own completions. |
|
370 | 372 | # Do not allow PYTHONSTARTUP to set up readline. |
|
371 | 373 | if self.shell.has_readline: |
|
372 | 374 | self.shell.set_readline_completer() |
|
373 | 375 | |
|
374 | 376 | startup_files += glob.glob(os.path.join(startup_dir, '*.py')) |
|
375 | 377 | startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) |
|
376 | 378 | if not startup_files: |
|
377 | 379 | return |
|
378 | 380 | |
|
379 | 381 | self.log.debug("Running startup files from %s...", startup_dir) |
|
380 | 382 | try: |
|
381 | 383 | for fname in sorted(startup_files): |
|
382 | 384 | self._exec_file(fname) |
|
383 | 385 | except: |
|
384 | 386 | self.log.warn("Unknown error in handling startup files:") |
|
385 | 387 | self.shell.showtraceback() |
|
386 | 388 | |
|
387 | 389 | def _run_exec_files(self): |
|
388 | 390 | """Run files from IPythonApp.exec_files""" |
|
389 | 391 | if not self.exec_files: |
|
390 | 392 | return |
|
391 | 393 | |
|
392 | 394 | self.log.debug("Running files in IPythonApp.exec_files...") |
|
393 | 395 | try: |
|
394 | 396 | for fname in self.exec_files: |
|
395 | 397 | self._exec_file(fname) |
|
396 | 398 | except: |
|
397 | 399 | self.log.warn("Unknown error in handling IPythonApp.exec_files:") |
|
398 | 400 | self.shell.showtraceback() |
|
399 | 401 | |
|
400 | 402 | def _run_cmd_line_code(self): |
|
401 | 403 | """Run code or file specified at the command-line""" |
|
402 | 404 | if self.code_to_run: |
|
403 | 405 | line = self.code_to_run |
|
404 | 406 | try: |
|
405 | 407 | self.log.info("Running code given at command line (c=): %s" % |
|
406 | 408 | line) |
|
407 | 409 | self.shell.run_cell(line, store_history=False) |
|
408 | 410 | except: |
|
409 | 411 | self.log.warn("Error in executing line in user namespace: %s" % |
|
410 | 412 | line) |
|
411 | 413 | self.shell.showtraceback() |
|
412 | 414 | |
|
413 | 415 | # Like Python itself, ignore the second if the first of these is present |
|
414 | 416 | elif self.file_to_run: |
|
415 | 417 | fname = self.file_to_run |
|
416 | 418 | try: |
|
417 | 419 | self._exec_file(fname, shell_futures=True) |
|
418 | 420 | except: |
|
419 | 421 | self.shell.showtraceback(tb_offset=4) |
|
420 | 422 | self.exit(1) |
|
421 | 423 | |
|
422 | 424 | def _run_module(self): |
|
423 | 425 | """Run module specified at the command-line.""" |
|
424 | 426 | if self.module_to_run: |
|
425 | 427 | # Make sure that the module gets a proper sys.argv as if it were |
|
426 | 428 | # run using `python -m`. |
|
427 | 429 | save_argv = sys.argv |
|
428 | 430 | sys.argv = [sys.executable] + self.extra_args |
|
429 | 431 | try: |
|
430 | 432 | self.shell.safe_run_module(self.module_to_run, |
|
431 | 433 | self.shell.user_ns) |
|
432 | 434 | finally: |
|
433 | 435 | sys.argv = save_argv |
@@ -1,944 +1,943 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Tests for the key interactiveshell module. |
|
3 | 3 | |
|
4 | 4 | Historically the main classes in interactiveshell have been under-tested. This |
|
5 | 5 | module should grow as many single-method tests as possible to trap many of the |
|
6 | 6 | recurring bugs we seem to encounter with high-level interaction. |
|
7 | 7 | """ |
|
8 | 8 | |
|
9 | 9 | # Copyright (c) IPython Development Team. |
|
10 | 10 | # Distributed under the terms of the Modified BSD License. |
|
11 | 11 | |
|
12 | 12 | import ast |
|
13 | 13 | import os |
|
14 | 14 | import signal |
|
15 | 15 | import shutil |
|
16 | 16 | import sys |
|
17 | 17 | import tempfile |
|
18 | 18 | import unittest |
|
19 | 19 | try: |
|
20 | 20 | from unittest import mock |
|
21 | 21 | except ImportError: |
|
22 | 22 | import mock |
|
23 | 23 | from os.path import join |
|
24 | 24 | |
|
25 | 25 | import nose.tools as nt |
|
26 | 26 | |
|
27 | 27 | from IPython.core.error import InputRejected |
|
28 | 28 | from IPython.core.inputtransformer import InputTransformer |
|
29 | 29 | from IPython.testing.decorators import ( |
|
30 | 30 | skipif, skip_win32, onlyif_unicode_paths, onlyif_cmds_exist, |
|
31 | 31 | ) |
|
32 | 32 | from IPython.testing import tools as tt |
|
33 | from IPython.utils import io | |
|
34 | 33 | from IPython.utils.process import find_cmd |
|
35 | 34 | from IPython.utils import py3compat |
|
36 | 35 | from IPython.utils.py3compat import unicode_type, PY3 |
|
37 | 36 | |
|
38 | 37 | if PY3: |
|
39 | 38 | from io import StringIO |
|
40 | 39 | else: |
|
41 | 40 | from StringIO import StringIO |
|
42 | 41 | |
|
43 | 42 | #----------------------------------------------------------------------------- |
|
44 | 43 | # Globals |
|
45 | 44 | #----------------------------------------------------------------------------- |
|
46 | 45 | # This is used by every single test, no point repeating it ad nauseam |
|
47 | 46 | ip = get_ipython() |
|
48 | 47 | |
|
49 | 48 | #----------------------------------------------------------------------------- |
|
50 | 49 | # Tests |
|
51 | 50 | #----------------------------------------------------------------------------- |
|
52 | 51 | |
|
53 | 52 | class DerivedInterrupt(KeyboardInterrupt): |
|
54 | 53 | pass |
|
55 | 54 | |
|
56 | 55 | class InteractiveShellTestCase(unittest.TestCase): |
|
57 | 56 | def test_naked_string_cells(self): |
|
58 | 57 | """Test that cells with only naked strings are fully executed""" |
|
59 | 58 | # First, single-line inputs |
|
60 | 59 | ip.run_cell('"a"\n') |
|
61 | 60 | self.assertEqual(ip.user_ns['_'], 'a') |
|
62 | 61 | # And also multi-line cells |
|
63 | 62 | ip.run_cell('"""a\nb"""\n') |
|
64 | 63 | self.assertEqual(ip.user_ns['_'], 'a\nb') |
|
65 | 64 | |
|
66 | 65 | def test_run_empty_cell(self): |
|
67 | 66 | """Just make sure we don't get a horrible error with a blank |
|
68 | 67 | cell of input. Yes, I did overlook that.""" |
|
69 | 68 | old_xc = ip.execution_count |
|
70 | 69 | res = ip.run_cell('') |
|
71 | 70 | self.assertEqual(ip.execution_count, old_xc) |
|
72 | 71 | self.assertEqual(res.execution_count, None) |
|
73 | 72 | |
|
74 | 73 | def test_run_cell_multiline(self): |
|
75 | 74 | """Multi-block, multi-line cells must execute correctly. |
|
76 | 75 | """ |
|
77 | 76 | src = '\n'.join(["x=1", |
|
78 | 77 | "y=2", |
|
79 | 78 | "if 1:", |
|
80 | 79 | " x += 1", |
|
81 | 80 | " y += 1",]) |
|
82 | 81 | res = ip.run_cell(src) |
|
83 | 82 | self.assertEqual(ip.user_ns['x'], 2) |
|
84 | 83 | self.assertEqual(ip.user_ns['y'], 3) |
|
85 | 84 | self.assertEqual(res.success, True) |
|
86 | 85 | self.assertEqual(res.result, None) |
|
87 | 86 | |
|
88 | 87 | def test_multiline_string_cells(self): |
|
89 | 88 | "Code sprinkled with multiline strings should execute (GH-306)" |
|
90 | 89 | ip.run_cell('tmp=0') |
|
91 | 90 | self.assertEqual(ip.user_ns['tmp'], 0) |
|
92 | 91 | res = ip.run_cell('tmp=1;"""a\nb"""\n') |
|
93 | 92 | self.assertEqual(ip.user_ns['tmp'], 1) |
|
94 | 93 | self.assertEqual(res.success, True) |
|
95 | 94 | self.assertEqual(res.result, "a\nb") |
|
96 | 95 | |
|
97 | 96 | def test_dont_cache_with_semicolon(self): |
|
98 | 97 | "Ending a line with semicolon should not cache the returned object (GH-307)" |
|
99 | 98 | oldlen = len(ip.user_ns['Out']) |
|
100 | 99 | for cell in ['1;', '1;1;']: |
|
101 | 100 | res = ip.run_cell(cell, store_history=True) |
|
102 | 101 | newlen = len(ip.user_ns['Out']) |
|
103 | 102 | self.assertEqual(oldlen, newlen) |
|
104 | 103 | self.assertIsNone(res.result) |
|
105 | 104 | i = 0 |
|
106 | 105 | #also test the default caching behavior |
|
107 | 106 | for cell in ['1', '1;1']: |
|
108 | 107 | ip.run_cell(cell, store_history=True) |
|
109 | 108 | newlen = len(ip.user_ns['Out']) |
|
110 | 109 | i += 1 |
|
111 | 110 | self.assertEqual(oldlen+i, newlen) |
|
112 | 111 | |
|
113 | 112 | def test_syntax_error(self): |
|
114 | 113 | res = ip.run_cell("raise = 3") |
|
115 | 114 | self.assertIsInstance(res.error_before_exec, SyntaxError) |
|
116 | 115 | |
|
117 | 116 | def test_In_variable(self): |
|
118 | 117 | "Verify that In variable grows with user input (GH-284)" |
|
119 | 118 | oldlen = len(ip.user_ns['In']) |
|
120 | 119 | ip.run_cell('1;', store_history=True) |
|
121 | 120 | newlen = len(ip.user_ns['In']) |
|
122 | 121 | self.assertEqual(oldlen+1, newlen) |
|
123 | 122 | self.assertEqual(ip.user_ns['In'][-1],'1;') |
|
124 | 123 | |
|
125 | 124 | def test_magic_names_in_string(self): |
|
126 | 125 | ip.run_cell('a = """\n%exit\n"""') |
|
127 | 126 | self.assertEqual(ip.user_ns['a'], '\n%exit\n') |
|
128 | 127 | |
|
129 | 128 | def test_trailing_newline(self): |
|
130 | 129 | """test that running !(command) does not raise a SyntaxError""" |
|
131 | 130 | ip.run_cell('!(true)\n', False) |
|
132 | 131 | ip.run_cell('!(true)\n\n\n', False) |
|
133 | 132 | |
|
134 | 133 | def test_gh_597(self): |
|
135 | 134 | """Pretty-printing lists of objects with non-ascii reprs may cause |
|
136 | 135 | problems.""" |
|
137 | 136 | class Spam(object): |
|
138 | 137 | def __repr__(self): |
|
139 | 138 | return "\xe9"*50 |
|
140 | 139 | import IPython.core.formatters |
|
141 | 140 | f = IPython.core.formatters.PlainTextFormatter() |
|
142 | 141 | f([Spam(),Spam()]) |
|
143 | 142 | |
|
144 | 143 | |
|
145 | 144 | def test_future_flags(self): |
|
146 | 145 | """Check that future flags are used for parsing code (gh-777)""" |
|
147 | 146 | ip.run_cell('from __future__ import print_function') |
|
148 | 147 | try: |
|
149 | 148 | ip.run_cell('prfunc_return_val = print(1,2, sep=" ")') |
|
150 | 149 | assert 'prfunc_return_val' in ip.user_ns |
|
151 | 150 | finally: |
|
152 | 151 | # Reset compiler flags so we don't mess up other tests. |
|
153 | 152 | ip.compile.reset_compiler_flags() |
|
154 | 153 | |
|
155 | 154 | def test_future_unicode(self): |
|
156 | 155 | """Check that unicode_literals is imported from __future__ (gh #786)""" |
|
157 | 156 | try: |
|
158 | 157 | ip.run_cell(u'byte_str = "a"') |
|
159 | 158 | assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default |
|
160 | 159 | ip.run_cell('from __future__ import unicode_literals') |
|
161 | 160 | ip.run_cell(u'unicode_str = "a"') |
|
162 | 161 | assert isinstance(ip.user_ns['unicode_str'], unicode_type) # strings literals are now unicode |
|
163 | 162 | finally: |
|
164 | 163 | # Reset compiler flags so we don't mess up other tests. |
|
165 | 164 | ip.compile.reset_compiler_flags() |
|
166 | 165 | |
|
167 | 166 | def test_can_pickle(self): |
|
168 | 167 | "Can we pickle objects defined interactively (GH-29)" |
|
169 | 168 | ip = get_ipython() |
|
170 | 169 | ip.reset() |
|
171 | 170 | ip.run_cell(("class Mylist(list):\n" |
|
172 | 171 | " def __init__(self,x=[]):\n" |
|
173 | 172 | " list.__init__(self,x)")) |
|
174 | 173 | ip.run_cell("w=Mylist([1,2,3])") |
|
175 | 174 | |
|
176 | 175 | from pickle import dumps |
|
177 | 176 | |
|
178 | 177 | # We need to swap in our main module - this is only necessary |
|
179 | 178 | # inside the test framework, because IPython puts the interactive module |
|
180 | 179 | # in place (but the test framework undoes this). |
|
181 | 180 | _main = sys.modules['__main__'] |
|
182 | 181 | sys.modules['__main__'] = ip.user_module |
|
183 | 182 | try: |
|
184 | 183 | res = dumps(ip.user_ns["w"]) |
|
185 | 184 | finally: |
|
186 | 185 | sys.modules['__main__'] = _main |
|
187 | 186 | self.assertTrue(isinstance(res, bytes)) |
|
188 | 187 | |
|
189 | 188 | def test_global_ns(self): |
|
190 | 189 | "Code in functions must be able to access variables outside them." |
|
191 | 190 | ip = get_ipython() |
|
192 | 191 | ip.run_cell("a = 10") |
|
193 | 192 | ip.run_cell(("def f(x):\n" |
|
194 | 193 | " return x + a")) |
|
195 | 194 | ip.run_cell("b = f(12)") |
|
196 | 195 | self.assertEqual(ip.user_ns["b"], 22) |
|
197 | 196 | |
|
198 | 197 | def test_bad_custom_tb(self): |
|
199 | 198 | """Check that InteractiveShell is protected from bad custom exception handlers""" |
|
200 | 199 | from IPython.utils import io |
|
201 | 200 | save_stderr = io.stderr |
|
202 | 201 | try: |
|
203 | 202 | # capture stderr |
|
204 | 203 | io.stderr = StringIO() |
|
205 | 204 | ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0) |
|
206 | 205 | self.assertEqual(ip.custom_exceptions, (IOError,)) |
|
207 | 206 | ip.run_cell(u'raise IOError("foo")') |
|
208 | 207 | self.assertEqual(ip.custom_exceptions, ()) |
|
209 | 208 | self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue()) |
|
210 | 209 | finally: |
|
211 | 210 | io.stderr = save_stderr |
|
212 | 211 | |
|
213 | 212 | def test_bad_custom_tb_return(self): |
|
214 | 213 | """Check that InteractiveShell is protected from bad return types in custom exception handlers""" |
|
215 | 214 | from IPython.utils import io |
|
216 | 215 | save_stderr = io.stderr |
|
217 | 216 | try: |
|
218 | 217 | # capture stderr |
|
219 | 218 | io.stderr = StringIO() |
|
220 | 219 | ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1) |
|
221 | 220 | self.assertEqual(ip.custom_exceptions, (NameError,)) |
|
222 | 221 | ip.run_cell(u'a=abracadabra') |
|
223 | 222 | self.assertEqual(ip.custom_exceptions, ()) |
|
224 | 223 | self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue()) |
|
225 | 224 | finally: |
|
226 | 225 | io.stderr = save_stderr |
|
227 | 226 | |
|
228 | 227 | def test_drop_by_id(self): |
|
229 | 228 | myvars = {"a":object(), "b":object(), "c": object()} |
|
230 | 229 | ip.push(myvars, interactive=False) |
|
231 | 230 | for name in myvars: |
|
232 | 231 | assert name in ip.user_ns, name |
|
233 | 232 | assert name in ip.user_ns_hidden, name |
|
234 | 233 | ip.user_ns['b'] = 12 |
|
235 | 234 | ip.drop_by_id(myvars) |
|
236 | 235 | for name in ["a", "c"]: |
|
237 | 236 | assert name not in ip.user_ns, name |
|
238 | 237 | assert name not in ip.user_ns_hidden, name |
|
239 | 238 | assert ip.user_ns['b'] == 12 |
|
240 | 239 | ip.reset() |
|
241 | 240 | |
|
242 | 241 | def test_var_expand(self): |
|
243 | 242 | ip.user_ns['f'] = u'Ca\xf1o' |
|
244 | 243 | self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o') |
|
245 | 244 | self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o') |
|
246 | 245 | self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1') |
|
247 | 246 | self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2') |
|
248 | 247 | |
|
249 | 248 | ip.user_ns['f'] = b'Ca\xc3\xb1o' |
|
250 | 249 | # This should not raise any exception: |
|
251 | 250 | ip.var_expand(u'echo $f') |
|
252 | 251 | |
|
253 | 252 | def test_var_expand_local(self): |
|
254 | 253 | """Test local variable expansion in !system and %magic calls""" |
|
255 | 254 | # !system |
|
256 | 255 | ip.run_cell('def test():\n' |
|
257 | 256 | ' lvar = "ttt"\n' |
|
258 | 257 | ' ret = !echo {lvar}\n' |
|
259 | 258 | ' return ret[0]\n') |
|
260 | 259 | res = ip.user_ns['test']() |
|
261 | 260 | nt.assert_in('ttt', res) |
|
262 | 261 | |
|
263 | 262 | # %magic |
|
264 | 263 | ip.run_cell('def makemacro():\n' |
|
265 | 264 | ' macroname = "macro_var_expand_locals"\n' |
|
266 | 265 | ' %macro {macroname} codestr\n') |
|
267 | 266 | ip.user_ns['codestr'] = "str(12)" |
|
268 | 267 | ip.run_cell('makemacro()') |
|
269 | 268 | nt.assert_in('macro_var_expand_locals', ip.user_ns) |
|
270 | 269 | |
|
271 | 270 | def test_var_expand_self(self): |
|
272 | 271 | """Test variable expansion with the name 'self', which was failing. |
|
273 | 272 | |
|
274 | 273 | See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218 |
|
275 | 274 | """ |
|
276 | 275 | ip.run_cell('class cTest:\n' |
|
277 | 276 | ' classvar="see me"\n' |
|
278 | 277 | ' def test(self):\n' |
|
279 | 278 | ' res = !echo Variable: {self.classvar}\n' |
|
280 | 279 | ' return res[0]\n') |
|
281 | 280 | nt.assert_in('see me', ip.user_ns['cTest']().test()) |
|
282 | 281 | |
|
283 | 282 | def test_bad_var_expand(self): |
|
284 | 283 | """var_expand on invalid formats shouldn't raise""" |
|
285 | 284 | # SyntaxError |
|
286 | 285 | self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}") |
|
287 | 286 | # NameError |
|
288 | 287 | self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}") |
|
289 | 288 | # ZeroDivisionError |
|
290 | 289 | self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}") |
|
291 | 290 | |
|
292 | 291 | def test_silent_postexec(self): |
|
293 | 292 | """run_cell(silent=True) doesn't invoke pre/post_run_cell callbacks""" |
|
294 | 293 | pre_explicit = mock.Mock() |
|
295 | 294 | pre_always = mock.Mock() |
|
296 | 295 | post_explicit = mock.Mock() |
|
297 | 296 | post_always = mock.Mock() |
|
298 | 297 | |
|
299 | 298 | ip.events.register('pre_run_cell', pre_explicit) |
|
300 | 299 | ip.events.register('pre_execute', pre_always) |
|
301 | 300 | ip.events.register('post_run_cell', post_explicit) |
|
302 | 301 | ip.events.register('post_execute', post_always) |
|
303 | 302 | |
|
304 | 303 | try: |
|
305 | 304 | ip.run_cell("1", silent=True) |
|
306 | 305 | assert pre_always.called |
|
307 | 306 | assert not pre_explicit.called |
|
308 | 307 | assert post_always.called |
|
309 | 308 | assert not post_explicit.called |
|
310 | 309 | # double-check that non-silent exec did what we expected |
|
311 | 310 | # silent to avoid |
|
312 | 311 | ip.run_cell("1") |
|
313 | 312 | assert pre_explicit.called |
|
314 | 313 | assert post_explicit.called |
|
315 | 314 | finally: |
|
316 | 315 | # remove post-exec |
|
317 | 316 | ip.events.unregister('pre_run_cell', pre_explicit) |
|
318 | 317 | ip.events.unregister('pre_execute', pre_always) |
|
319 | 318 | ip.events.unregister('post_run_cell', post_explicit) |
|
320 | 319 | ip.events.unregister('post_execute', post_always) |
|
321 | 320 | |
|
322 | 321 | def test_silent_noadvance(self): |
|
323 | 322 | """run_cell(silent=True) doesn't advance execution_count""" |
|
324 | 323 | ec = ip.execution_count |
|
325 | 324 | # silent should force store_history=False |
|
326 | 325 | ip.run_cell("1", store_history=True, silent=True) |
|
327 | 326 | |
|
328 | 327 | self.assertEqual(ec, ip.execution_count) |
|
329 | 328 | # double-check that non-silent exec did what we expected |
|
330 | 329 | # silent to avoid |
|
331 | 330 | ip.run_cell("1", store_history=True) |
|
332 | 331 | self.assertEqual(ec+1, ip.execution_count) |
|
333 | 332 | |
|
334 | 333 | def test_silent_nodisplayhook(self): |
|
335 | 334 | """run_cell(silent=True) doesn't trigger displayhook""" |
|
336 | 335 | d = dict(called=False) |
|
337 | 336 | |
|
338 | 337 | trap = ip.display_trap |
|
339 | 338 | save_hook = trap.hook |
|
340 | 339 | |
|
341 | 340 | def failing_hook(*args, **kwargs): |
|
342 | 341 | d['called'] = True |
|
343 | 342 | |
|
344 | 343 | try: |
|
345 | 344 | trap.hook = failing_hook |
|
346 | 345 | res = ip.run_cell("1", silent=True) |
|
347 | 346 | self.assertFalse(d['called']) |
|
348 | 347 | self.assertIsNone(res.result) |
|
349 | 348 | # double-check that non-silent exec did what we expected |
|
350 | 349 | # silent to avoid |
|
351 | 350 | ip.run_cell("1") |
|
352 | 351 | self.assertTrue(d['called']) |
|
353 | 352 | finally: |
|
354 | 353 | trap.hook = save_hook |
|
355 | 354 | |
|
356 | 355 | @skipif(sys.version_info[0] >= 3, "softspace removed in py3") |
|
357 | 356 | def test_print_softspace(self): |
|
358 | 357 | """Verify that softspace is handled correctly when executing multiple |
|
359 | 358 | statements. |
|
360 | 359 | |
|
361 | 360 | In [1]: print 1; print 2 |
|
362 | 361 | 1 |
|
363 | 362 | 2 |
|
364 | 363 | |
|
365 | 364 | In [2]: print 1,; print 2 |
|
366 | 365 | 1 2 |
|
367 | 366 | """ |
|
368 | 367 | |
|
369 | 368 | def test_ofind_line_magic(self): |
|
370 | 369 | from IPython.core.magic import register_line_magic |
|
371 | 370 | |
|
372 | 371 | @register_line_magic |
|
373 | 372 | def lmagic(line): |
|
374 | 373 | "A line magic" |
|
375 | 374 | |
|
376 | 375 | # Get info on line magic |
|
377 | 376 | lfind = ip._ofind('lmagic') |
|
378 | 377 | info = dict(found=True, isalias=False, ismagic=True, |
|
379 | 378 | namespace = 'IPython internal', obj= lmagic.__wrapped__, |
|
380 | 379 | parent = None) |
|
381 | 380 | nt.assert_equal(lfind, info) |
|
382 | 381 | |
|
383 | 382 | def test_ofind_cell_magic(self): |
|
384 | 383 | from IPython.core.magic import register_cell_magic |
|
385 | 384 | |
|
386 | 385 | @register_cell_magic |
|
387 | 386 | def cmagic(line, cell): |
|
388 | 387 | "A cell magic" |
|
389 | 388 | |
|
390 | 389 | # Get info on cell magic |
|
391 | 390 | find = ip._ofind('cmagic') |
|
392 | 391 | info = dict(found=True, isalias=False, ismagic=True, |
|
393 | 392 | namespace = 'IPython internal', obj= cmagic.__wrapped__, |
|
394 | 393 | parent = None) |
|
395 | 394 | nt.assert_equal(find, info) |
|
396 | 395 | |
|
397 | 396 | def test_ofind_property_with_error(self): |
|
398 | 397 | class A(object): |
|
399 | 398 | @property |
|
400 | 399 | def foo(self): |
|
401 | 400 | raise NotImplementedError() |
|
402 | 401 | a = A() |
|
403 | 402 | |
|
404 | 403 | found = ip._ofind('a.foo', [('locals', locals())]) |
|
405 | 404 | info = dict(found=True, isalias=False, ismagic=False, |
|
406 | 405 | namespace='locals', obj=A.foo, parent=a) |
|
407 | 406 | nt.assert_equal(found, info) |
|
408 | 407 | |
|
409 | 408 | def test_ofind_multiple_attribute_lookups(self): |
|
410 | 409 | class A(object): |
|
411 | 410 | @property |
|
412 | 411 | def foo(self): |
|
413 | 412 | raise NotImplementedError() |
|
414 | 413 | |
|
415 | 414 | a = A() |
|
416 | 415 | a.a = A() |
|
417 | 416 | a.a.a = A() |
|
418 | 417 | |
|
419 | 418 | found = ip._ofind('a.a.a.foo', [('locals', locals())]) |
|
420 | 419 | info = dict(found=True, isalias=False, ismagic=False, |
|
421 | 420 | namespace='locals', obj=A.foo, parent=a.a.a) |
|
422 | 421 | nt.assert_equal(found, info) |
|
423 | 422 | |
|
424 | 423 | def test_ofind_slotted_attributes(self): |
|
425 | 424 | class A(object): |
|
426 | 425 | __slots__ = ['foo'] |
|
427 | 426 | def __init__(self): |
|
428 | 427 | self.foo = 'bar' |
|
429 | 428 | |
|
430 | 429 | a = A() |
|
431 | 430 | found = ip._ofind('a.foo', [('locals', locals())]) |
|
432 | 431 | info = dict(found=True, isalias=False, ismagic=False, |
|
433 | 432 | namespace='locals', obj=a.foo, parent=a) |
|
434 | 433 | nt.assert_equal(found, info) |
|
435 | 434 | |
|
436 | 435 | found = ip._ofind('a.bar', [('locals', locals())]) |
|
437 | 436 | info = dict(found=False, isalias=False, ismagic=False, |
|
438 | 437 | namespace=None, obj=None, parent=a) |
|
439 | 438 | nt.assert_equal(found, info) |
|
440 | 439 | |
|
441 | 440 | def test_ofind_prefers_property_to_instance_level_attribute(self): |
|
442 | 441 | class A(object): |
|
443 | 442 | @property |
|
444 | 443 | def foo(self): |
|
445 | 444 | return 'bar' |
|
446 | 445 | a = A() |
|
447 | 446 | a.__dict__['foo'] = 'baz' |
|
448 | 447 | nt.assert_equal(a.foo, 'bar') |
|
449 | 448 | found = ip._ofind('a.foo', [('locals', locals())]) |
|
450 | 449 | nt.assert_is(found['obj'], A.foo) |
|
451 | 450 | |
|
452 | 451 | def test_custom_exception(self): |
|
453 | 452 | called = [] |
|
454 | 453 | def my_handler(shell, etype, value, tb, tb_offset=None): |
|
455 | 454 | called.append(etype) |
|
456 | 455 | shell.showtraceback((etype, value, tb), tb_offset=tb_offset) |
|
457 | 456 | |
|
458 | 457 | ip.set_custom_exc((ValueError,), my_handler) |
|
459 | 458 | try: |
|
460 | 459 | res = ip.run_cell("raise ValueError('test')") |
|
461 | 460 | # Check that this was called, and only once. |
|
462 | 461 | self.assertEqual(called, [ValueError]) |
|
463 | 462 | # Check that the error is on the result object |
|
464 | 463 | self.assertIsInstance(res.error_in_exec, ValueError) |
|
465 | 464 | finally: |
|
466 | 465 | # Reset the custom exception hook |
|
467 | 466 | ip.set_custom_exc((), None) |
|
468 | 467 | |
|
469 | 468 | @skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3") |
|
470 | 469 | def test_future_environment(self): |
|
471 | 470 | "Can we run code with & without the shell's __future__ imports?" |
|
472 | 471 | ip.run_cell("from __future__ import division") |
|
473 | 472 | ip.run_cell("a = 1/2", shell_futures=True) |
|
474 | 473 | self.assertEqual(ip.user_ns['a'], 0.5) |
|
475 | 474 | ip.run_cell("b = 1/2", shell_futures=False) |
|
476 | 475 | self.assertEqual(ip.user_ns['b'], 0) |
|
477 | 476 | |
|
478 | 477 | ip.compile.reset_compiler_flags() |
|
479 | 478 | # This shouldn't leak to the shell's compiler |
|
480 | 479 | ip.run_cell("from __future__ import division \nc=1/2", shell_futures=False) |
|
481 | 480 | self.assertEqual(ip.user_ns['c'], 0.5) |
|
482 | 481 | ip.run_cell("d = 1/2", shell_futures=True) |
|
483 | 482 | self.assertEqual(ip.user_ns['d'], 0) |
|
484 | 483 | |
|
485 | 484 | def test_mktempfile(self): |
|
486 | 485 | filename = ip.mktempfile() |
|
487 | 486 | # Check that we can open the file again on Windows |
|
488 | 487 | with open(filename, 'w') as f: |
|
489 | 488 | f.write('abc') |
|
490 | 489 | |
|
491 | 490 | filename = ip.mktempfile(data='blah') |
|
492 | 491 | with open(filename, 'r') as f: |
|
493 | 492 | self.assertEqual(f.read(), 'blah') |
|
494 | 493 | |
|
495 | 494 | def test_new_main_mod(self): |
|
496 | 495 | # Smoketest to check that this accepts a unicode module name |
|
497 | 496 | name = u'jiefmw' |
|
498 | 497 | mod = ip.new_main_mod(u'%s.py' % name, name) |
|
499 | 498 | self.assertEqual(mod.__name__, name) |
|
500 | 499 | |
|
501 | 500 | def test_get_exception_only(self): |
|
502 | 501 | try: |
|
503 | 502 | raise KeyboardInterrupt |
|
504 | 503 | except KeyboardInterrupt: |
|
505 | 504 | msg = ip.get_exception_only() |
|
506 | 505 | self.assertEqual(msg, 'KeyboardInterrupt\n') |
|
507 | 506 | |
|
508 | 507 | try: |
|
509 | 508 | raise DerivedInterrupt("foo") |
|
510 | 509 | except KeyboardInterrupt: |
|
511 | 510 | msg = ip.get_exception_only() |
|
512 | 511 | if sys.version_info[0] <= 2: |
|
513 | 512 | self.assertEqual(msg, 'DerivedInterrupt: foo\n') |
|
514 | 513 | else: |
|
515 | 514 | self.assertEqual(msg, 'IPython.core.tests.test_interactiveshell.DerivedInterrupt: foo\n') |
|
516 | 515 | |
|
517 | 516 | class TestSafeExecfileNonAsciiPath(unittest.TestCase): |
|
518 | 517 | |
|
519 | 518 | @onlyif_unicode_paths |
|
520 | 519 | def setUp(self): |
|
521 | 520 | self.BASETESTDIR = tempfile.mkdtemp() |
|
522 | 521 | self.TESTDIR = join(self.BASETESTDIR, u"Γ₯Àâ") |
|
523 | 522 | os.mkdir(self.TESTDIR) |
|
524 | 523 | with open(join(self.TESTDIR, u"Γ₯Àâtestscript.py"), "w") as sfile: |
|
525 | 524 | sfile.write("pass\n") |
|
526 | 525 | self.oldpath = py3compat.getcwd() |
|
527 | 526 | os.chdir(self.TESTDIR) |
|
528 | 527 | self.fname = u"Γ₯Àâtestscript.py" |
|
529 | 528 | |
|
530 | 529 | def tearDown(self): |
|
531 | 530 | os.chdir(self.oldpath) |
|
532 | 531 | shutil.rmtree(self.BASETESTDIR) |
|
533 | 532 | |
|
534 | 533 | @onlyif_unicode_paths |
|
535 | 534 | def test_1(self): |
|
536 | 535 | """Test safe_execfile with non-ascii path |
|
537 | 536 | """ |
|
538 | 537 | ip.safe_execfile(self.fname, {}, raise_exceptions=True) |
|
539 | 538 | |
|
540 | 539 | class ExitCodeChecks(tt.TempFileMixin): |
|
541 | 540 | def test_exit_code_ok(self): |
|
542 | 541 | self.system('exit 0') |
|
543 | 542 | self.assertEqual(ip.user_ns['_exit_code'], 0) |
|
544 | 543 | |
|
545 | 544 | def test_exit_code_error(self): |
|
546 | 545 | self.system('exit 1') |
|
547 | 546 | self.assertEqual(ip.user_ns['_exit_code'], 1) |
|
548 | 547 | |
|
549 | 548 | @skipif(not hasattr(signal, 'SIGALRM')) |
|
550 | 549 | def test_exit_code_signal(self): |
|
551 | 550 | self.mktmp("import signal, time\n" |
|
552 | 551 | "signal.setitimer(signal.ITIMER_REAL, 0.1)\n" |
|
553 | 552 | "time.sleep(1)\n") |
|
554 | 553 | self.system("%s %s" % (sys.executable, self.fname)) |
|
555 | 554 | self.assertEqual(ip.user_ns['_exit_code'], -signal.SIGALRM) |
|
556 | 555 | |
|
557 | 556 | @onlyif_cmds_exist("csh") |
|
558 | 557 | def test_exit_code_signal_csh(self): |
|
559 | 558 | SHELL = os.environ.get('SHELL', None) |
|
560 | 559 | os.environ['SHELL'] = find_cmd("csh") |
|
561 | 560 | try: |
|
562 | 561 | self.test_exit_code_signal() |
|
563 | 562 | finally: |
|
564 | 563 | if SHELL is not None: |
|
565 | 564 | os.environ['SHELL'] = SHELL |
|
566 | 565 | else: |
|
567 | 566 | del os.environ['SHELL'] |
|
568 | 567 | |
|
569 | 568 | class TestSystemRaw(unittest.TestCase, ExitCodeChecks): |
|
570 | 569 | system = ip.system_raw |
|
571 | 570 | |
|
572 | 571 | @onlyif_unicode_paths |
|
573 | 572 | def test_1(self): |
|
574 | 573 | """Test system_raw with non-ascii cmd |
|
575 | 574 | """ |
|
576 | 575 | cmd = u'''python -c "'Γ₯Àâ'" ''' |
|
577 | 576 | ip.system_raw(cmd) |
|
578 | 577 | |
|
579 | 578 | @mock.patch('subprocess.call', side_effect=KeyboardInterrupt) |
|
580 | 579 | @mock.patch('os.system', side_effect=KeyboardInterrupt) |
|
581 | 580 | def test_control_c(self, *mocks): |
|
582 | 581 | try: |
|
583 | 582 | self.system("sleep 1 # wont happen") |
|
584 | 583 | except KeyboardInterrupt: |
|
585 | 584 | self.fail("system call should intercept " |
|
586 | 585 | "keyboard interrupt from subprocess.call") |
|
587 | 586 | self.assertEqual(ip.user_ns['_exit_code'], -signal.SIGINT) |
|
588 | 587 | |
|
589 | 588 | # TODO: Exit codes are currently ignored on Windows. |
|
590 | 589 | class TestSystemPipedExitCode(unittest.TestCase, ExitCodeChecks): |
|
591 | 590 | system = ip.system_piped |
|
592 | 591 | |
|
593 | 592 | @skip_win32 |
|
594 | 593 | def test_exit_code_ok(self): |
|
595 | 594 | ExitCodeChecks.test_exit_code_ok(self) |
|
596 | 595 | |
|
597 | 596 | @skip_win32 |
|
598 | 597 | def test_exit_code_error(self): |
|
599 | 598 | ExitCodeChecks.test_exit_code_error(self) |
|
600 | 599 | |
|
601 | 600 | @skip_win32 |
|
602 | 601 | def test_exit_code_signal(self): |
|
603 | 602 | ExitCodeChecks.test_exit_code_signal(self) |
|
604 | 603 | |
|
605 | 604 | class TestModules(unittest.TestCase, tt.TempFileMixin): |
|
606 | 605 | def test_extraneous_loads(self): |
|
607 | 606 | """Test we're not loading modules on startup that we shouldn't. |
|
608 | 607 | """ |
|
609 | 608 | self.mktmp("import sys\n" |
|
610 | 609 | "print('numpy' in sys.modules)\n" |
|
611 | 610 | "print('ipyparallel' in sys.modules)\n" |
|
612 | 611 | "print('ipykernel' in sys.modules)\n" |
|
613 | 612 | ) |
|
614 | 613 | out = "False\nFalse\nFalse\n" |
|
615 | 614 | tt.ipexec_validate(self.fname, out) |
|
616 | 615 | |
|
617 | 616 | class Negator(ast.NodeTransformer): |
|
618 | 617 | """Negates all number literals in an AST.""" |
|
619 | 618 | def visit_Num(self, node): |
|
620 | 619 | node.n = -node.n |
|
621 | 620 | return node |
|
622 | 621 | |
|
623 | 622 | class TestAstTransform(unittest.TestCase): |
|
624 | 623 | def setUp(self): |
|
625 | 624 | self.negator = Negator() |
|
626 | 625 | ip.ast_transformers.append(self.negator) |
|
627 | 626 | |
|
628 | 627 | def tearDown(self): |
|
629 | 628 | ip.ast_transformers.remove(self.negator) |
|
630 | 629 | |
|
631 | 630 | def test_run_cell(self): |
|
632 | 631 | with tt.AssertPrints('-34'): |
|
633 | 632 | ip.run_cell('print (12 + 22)') |
|
634 | 633 | |
|
635 | 634 | # A named reference to a number shouldn't be transformed. |
|
636 | 635 | ip.user_ns['n'] = 55 |
|
637 | 636 | with tt.AssertNotPrints('-55'): |
|
638 | 637 | ip.run_cell('print (n)') |
|
639 | 638 | |
|
640 | 639 | def test_timeit(self): |
|
641 | 640 | called = set() |
|
642 | 641 | def f(x): |
|
643 | 642 | called.add(x) |
|
644 | 643 | ip.push({'f':f}) |
|
645 | 644 | |
|
646 | 645 | with tt.AssertPrints("best of "): |
|
647 | 646 | ip.run_line_magic("timeit", "-n1 f(1)") |
|
648 | 647 | self.assertEqual(called, {-1}) |
|
649 | 648 | called.clear() |
|
650 | 649 | |
|
651 | 650 | with tt.AssertPrints("best of "): |
|
652 | 651 | ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)") |
|
653 | 652 | self.assertEqual(called, {-2, -3}) |
|
654 | 653 | |
|
655 | 654 | def test_time(self): |
|
656 | 655 | called = [] |
|
657 | 656 | def f(x): |
|
658 | 657 | called.append(x) |
|
659 | 658 | ip.push({'f':f}) |
|
660 | 659 | |
|
661 | 660 | # Test with an expression |
|
662 | 661 | with tt.AssertPrints("Wall time: "): |
|
663 | 662 | ip.run_line_magic("time", "f(5+9)") |
|
664 | 663 | self.assertEqual(called, [-14]) |
|
665 | 664 | called[:] = [] |
|
666 | 665 | |
|
667 | 666 | # Test with a statement (different code path) |
|
668 | 667 | with tt.AssertPrints("Wall time: "): |
|
669 | 668 | ip.run_line_magic("time", "a = f(-3 + -2)") |
|
670 | 669 | self.assertEqual(called, [5]) |
|
671 | 670 | |
|
672 | 671 | def test_macro(self): |
|
673 | 672 | ip.push({'a':10}) |
|
674 | 673 | # The AST transformation makes this do a+=-1 |
|
675 | 674 | ip.define_macro("amacro", "a+=1\nprint(a)") |
|
676 | 675 | |
|
677 | 676 | with tt.AssertPrints("9"): |
|
678 | 677 | ip.run_cell("amacro") |
|
679 | 678 | with tt.AssertPrints("8"): |
|
680 | 679 | ip.run_cell("amacro") |
|
681 | 680 | |
|
682 | 681 | class IntegerWrapper(ast.NodeTransformer): |
|
683 | 682 | """Wraps all integers in a call to Integer()""" |
|
684 | 683 | def visit_Num(self, node): |
|
685 | 684 | if isinstance(node.n, int): |
|
686 | 685 | return ast.Call(func=ast.Name(id='Integer', ctx=ast.Load()), |
|
687 | 686 | args=[node], keywords=[]) |
|
688 | 687 | return node |
|
689 | 688 | |
|
690 | 689 | class TestAstTransform2(unittest.TestCase): |
|
691 | 690 | def setUp(self): |
|
692 | 691 | self.intwrapper = IntegerWrapper() |
|
693 | 692 | ip.ast_transformers.append(self.intwrapper) |
|
694 | 693 | |
|
695 | 694 | self.calls = [] |
|
696 | 695 | def Integer(*args): |
|
697 | 696 | self.calls.append(args) |
|
698 | 697 | return args |
|
699 | 698 | ip.push({"Integer": Integer}) |
|
700 | 699 | |
|
701 | 700 | def tearDown(self): |
|
702 | 701 | ip.ast_transformers.remove(self.intwrapper) |
|
703 | 702 | del ip.user_ns['Integer'] |
|
704 | 703 | |
|
705 | 704 | def test_run_cell(self): |
|
706 | 705 | ip.run_cell("n = 2") |
|
707 | 706 | self.assertEqual(self.calls, [(2,)]) |
|
708 | 707 | |
|
709 | 708 | # This shouldn't throw an error |
|
710 | 709 | ip.run_cell("o = 2.0") |
|
711 | 710 | self.assertEqual(ip.user_ns['o'], 2.0) |
|
712 | 711 | |
|
713 | 712 | def test_timeit(self): |
|
714 | 713 | called = set() |
|
715 | 714 | def f(x): |
|
716 | 715 | called.add(x) |
|
717 | 716 | ip.push({'f':f}) |
|
718 | 717 | |
|
719 | 718 | with tt.AssertPrints("best of "): |
|
720 | 719 | ip.run_line_magic("timeit", "-n1 f(1)") |
|
721 | 720 | self.assertEqual(called, {(1,)}) |
|
722 | 721 | called.clear() |
|
723 | 722 | |
|
724 | 723 | with tt.AssertPrints("best of "): |
|
725 | 724 | ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)") |
|
726 | 725 | self.assertEqual(called, {(2,), (3,)}) |
|
727 | 726 | |
|
728 | 727 | class ErrorTransformer(ast.NodeTransformer): |
|
729 | 728 | """Throws an error when it sees a number.""" |
|
730 | 729 | def visit_Num(self, node): |
|
731 | 730 | raise ValueError("test") |
|
732 | 731 | |
|
733 | 732 | class TestAstTransformError(unittest.TestCase): |
|
734 | 733 | def test_unregistering(self): |
|
735 | 734 | err_transformer = ErrorTransformer() |
|
736 | 735 | ip.ast_transformers.append(err_transformer) |
|
737 | 736 | |
|
738 | 737 | with tt.AssertPrints("unregister", channel='stderr'): |
|
739 | 738 | ip.run_cell("1 + 2") |
|
740 | 739 | |
|
741 | 740 | # This should have been removed. |
|
742 | 741 | nt.assert_not_in(err_transformer, ip.ast_transformers) |
|
743 | 742 | |
|
744 | 743 | |
|
745 | 744 | class StringRejector(ast.NodeTransformer): |
|
746 | 745 | """Throws an InputRejected when it sees a string literal. |
|
747 | 746 | |
|
748 | 747 | Used to verify that NodeTransformers can signal that a piece of code should |
|
749 | 748 | not be executed by throwing an InputRejected. |
|
750 | 749 | """ |
|
751 | 750 | |
|
752 | 751 | def visit_Str(self, node): |
|
753 | 752 | raise InputRejected("test") |
|
754 | 753 | |
|
755 | 754 | |
|
756 | 755 | class TestAstTransformInputRejection(unittest.TestCase): |
|
757 | 756 | |
|
758 | 757 | def setUp(self): |
|
759 | 758 | self.transformer = StringRejector() |
|
760 | 759 | ip.ast_transformers.append(self.transformer) |
|
761 | 760 | |
|
762 | 761 | def tearDown(self): |
|
763 | 762 | ip.ast_transformers.remove(self.transformer) |
|
764 | 763 | |
|
765 | 764 | def test_input_rejection(self): |
|
766 | 765 | """Check that NodeTransformers can reject input.""" |
|
767 | 766 | |
|
768 | 767 | expect_exception_tb = tt.AssertPrints("InputRejected: test") |
|
769 | 768 | expect_no_cell_output = tt.AssertNotPrints("'unsafe'", suppress=False) |
|
770 | 769 | |
|
771 | 770 | # Run the same check twice to verify that the transformer is not |
|
772 | 771 | # disabled after raising. |
|
773 | 772 | with expect_exception_tb, expect_no_cell_output: |
|
774 | 773 | ip.run_cell("'unsafe'") |
|
775 | 774 | |
|
776 | 775 | with expect_exception_tb, expect_no_cell_output: |
|
777 | 776 | res = ip.run_cell("'unsafe'") |
|
778 | 777 | |
|
779 | 778 | self.assertIsInstance(res.error_before_exec, InputRejected) |
|
780 | 779 | |
|
781 | 780 | def test__IPYTHON__(): |
|
782 | 781 | # This shouldn't raise a NameError, that's all |
|
783 | 782 | __IPYTHON__ |
|
784 | 783 | |
|
785 | 784 | |
|
786 | 785 | class DummyRepr(object): |
|
787 | 786 | def __repr__(self): |
|
788 | 787 | return "DummyRepr" |
|
789 | 788 | |
|
790 | 789 | def _repr_html_(self): |
|
791 | 790 | return "<b>dummy</b>" |
|
792 | 791 | |
|
793 | 792 | def _repr_javascript_(self): |
|
794 | 793 | return "console.log('hi');", {'key': 'value'} |
|
795 | 794 | |
|
796 | 795 | |
|
797 | 796 | def test_user_variables(): |
|
798 | 797 | # enable all formatters |
|
799 | 798 | ip.display_formatter.active_types = ip.display_formatter.format_types |
|
800 | 799 | |
|
801 | 800 | ip.user_ns['dummy'] = d = DummyRepr() |
|
802 | 801 | keys = {'dummy', 'doesnotexist'} |
|
803 | 802 | r = ip.user_expressions({ key:key for key in keys}) |
|
804 | 803 | |
|
805 | 804 | nt.assert_equal(keys, set(r.keys())) |
|
806 | 805 | dummy = r['dummy'] |
|
807 | 806 | nt.assert_equal({'status', 'data', 'metadata'}, set(dummy.keys())) |
|
808 | 807 | nt.assert_equal(dummy['status'], 'ok') |
|
809 | 808 | data = dummy['data'] |
|
810 | 809 | metadata = dummy['metadata'] |
|
811 | 810 | nt.assert_equal(data.get('text/html'), d._repr_html_()) |
|
812 | 811 | js, jsmd = d._repr_javascript_() |
|
813 | 812 | nt.assert_equal(data.get('application/javascript'), js) |
|
814 | 813 | nt.assert_equal(metadata.get('application/javascript'), jsmd) |
|
815 | 814 | |
|
816 | 815 | dne = r['doesnotexist'] |
|
817 | 816 | nt.assert_equal(dne['status'], 'error') |
|
818 | 817 | nt.assert_equal(dne['ename'], 'NameError') |
|
819 | 818 | |
|
820 | 819 | # back to text only |
|
821 | 820 | ip.display_formatter.active_types = ['text/plain'] |
|
822 | 821 | |
|
823 | 822 | def test_user_expression(): |
|
824 | 823 | # enable all formatters |
|
825 | 824 | ip.display_formatter.active_types = ip.display_formatter.format_types |
|
826 | 825 | query = { |
|
827 | 826 | 'a' : '1 + 2', |
|
828 | 827 | 'b' : '1/0', |
|
829 | 828 | } |
|
830 | 829 | r = ip.user_expressions(query) |
|
831 | 830 | import pprint |
|
832 | 831 | pprint.pprint(r) |
|
833 | 832 | nt.assert_equal(set(r.keys()), set(query.keys())) |
|
834 | 833 | a = r['a'] |
|
835 | 834 | nt.assert_equal({'status', 'data', 'metadata'}, set(a.keys())) |
|
836 | 835 | nt.assert_equal(a['status'], 'ok') |
|
837 | 836 | data = a['data'] |
|
838 | 837 | metadata = a['metadata'] |
|
839 | 838 | nt.assert_equal(data.get('text/plain'), '3') |
|
840 | 839 | |
|
841 | 840 | b = r['b'] |
|
842 | 841 | nt.assert_equal(b['status'], 'error') |
|
843 | 842 | nt.assert_equal(b['ename'], 'ZeroDivisionError') |
|
844 | 843 | |
|
845 | 844 | # back to text only |
|
846 | 845 | ip.display_formatter.active_types = ['text/plain'] |
|
847 | 846 | |
|
848 | 847 | |
|
849 | 848 | |
|
850 | 849 | |
|
851 | 850 | |
|
852 | 851 | class TestSyntaxErrorTransformer(unittest.TestCase): |
|
853 | 852 | """Check that SyntaxError raised by an input transformer is handled by run_cell()""" |
|
854 | 853 | |
|
855 | 854 | class SyntaxErrorTransformer(InputTransformer): |
|
856 | 855 | |
|
857 | 856 | def push(self, line): |
|
858 | 857 | pos = line.find('syntaxerror') |
|
859 | 858 | if pos >= 0: |
|
860 | 859 | e = SyntaxError('input contains "syntaxerror"') |
|
861 | 860 | e.text = line |
|
862 | 861 | e.offset = pos + 1 |
|
863 | 862 | raise e |
|
864 | 863 | return line |
|
865 | 864 | |
|
866 | 865 | def reset(self): |
|
867 | 866 | pass |
|
868 | 867 | |
|
869 | 868 | def setUp(self): |
|
870 | 869 | self.transformer = TestSyntaxErrorTransformer.SyntaxErrorTransformer() |
|
871 | 870 | ip.input_splitter.python_line_transforms.append(self.transformer) |
|
872 | 871 | ip.input_transformer_manager.python_line_transforms.append(self.transformer) |
|
873 | 872 | |
|
874 | 873 | def tearDown(self): |
|
875 | 874 | ip.input_splitter.python_line_transforms.remove(self.transformer) |
|
876 | 875 | ip.input_transformer_manager.python_line_transforms.remove(self.transformer) |
|
877 | 876 | |
|
878 | 877 | def test_syntaxerror_input_transformer(self): |
|
879 | 878 | with tt.AssertPrints('1234'): |
|
880 | 879 | ip.run_cell('1234') |
|
881 | 880 | with tt.AssertPrints('SyntaxError: invalid syntax'): |
|
882 | 881 | ip.run_cell('1 2 3') # plain python syntax error |
|
883 | 882 | with tt.AssertPrints('SyntaxError: input contains "syntaxerror"'): |
|
884 | 883 | ip.run_cell('2345 # syntaxerror') # input transformer syntax error |
|
885 | 884 | with tt.AssertPrints('3456'): |
|
886 | 885 | ip.run_cell('3456') |
|
887 | 886 | |
|
888 | 887 | |
|
889 | 888 | |
|
890 | 889 | def test_warning_suppression(): |
|
891 | 890 | ip.run_cell("import warnings") |
|
892 | 891 | try: |
|
893 | 892 | with tt.AssertPrints("UserWarning: asdf", channel="stderr"): |
|
894 | 893 | ip.run_cell("warnings.warn('asdf')") |
|
895 | 894 | # Here's the real test -- if we run that again, we should get the |
|
896 | 895 | # warning again. Traditionally, each warning was only issued once per |
|
897 | 896 | # IPython session (approximately), even if the user typed in new and |
|
898 | 897 | # different code that should have also triggered the warning, leading |
|
899 | 898 | # to much confusion. |
|
900 | 899 | with tt.AssertPrints("UserWarning: asdf", channel="stderr"): |
|
901 | 900 | ip.run_cell("warnings.warn('asdf')") |
|
902 | 901 | finally: |
|
903 | 902 | ip.run_cell("del warnings") |
|
904 | 903 | |
|
905 | 904 | |
|
906 | 905 | def test_deprecation_warning(): |
|
907 | 906 | ip.run_cell(""" |
|
908 | 907 | import warnings |
|
909 | 908 | def wrn(): |
|
910 | 909 | warnings.warn( |
|
911 | 910 | "I AM A WARNING", |
|
912 | 911 | DeprecationWarning |
|
913 | 912 | ) |
|
914 | 913 | """) |
|
915 | 914 | try: |
|
916 | 915 | with tt.AssertPrints("I AM A WARNING", channel="stderr"): |
|
917 | 916 | ip.run_cell("wrn()") |
|
918 | 917 | finally: |
|
919 | 918 | ip.run_cell("del warnings") |
|
920 | 919 | ip.run_cell("del wrn") |
|
921 | 920 | |
|
922 | 921 | |
|
923 | 922 | class TestImportNoDeprecate(tt.TempFileMixin): |
|
924 | 923 | |
|
925 | 924 | def setup(self): |
|
926 | 925 | """Make a valid python temp file.""" |
|
927 | 926 | self.mktmp(""" |
|
928 | 927 | import warnings |
|
929 | 928 | def wrn(): |
|
930 | 929 | warnings.warn( |
|
931 | 930 | "I AM A WARNING", |
|
932 | 931 | DeprecationWarning |
|
933 | 932 | ) |
|
934 | 933 | """) |
|
935 | 934 | |
|
936 | 935 | def test_no_dep(self): |
|
937 | 936 | """ |
|
938 | 937 | No deprecation warning should be raised from imported functions |
|
939 | 938 | """ |
|
940 | 939 | ip.run_cell("from {} import wrn".format(self.fname)) |
|
941 | 940 | |
|
942 | 941 | with tt.AssertNotPrints("I AM A WARNING"): |
|
943 | 942 | ip.run_cell("wrn()") |
|
944 | 943 | ip.run_cell("del wrn") |
@@ -1,360 +1,361 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Provides a reload() function that acts recursively. |
|
4 | 4 | |
|
5 | 5 | Python's normal :func:`python:reload` function only reloads the module that it's |
|
6 | 6 | passed. The :func:`reload` function in this module also reloads everything |
|
7 | 7 | imported from that module, which is useful when you're changing files deep |
|
8 | 8 | inside a package. |
|
9 | 9 | |
|
10 | 10 | To use this as your default reload function, type this for Python 2:: |
|
11 | 11 | |
|
12 | 12 | import __builtin__ |
|
13 | 13 | from IPython.lib import deepreload |
|
14 | 14 | __builtin__.reload = deepreload.reload |
|
15 | 15 | |
|
16 | 16 | Or this for Python 3:: |
|
17 | 17 | |
|
18 | 18 | import builtins |
|
19 | 19 | from IPython.lib import deepreload |
|
20 | 20 | builtins.reload = deepreload.reload |
|
21 | 21 | |
|
22 | 22 | A reference to the original :func:`python:reload` is stored in this module as |
|
23 | 23 | :data:`original_reload`, so you can restore it later. |
|
24 | 24 | |
|
25 | 25 | This code is almost entirely based on knee.py, which is a Python |
|
26 | 26 | re-implementation of hierarchical module import. |
|
27 | 27 | """ |
|
28 | 28 | from __future__ import print_function |
|
29 | 29 | #***************************************************************************** |
|
30 | 30 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
31 | 31 | # |
|
32 | 32 | # Distributed under the terms of the BSD License. The full license is in |
|
33 | 33 | # the file COPYING, distributed as part of this software. |
|
34 | 34 | #***************************************************************************** |
|
35 | 35 | |
|
36 | 36 | from contextlib import contextmanager |
|
37 | 37 | import imp |
|
38 | 38 | import sys |
|
39 | 39 | |
|
40 | 40 | from types import ModuleType |
|
41 | 41 | from warnings import warn |
|
42 | 42 | |
|
43 | 43 | from IPython.utils.py3compat import builtin_mod, builtin_mod_name |
|
44 | 44 | |
|
45 | 45 | original_import = builtin_mod.__import__ |
|
46 | 46 | |
|
47 | 47 | @contextmanager |
|
48 | 48 | def replace_import_hook(new_import): |
|
49 | 49 | saved_import = builtin_mod.__import__ |
|
50 | 50 | builtin_mod.__import__ = new_import |
|
51 | 51 | try: |
|
52 | 52 | yield |
|
53 | 53 | finally: |
|
54 | 54 | builtin_mod.__import__ = saved_import |
|
55 | 55 | |
|
56 | 56 | def get_parent(globals, level): |
|
57 | 57 | """ |
|
58 | 58 | parent, name = get_parent(globals, level) |
|
59 | 59 | |
|
60 | 60 | Return the package that an import is being performed in. If globals comes |
|
61 | 61 | from the module foo.bar.bat (not itself a package), this returns the |
|
62 | 62 | sys.modules entry for foo.bar. If globals is from a package's __init__.py, |
|
63 | 63 | the package's entry in sys.modules is returned. |
|
64 | 64 | |
|
65 | 65 | If globals doesn't come from a package or a module in a package, or a |
|
66 | 66 | corresponding entry is not found in sys.modules, None is returned. |
|
67 | 67 | """ |
|
68 | 68 | orig_level = level |
|
69 | 69 | |
|
70 | 70 | if not level or not isinstance(globals, dict): |
|
71 | 71 | return None, '' |
|
72 | 72 | |
|
73 | 73 | pkgname = globals.get('__package__', None) |
|
74 | 74 | |
|
75 | 75 | if pkgname is not None: |
|
76 | 76 | # __package__ is set, so use it |
|
77 | 77 | if not hasattr(pkgname, 'rindex'): |
|
78 | 78 | raise ValueError('__package__ set to non-string') |
|
79 | 79 | if len(pkgname) == 0: |
|
80 | 80 | if level > 0: |
|
81 | 81 | raise ValueError('Attempted relative import in non-package') |
|
82 | 82 | return None, '' |
|
83 | 83 | name = pkgname |
|
84 | 84 | else: |
|
85 | 85 | # __package__ not set, so figure it out and set it |
|
86 | 86 | if '__name__' not in globals: |
|
87 | 87 | return None, '' |
|
88 | 88 | modname = globals['__name__'] |
|
89 | 89 | |
|
90 | 90 | if '__path__' in globals: |
|
91 | 91 | # __path__ is set, so modname is already the package name |
|
92 | 92 | globals['__package__'] = name = modname |
|
93 | 93 | else: |
|
94 | 94 | # Normal module, so work out the package name if any |
|
95 | 95 | lastdot = modname.rfind('.') |
|
96 | 96 | if lastdot < 0 < level: |
|
97 | 97 | raise ValueError("Attempted relative import in non-package") |
|
98 | 98 | if lastdot < 0: |
|
99 | 99 | globals['__package__'] = None |
|
100 | 100 | return None, '' |
|
101 | 101 | globals['__package__'] = name = modname[:lastdot] |
|
102 | 102 | |
|
103 | 103 | dot = len(name) |
|
104 | 104 | for x in range(level, 1, -1): |
|
105 | 105 | try: |
|
106 | 106 | dot = name.rindex('.', 0, dot) |
|
107 | 107 | except ValueError: |
|
108 | 108 | raise ValueError("attempted relative import beyond top-level " |
|
109 | 109 | "package") |
|
110 | 110 | name = name[:dot] |
|
111 | 111 | |
|
112 | 112 | try: |
|
113 | 113 | parent = sys.modules[name] |
|
114 | 114 | except: |
|
115 | 115 | if orig_level < 1: |
|
116 | 116 | warn("Parent module '%.200s' not found while handling absolute " |
|
117 | 117 | "import" % name) |
|
118 | 118 | parent = None |
|
119 | 119 | else: |
|
120 | 120 | raise SystemError("Parent module '%.200s' not loaded, cannot " |
|
121 | 121 | "perform relative import" % name) |
|
122 | 122 | |
|
123 | 123 | # We expect, but can't guarantee, if parent != None, that: |
|
124 | 124 | # - parent.__name__ == name |
|
125 | 125 | # - parent.__dict__ is globals |
|
126 | 126 | # If this is violated... Who cares? |
|
127 | 127 | return parent, name |
|
128 | 128 | |
|
129 | 129 | def load_next(mod, altmod, name, buf): |
|
130 | 130 | """ |
|
131 | 131 | mod, name, buf = load_next(mod, altmod, name, buf) |
|
132 | 132 | |
|
133 | 133 | altmod is either None or same as mod |
|
134 | 134 | """ |
|
135 | 135 | |
|
136 | 136 | if len(name) == 0: |
|
137 | 137 | # completely empty module name should only happen in |
|
138 | 138 | # 'from . import' (or '__import__("")') |
|
139 | 139 | return mod, None, buf |
|
140 | 140 | |
|
141 | 141 | dot = name.find('.') |
|
142 | 142 | if dot == 0: |
|
143 | 143 | raise ValueError('Empty module name') |
|
144 | 144 | |
|
145 | 145 | if dot < 0: |
|
146 | 146 | subname = name |
|
147 | 147 | next = None |
|
148 | 148 | else: |
|
149 | 149 | subname = name[:dot] |
|
150 | 150 | next = name[dot+1:] |
|
151 | 151 | |
|
152 | 152 | if buf != '': |
|
153 | 153 | buf += '.' |
|
154 | 154 | buf += subname |
|
155 | 155 | |
|
156 | 156 | result = import_submodule(mod, subname, buf) |
|
157 | 157 | if result is None and mod != altmod: |
|
158 | 158 | result = import_submodule(altmod, subname, subname) |
|
159 | 159 | if result is not None: |
|
160 | 160 | buf = subname |
|
161 | 161 | |
|
162 | 162 | if result is None: |
|
163 | 163 | raise ImportError("No module named %.200s" % name) |
|
164 | 164 | |
|
165 | 165 | return result, next, buf |
|
166 | 166 | |
|
167 | 167 | # Need to keep track of what we've already reloaded to prevent cyclic evil |
|
168 | 168 | found_now = {} |
|
169 | 169 | |
|
170 | 170 | def import_submodule(mod, subname, fullname): |
|
171 | 171 | """m = import_submodule(mod, subname, fullname)""" |
|
172 | 172 | # Require: |
|
173 | 173 | # if mod == None: subname == fullname |
|
174 | 174 | # else: mod.__name__ + "." + subname == fullname |
|
175 | 175 | |
|
176 | 176 | global found_now |
|
177 | 177 | if fullname in found_now and fullname in sys.modules: |
|
178 | 178 | m = sys.modules[fullname] |
|
179 | 179 | else: |
|
180 | 180 | print('Reloading', fullname) |
|
181 | 181 | found_now[fullname] = 1 |
|
182 | 182 | oldm = sys.modules.get(fullname, None) |
|
183 | 183 | |
|
184 | 184 | if mod is None: |
|
185 | 185 | path = None |
|
186 | 186 | elif hasattr(mod, '__path__'): |
|
187 | 187 | path = mod.__path__ |
|
188 | 188 | else: |
|
189 | 189 | return None |
|
190 | 190 | |
|
191 | 191 | try: |
|
192 | 192 | # This appears to be necessary on Python 3, because imp.find_module() |
|
193 | 193 | # tries to import standard libraries (like io) itself, and we don't |
|
194 | 194 | # want them to be processed by our deep_import_hook. |
|
195 | 195 | with replace_import_hook(original_import): |
|
196 | 196 | fp, filename, stuff = imp.find_module(subname, path) |
|
197 | 197 | except ImportError: |
|
198 | 198 | return None |
|
199 | 199 | |
|
200 | 200 | try: |
|
201 | 201 | m = imp.load_module(fullname, fp, filename, stuff) |
|
202 | 202 | except: |
|
203 | 203 | # load_module probably removed name from modules because of |
|
204 | 204 | # the error. Put back the original module object. |
|
205 | 205 | if oldm: |
|
206 | 206 | sys.modules[fullname] = oldm |
|
207 | 207 | raise |
|
208 | 208 | finally: |
|
209 | 209 | if fp: fp.close() |
|
210 | 210 | |
|
211 | 211 | add_submodule(mod, m, fullname, subname) |
|
212 | 212 | |
|
213 | 213 | return m |
|
214 | 214 | |
|
215 | 215 | def add_submodule(mod, submod, fullname, subname): |
|
216 | 216 | """mod.{subname} = submod""" |
|
217 | 217 | if mod is None: |
|
218 | 218 | return #Nothing to do here. |
|
219 | 219 | |
|
220 | 220 | if submod is None: |
|
221 | 221 | submod = sys.modules[fullname] |
|
222 | 222 | |
|
223 | 223 | setattr(mod, subname, submod) |
|
224 | 224 | |
|
225 | 225 | return |
|
226 | 226 | |
|
227 | 227 | def ensure_fromlist(mod, fromlist, buf, recursive): |
|
228 | 228 | """Handle 'from module import a, b, c' imports.""" |
|
229 | 229 | if not hasattr(mod, '__path__'): |
|
230 | 230 | return |
|
231 | 231 | for item in fromlist: |
|
232 | 232 | if not hasattr(item, 'rindex'): |
|
233 | 233 | raise TypeError("Item in ``from list'' not a string") |
|
234 | 234 | if item == '*': |
|
235 | 235 | if recursive: |
|
236 | 236 | continue # avoid endless recursion |
|
237 | 237 | try: |
|
238 | 238 | all = mod.__all__ |
|
239 | 239 | except AttributeError: |
|
240 | 240 | pass |
|
241 | 241 | else: |
|
242 | 242 | ret = ensure_fromlist(mod, all, buf, 1) |
|
243 | 243 | if not ret: |
|
244 | 244 | return 0 |
|
245 | 245 | elif not hasattr(mod, item): |
|
246 | 246 | import_submodule(mod, item, buf + '.' + item) |
|
247 | 247 | |
|
248 | 248 | def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1): |
|
249 | 249 | """Replacement for __import__()""" |
|
250 | 250 | parent, buf = get_parent(globals, level) |
|
251 | 251 | |
|
252 | 252 | head, name, buf = load_next(parent, None if level < 0 else parent, name, buf) |
|
253 | 253 | |
|
254 | 254 | tail = head |
|
255 | 255 | while name: |
|
256 | 256 | tail, name, buf = load_next(tail, tail, name, buf) |
|
257 | 257 | |
|
258 | 258 | # If tail is None, both get_parent and load_next found |
|
259 | 259 | # an empty module name: someone called __import__("") or |
|
260 | 260 | # doctored faulty bytecode |
|
261 | 261 | if tail is None: |
|
262 | 262 | raise ValueError('Empty module name') |
|
263 | 263 | |
|
264 | 264 | if not fromlist: |
|
265 | 265 | return head |
|
266 | 266 | |
|
267 | 267 | ensure_fromlist(tail, fromlist, buf, 0) |
|
268 | 268 | return tail |
|
269 | 269 | |
|
270 | 270 | modules_reloading = {} |
|
271 | 271 | |
|
272 | 272 | def deep_reload_hook(m): |
|
273 | 273 | """Replacement for reload().""" |
|
274 | 274 | if not isinstance(m, ModuleType): |
|
275 | 275 | raise TypeError("reload() argument must be module") |
|
276 | 276 | |
|
277 | 277 | name = m.__name__ |
|
278 | 278 | |
|
279 | 279 | if name not in sys.modules: |
|
280 | 280 | raise ImportError("reload(): module %.200s not in sys.modules" % name) |
|
281 | 281 | |
|
282 | 282 | global modules_reloading |
|
283 | 283 | try: |
|
284 | 284 | return modules_reloading[name] |
|
285 | 285 | except: |
|
286 | 286 | modules_reloading[name] = m |
|
287 | 287 | |
|
288 | 288 | dot = name.rfind('.') |
|
289 | 289 | if dot < 0: |
|
290 | 290 | subname = name |
|
291 | 291 | path = None |
|
292 | 292 | else: |
|
293 | 293 | try: |
|
294 | 294 | parent = sys.modules[name[:dot]] |
|
295 | 295 | except KeyError: |
|
296 | 296 | modules_reloading.clear() |
|
297 | 297 | raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot]) |
|
298 | 298 | subname = name[dot+1:] |
|
299 | 299 | path = getattr(parent, "__path__", None) |
|
300 | 300 | |
|
301 | 301 | try: |
|
302 | 302 | # This appears to be necessary on Python 3, because imp.find_module() |
|
303 | 303 | # tries to import standard libraries (like io) itself, and we don't |
|
304 | 304 | # want them to be processed by our deep_import_hook. |
|
305 | 305 | with replace_import_hook(original_import): |
|
306 | 306 | fp, filename, stuff = imp.find_module(subname, path) |
|
307 | 307 | finally: |
|
308 | 308 | modules_reloading.clear() |
|
309 | 309 | |
|
310 | 310 | try: |
|
311 | 311 | newm = imp.load_module(name, fp, filename, stuff) |
|
312 | 312 | except: |
|
313 | 313 | # load_module probably removed name from modules because of |
|
314 | 314 | # the error. Put back the original module object. |
|
315 | 315 | sys.modules[name] = m |
|
316 | 316 | raise |
|
317 | 317 | finally: |
|
318 | 318 | if fp: fp.close() |
|
319 | 319 | |
|
320 | 320 | modules_reloading.clear() |
|
321 | 321 | return newm |
|
322 | 322 | |
|
323 | 323 | # Save the original hooks |
|
324 | 324 | try: |
|
325 | 325 | original_reload = builtin_mod.reload |
|
326 | 326 | except AttributeError: |
|
327 | 327 | original_reload = imp.reload # Python 3 |
|
328 | 328 | |
|
329 | 329 | # Replacement for reload() |
|
330 | 330 | def reload(module, exclude=('sys', 'os.path', builtin_mod_name, '__main__')): |
|
331 | 331 | """Recursively reload all modules used in the given module. Optionally |
|
332 | 332 | takes a list of modules to exclude from reloading. The default exclude |
|
333 | 333 | list contains sys, __main__, and __builtin__, to prevent, e.g., resetting |
|
334 | 334 | display, exception, and io hooks. |
|
335 | 335 | """ |
|
336 | 336 | global found_now |
|
337 | 337 | for i in exclude: |
|
338 | 338 | found_now[i] = 1 |
|
339 | 339 | try: |
|
340 | 340 | with replace_import_hook(deep_import_hook): |
|
341 | 341 | return deep_reload_hook(module) |
|
342 | 342 | finally: |
|
343 | 343 | found_now = {} |
|
344 | 344 | |
|
345 | 345 | |
|
346 | 346 | def _dreload(module, **kwargs): |
|
347 | 347 | """ |
|
348 | 348 | **deprecated** |
|
349 | 349 | |
|
350 | 350 | import reload explicitly from `IPython.lib.deepreload` to use it |
|
351 | 351 | |
|
352 | 352 | """ |
|
353 | 353 | warn(""" |
|
354 |
injecting `dreload` in interactive namespace is deprecated, |
|
|
354 | injecting `dreload` in interactive namespace is deprecated, and will be removed in IPython 5.0. | |
|
355 | Please import `reload` explicitly from `IPython.lib.deepreload`. | |
|
355 | 356 | """, DeprecationWarning, stacklevel=2) |
|
356 | 357 | reload(module, **kwargs) |
|
357 | 358 | |
|
358 | 359 | # Uncomment the following to automatically activate deep reloading whenever |
|
359 | 360 | # this module is imported |
|
360 | 361 | #builtin_mod.reload = reload |
@@ -1,12 +1,13 b'' | |||
|
1 | 1 | """[DEPRECATED] Utilities for connecting to kernels |
|
2 | 2 | |
|
3 | 3 | Moved to IPython.kernel.connect |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | import warnings |
|
7 |
warnings.warn("IPython.lib.kernel moved to IPython.kernel.connect in IPython 1.0" |
|
|
7 | warnings.warn("IPython.lib.kernel moved to IPython.kernel.connect in IPython 1.0," | |
|
8 | "and will be removed in IPython 6.0.", | |
|
8 | 9 | DeprecationWarning |
|
9 | 10 | ) |
|
10 | 11 | |
|
11 | 12 | from ipykernel.connect import * |
|
12 | 13 |
@@ -1,278 +1,278 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | An embedded IPython shell. |
|
4 | 4 | """ |
|
5 | 5 | # Copyright (c) IPython Development Team. |
|
6 | 6 | # Distributed under the terms of the Modified BSD License. |
|
7 | 7 | |
|
8 | 8 | from __future__ import with_statement |
|
9 | 9 | from __future__ import print_function |
|
10 | 10 | |
|
11 | 11 | import sys |
|
12 | 12 | import warnings |
|
13 | 13 | |
|
14 | 14 | from IPython.core import ultratb, compilerop |
|
15 | 15 | from IPython.core.magic import Magics, magics_class, line_magic |
|
16 | 16 | from IPython.core.interactiveshell import DummyMod |
|
17 | 17 | from IPython.core.interactiveshell import InteractiveShell |
|
18 | 18 | from IPython.terminal.interactiveshell import TerminalInteractiveShell |
|
19 | 19 | from IPython.terminal.ipapp import load_default_config |
|
20 | 20 | |
|
21 | 21 | from traitlets import Bool, CBool, Unicode |
|
22 | 22 | from IPython.utils.io import ask_yes_no |
|
23 | 23 | |
|
24 | 24 | |
|
25 | 25 | # This is an additional magic that is exposed in embedded shells. |
|
26 | 26 | @magics_class |
|
27 | 27 | class EmbeddedMagics(Magics): |
|
28 | 28 | |
|
29 | 29 | @line_magic |
|
30 | 30 | def kill_embedded(self, parameter_s=''): |
|
31 | 31 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
32 | 32 | |
|
33 | 33 | This function (after asking for confirmation) sets an internal flag so |
|
34 | 34 | that an embedded IPython will never activate again. This is useful to |
|
35 | 35 | permanently disable a shell that is being called inside a loop: once |
|
36 | 36 | you've figured out what you needed from it, you may then kill it and |
|
37 | 37 | the program will then continue to run without the interactive shell |
|
38 | 38 | interfering again. |
|
39 | 39 | """ |
|
40 | 40 | |
|
41 | 41 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
42 | 42 | "(y/n)? [y/N] ",'n') |
|
43 | 43 | if kill: |
|
44 | 44 | self.shell.embedded_active = False |
|
45 | 45 | print ("This embedded IPython will not reactivate anymore " |
|
46 | 46 | "once you exit.") |
|
47 | 47 | |
|
48 | 48 | |
|
49 | 49 | class InteractiveShellEmbed(TerminalInteractiveShell): |
|
50 | 50 | |
|
51 | 51 | dummy_mode = Bool(False) |
|
52 | 52 | exit_msg = Unicode('') |
|
53 | 53 | embedded = CBool(True) |
|
54 | 54 | embedded_active = CBool(True) |
|
55 | 55 | # Like the base class display_banner is not configurable, but here it |
|
56 | 56 | # is True by default. |
|
57 | 57 | display_banner = CBool(True) |
|
58 | 58 | exit_msg = Unicode() |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | def __init__(self, **kw): |
|
62 | 62 | |
|
63 | 63 | |
|
64 | 64 | if kw.get('user_global_ns', None) is not None: |
|
65 | 65 | warnings.warn("user_global_ns has been replaced by user_module. The\ |
|
66 | parameter will be ignored.", DeprecationWarning) | |
|
66 | parameter will be ignored, and removed in IPython 5.0", DeprecationWarning) | |
|
67 | 67 | |
|
68 | 68 | super(InteractiveShellEmbed,self).__init__(**kw) |
|
69 | 69 | |
|
70 | 70 | # don't use the ipython crash handler so that user exceptions aren't |
|
71 | 71 | # trapped |
|
72 | 72 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, |
|
73 | 73 | mode=self.xmode, |
|
74 | 74 | call_pdb=self.pdb) |
|
75 | 75 | |
|
76 | 76 | def init_sys_modules(self): |
|
77 | 77 | pass |
|
78 | 78 | |
|
79 | 79 | def init_magics(self): |
|
80 | 80 | super(InteractiveShellEmbed, self).init_magics() |
|
81 | 81 | self.register_magics(EmbeddedMagics) |
|
82 | 82 | |
|
83 | 83 | def __call__(self, header='', local_ns=None, module=None, dummy=None, |
|
84 | 84 | stack_depth=1, global_ns=None, compile_flags=None): |
|
85 | 85 | """Activate the interactive interpreter. |
|
86 | 86 | |
|
87 | 87 | __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start |
|
88 | 88 | the interpreter shell with the given local and global namespaces, and |
|
89 | 89 | optionally print a header string at startup. |
|
90 | 90 | |
|
91 | 91 | The shell can be globally activated/deactivated using the |
|
92 | 92 | dummy_mode attribute. This allows you to turn off a shell used |
|
93 | 93 | for debugging globally. |
|
94 | 94 | |
|
95 | 95 | However, *each* time you call the shell you can override the current |
|
96 | 96 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
97 | 97 | example, if you set dummy mode on with IPShell.dummy_mode = True, you |
|
98 | 98 | can still have a specific call work by making it as IPShell(dummy=False). |
|
99 | 99 | """ |
|
100 | 100 | |
|
101 | 101 | # If the user has turned it off, go away |
|
102 | 102 | if not self.embedded_active: |
|
103 | 103 | return |
|
104 | 104 | |
|
105 | 105 | # Normal exits from interactive mode set this flag, so the shell can't |
|
106 | 106 | # re-enter (it checks this variable at the start of interactive mode). |
|
107 | 107 | self.exit_now = False |
|
108 | 108 | |
|
109 | 109 | # Allow the dummy parameter to override the global __dummy_mode |
|
110 | 110 | if dummy or (dummy != 0 and self.dummy_mode): |
|
111 | 111 | return |
|
112 | 112 | |
|
113 | 113 | if self.has_readline: |
|
114 | 114 | self.set_readline_completer() |
|
115 | 115 | |
|
116 | 116 | # self.banner is auto computed |
|
117 | 117 | if header: |
|
118 | 118 | self.old_banner2 = self.banner2 |
|
119 | 119 | self.banner2 = self.banner2 + '\n' + header + '\n' |
|
120 | 120 | else: |
|
121 | 121 | self.old_banner2 = '' |
|
122 | 122 | |
|
123 | 123 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
124 | 124 | # our call and get the original caller's namespaces. |
|
125 | 125 | self.mainloop(local_ns, module, stack_depth=stack_depth, |
|
126 | 126 | global_ns=global_ns, compile_flags=compile_flags) |
|
127 | 127 | |
|
128 | 128 | self.banner2 = self.old_banner2 |
|
129 | 129 | |
|
130 | 130 | if self.exit_msg is not None: |
|
131 | 131 | print(self.exit_msg) |
|
132 | 132 | |
|
133 | 133 | def mainloop(self, local_ns=None, module=None, stack_depth=0, |
|
134 | 134 | display_banner=None, global_ns=None, compile_flags=None): |
|
135 | 135 | """Embeds IPython into a running python program. |
|
136 | 136 | |
|
137 | 137 | Parameters |
|
138 | 138 | ---------- |
|
139 | 139 | |
|
140 | 140 | local_ns, module |
|
141 | 141 | Working local namespace (a dict) and module (a module or similar |
|
142 | 142 | object). If given as None, they are automatically taken from the scope |
|
143 | 143 | where the shell was called, so that program variables become visible. |
|
144 | 144 | |
|
145 | 145 | stack_depth : int |
|
146 | 146 | How many levels in the stack to go to looking for namespaces (when |
|
147 | 147 | local_ns or module is None). This allows an intermediate caller to |
|
148 | 148 | make sure that this function gets the namespace from the intended |
|
149 | 149 | level in the stack. By default (0) it will get its locals and globals |
|
150 | 150 | from the immediate caller. |
|
151 | 151 | |
|
152 | 152 | compile_flags |
|
153 | 153 | A bit field identifying the __future__ features |
|
154 | 154 | that are enabled, as passed to the builtin :func:`compile` function. |
|
155 | 155 | If given as None, they are automatically taken from the scope where |
|
156 | 156 | the shell was called. |
|
157 | 157 | |
|
158 | 158 | """ |
|
159 | 159 | |
|
160 | 160 | if (global_ns is not None) and (module is None): |
|
161 | warnings.warn("global_ns is deprecated, use module instead.", DeprecationWarning) | |
|
161 | warnings.warn("global_ns is deprecated, and will be removed in IPython 5.0 use module instead.", DeprecationWarning) | |
|
162 | 162 | module = DummyMod() |
|
163 | 163 | module.__dict__ = global_ns |
|
164 | 164 | |
|
165 | 165 | # Get locals and globals from caller |
|
166 | 166 | if ((local_ns is None or module is None or compile_flags is None) |
|
167 | 167 | and self.default_user_namespaces): |
|
168 | 168 | call_frame = sys._getframe(stack_depth).f_back |
|
169 | 169 | |
|
170 | 170 | if local_ns is None: |
|
171 | 171 | local_ns = call_frame.f_locals |
|
172 | 172 | if module is None: |
|
173 | 173 | global_ns = call_frame.f_globals |
|
174 | 174 | module = sys.modules[global_ns['__name__']] |
|
175 | 175 | if compile_flags is None: |
|
176 | 176 | compile_flags = (call_frame.f_code.co_flags & |
|
177 | 177 | compilerop.PyCF_MASK) |
|
178 | 178 | |
|
179 | 179 | # Save original namespace and module so we can restore them after |
|
180 | 180 | # embedding; otherwise the shell doesn't shut down correctly. |
|
181 | 181 | orig_user_module = self.user_module |
|
182 | 182 | orig_user_ns = self.user_ns |
|
183 | 183 | orig_compile_flags = self.compile.flags |
|
184 | 184 | |
|
185 | 185 | # Update namespaces and fire up interpreter |
|
186 | 186 | |
|
187 | 187 | # The global one is easy, we can just throw it in |
|
188 | 188 | if module is not None: |
|
189 | 189 | self.user_module = module |
|
190 | 190 | |
|
191 | 191 | # But the user/local one is tricky: ipython needs it to store internal |
|
192 | 192 | # data, but we also need the locals. We'll throw our hidden variables |
|
193 | 193 | # like _ih and get_ipython() into the local namespace, but delete them |
|
194 | 194 | # later. |
|
195 | 195 | if local_ns is not None: |
|
196 | 196 | reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()} |
|
197 | 197 | self.user_ns = reentrant_local_ns |
|
198 | 198 | self.init_user_ns() |
|
199 | 199 | |
|
200 | 200 | # Compiler flags |
|
201 | 201 | if compile_flags is not None: |
|
202 | 202 | self.compile.flags = compile_flags |
|
203 | 203 | |
|
204 | 204 | # make sure the tab-completer has the correct frame information, so it |
|
205 | 205 | # actually completes using the frame's locals/globals |
|
206 | 206 | self.set_completer_frame() |
|
207 | 207 | |
|
208 | 208 | with self.builtin_trap, self.display_trap: |
|
209 | 209 | self.interact(display_banner=display_banner) |
|
210 | 210 | |
|
211 | 211 | # now, purge out the local namespace of IPython's hidden variables. |
|
212 | 212 | if local_ns is not None: |
|
213 | 213 | local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()}) |
|
214 | 214 | |
|
215 | 215 | |
|
216 | 216 | # Restore original namespace so shell can shut down when we exit. |
|
217 | 217 | self.user_module = orig_user_module |
|
218 | 218 | self.user_ns = orig_user_ns |
|
219 | 219 | self.compile.flags = orig_compile_flags |
|
220 | 220 | |
|
221 | 221 | |
|
222 | 222 | def embed(**kwargs): |
|
223 | 223 | """Call this to embed IPython at the current point in your program. |
|
224 | 224 | |
|
225 | 225 | The first invocation of this will create an :class:`InteractiveShellEmbed` |
|
226 | 226 | instance and then call it. Consecutive calls just call the already |
|
227 | 227 | created instance. |
|
228 | 228 | |
|
229 | 229 | If you don't want the kernel to initialize the namespace |
|
230 | 230 | from the scope of the surrounding function, |
|
231 | 231 | and/or you want to load full IPython configuration, |
|
232 | 232 | you probably want `IPython.start_ipython()` instead. |
|
233 | 233 | |
|
234 | 234 | Here is a simple example:: |
|
235 | 235 | |
|
236 | 236 | from IPython import embed |
|
237 | 237 | a = 10 |
|
238 | 238 | b = 20 |
|
239 | 239 | embed(header='First time') |
|
240 | 240 | c = 30 |
|
241 | 241 | d = 40 |
|
242 | 242 | embed() |
|
243 | 243 | |
|
244 | 244 | Full customization can be done by passing a :class:`Config` in as the |
|
245 | 245 | config argument. |
|
246 | 246 | """ |
|
247 | 247 | config = kwargs.get('config') |
|
248 | 248 | header = kwargs.pop('header', u'') |
|
249 | 249 | compile_flags = kwargs.pop('compile_flags', None) |
|
250 | 250 | if config is None: |
|
251 | 251 | config = load_default_config() |
|
252 | 252 | config.InteractiveShellEmbed = config.TerminalInteractiveShell |
|
253 | 253 | kwargs['config'] = config |
|
254 | 254 | #save ps1/ps2 if defined |
|
255 | 255 | ps1 = None |
|
256 | 256 | ps2 = None |
|
257 | 257 | try: |
|
258 | 258 | ps1 = sys.ps1 |
|
259 | 259 | ps2 = sys.ps2 |
|
260 | 260 | except AttributeError: |
|
261 | 261 | pass |
|
262 | 262 | #save previous instance |
|
263 | 263 | saved_shell_instance = InteractiveShell._instance |
|
264 | 264 | if saved_shell_instance is not None: |
|
265 | 265 | cls = type(saved_shell_instance) |
|
266 | 266 | cls.clear_instance() |
|
267 | 267 | shell = InteractiveShellEmbed.instance(**kwargs) |
|
268 | 268 | shell(header=header, stack_depth=2, compile_flags=compile_flags) |
|
269 | 269 | InteractiveShellEmbed.clear_instance() |
|
270 | 270 | #restore previous instance |
|
271 | 271 | if saved_shell_instance is not None: |
|
272 | 272 | cls = type(saved_shell_instance) |
|
273 | 273 | cls.clear_instance() |
|
274 | 274 | for subclass in cls._walk_mro(): |
|
275 | 275 | subclass._instance = saved_shell_instance |
|
276 | 276 | if ps1 is not None: |
|
277 | 277 | sys.ps1 = ps1 |
|
278 | 278 | sys.ps2 = ps2 |
@@ -1,369 +1,369 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | The :class:`~IPython.core.application.Application` object for the command |
|
5 | 5 | line :command:`ipython` program. |
|
6 | 6 | """ |
|
7 | 7 | |
|
8 | 8 | # Copyright (c) IPython Development Team. |
|
9 | 9 | # Distributed under the terms of the Modified BSD License. |
|
10 | 10 | |
|
11 | 11 | from __future__ import absolute_import |
|
12 | 12 | from __future__ import print_function |
|
13 | 13 | |
|
14 | 14 | import logging |
|
15 | 15 | import os |
|
16 | 16 | import sys |
|
17 | 17 | |
|
18 | 18 | from traitlets.config.loader import Config |
|
19 | 19 | from traitlets.config.application import boolean_flag, catch_config_error, Application |
|
20 | 20 | from IPython.core import release |
|
21 | 21 | from IPython.core import usage |
|
22 | 22 | from IPython.core.completer import IPCompleter |
|
23 | 23 | from IPython.core.crashhandler import CrashHandler |
|
24 | 24 | from IPython.core.formatters import PlainTextFormatter |
|
25 | 25 | from IPython.core.history import HistoryManager |
|
26 | 26 | from IPython.core.prompts import PromptManager |
|
27 | 27 | from IPython.core.application import ( |
|
28 | 28 | ProfileDir, BaseIPythonApplication, base_flags, base_aliases |
|
29 | 29 | ) |
|
30 | 30 | from IPython.core.magics import ScriptMagics |
|
31 | 31 | from IPython.core.shellapp import ( |
|
32 | 32 | InteractiveShellApp, shell_flags, shell_aliases |
|
33 | 33 | ) |
|
34 | 34 | from IPython.extensions.storemagic import StoreMagics |
|
35 | 35 | from IPython.terminal.interactiveshell import TerminalInteractiveShell |
|
36 | 36 | from IPython.utils import warn |
|
37 | 37 | from IPython.paths import get_ipython_dir |
|
38 | 38 | from traitlets import ( |
|
39 | 39 | Bool, List, Dict, |
|
40 | 40 | ) |
|
41 | 41 | |
|
42 | 42 | #----------------------------------------------------------------------------- |
|
43 | 43 | # Globals, utilities and helpers |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | |
|
46 | 46 | _examples = """ |
|
47 | 47 | ipython --matplotlib # enable matplotlib integration |
|
48 | 48 | ipython --matplotlib=qt # enable matplotlib integration with qt4 backend |
|
49 | 49 | |
|
50 | 50 | ipython --log-level=DEBUG # set logging to DEBUG |
|
51 | 51 | ipython --profile=foo # start with profile foo |
|
52 | 52 | |
|
53 | 53 | ipython profile create foo # create profile foo w/ default config files |
|
54 | 54 | ipython help profile # show the help for the profile subcmd |
|
55 | 55 | |
|
56 | 56 | ipython locate # print the path to the IPython directory |
|
57 | 57 | ipython locate profile foo # print the path to the directory for profile `foo` |
|
58 | 58 | """ |
|
59 | 59 | |
|
60 | 60 | #----------------------------------------------------------------------------- |
|
61 | 61 | # Crash handler for this application |
|
62 | 62 | #----------------------------------------------------------------------------- |
|
63 | 63 | |
|
64 | 64 | class IPAppCrashHandler(CrashHandler): |
|
65 | 65 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" |
|
66 | 66 | |
|
67 | 67 | def __init__(self, app): |
|
68 | 68 | contact_name = release.author |
|
69 | 69 | contact_email = release.author_email |
|
70 | 70 | bug_tracker = 'https://github.com/ipython/ipython/issues' |
|
71 | 71 | super(IPAppCrashHandler,self).__init__( |
|
72 | 72 | app, contact_name, contact_email, bug_tracker |
|
73 | 73 | ) |
|
74 | 74 | |
|
75 | 75 | def make_report(self,traceback): |
|
76 | 76 | """Return a string containing a crash report.""" |
|
77 | 77 | |
|
78 | 78 | sec_sep = self.section_sep |
|
79 | 79 | # Start with parent report |
|
80 | 80 | report = [super(IPAppCrashHandler, self).make_report(traceback)] |
|
81 | 81 | # Add interactive-specific info we may have |
|
82 | 82 | rpt_add = report.append |
|
83 | 83 | try: |
|
84 | 84 | rpt_add(sec_sep+"History of session input:") |
|
85 | 85 | for line in self.app.shell.user_ns['_ih']: |
|
86 | 86 | rpt_add(line) |
|
87 | 87 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
88 | 88 | rpt_add(self.app.shell._last_input_line+'\n') |
|
89 | 89 | except: |
|
90 | 90 | pass |
|
91 | 91 | |
|
92 | 92 | return ''.join(report) |
|
93 | 93 | |
|
94 | 94 | #----------------------------------------------------------------------------- |
|
95 | 95 | # Aliases and Flags |
|
96 | 96 | #----------------------------------------------------------------------------- |
|
97 | 97 | flags = dict(base_flags) |
|
98 | 98 | flags.update(shell_flags) |
|
99 | 99 | frontend_flags = {} |
|
100 | 100 | addflag = lambda *args: frontend_flags.update(boolean_flag(*args)) |
|
101 | 101 | addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax', |
|
102 | 102 | 'Turn on auto editing of files with syntax errors.', |
|
103 | 103 | 'Turn off auto editing of files with syntax errors.' |
|
104 | 104 | ) |
|
105 | 105 | addflag('banner', 'TerminalIPythonApp.display_banner', |
|
106 | 106 | "Display a banner upon starting IPython.", |
|
107 | 107 | "Don't display a banner upon starting IPython." |
|
108 | 108 | ) |
|
109 | 109 | addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit', |
|
110 | 110 | """Set to confirm when you try to exit IPython with an EOF (Control-D |
|
111 | 111 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
112 | 112 | you can force a direct exit without any confirmation.""", |
|
113 | 113 | "Don't prompt the user when exiting." |
|
114 | 114 | ) |
|
115 | 115 | addflag('term-title', 'TerminalInteractiveShell.term_title', |
|
116 | 116 | "Enable auto setting the terminal title.", |
|
117 | 117 | "Disable auto setting the terminal title." |
|
118 | 118 | ) |
|
119 | 119 | classic_config = Config() |
|
120 | 120 | classic_config.InteractiveShell.cache_size = 0 |
|
121 | 121 | classic_config.PlainTextFormatter.pprint = False |
|
122 | 122 | classic_config.PromptManager.in_template = '>>> ' |
|
123 | 123 | classic_config.PromptManager.in2_template = '... ' |
|
124 | 124 | classic_config.PromptManager.out_template = '' |
|
125 | 125 | classic_config.InteractiveShell.separate_in = '' |
|
126 | 126 | classic_config.InteractiveShell.separate_out = '' |
|
127 | 127 | classic_config.InteractiveShell.separate_out2 = '' |
|
128 | 128 | classic_config.InteractiveShell.colors = 'NoColor' |
|
129 | 129 | classic_config.InteractiveShell.xmode = 'Plain' |
|
130 | 130 | |
|
131 | 131 | frontend_flags['classic']=( |
|
132 | 132 | classic_config, |
|
133 | 133 | "Gives IPython a similar feel to the classic Python prompt." |
|
134 | 134 | ) |
|
135 | 135 | # # log doesn't make so much sense this way anymore |
|
136 | 136 | # paa('--log','-l', |
|
137 | 137 | # action='store_true', dest='InteractiveShell.logstart', |
|
138 | 138 | # help="Start logging to the default log file (./ipython_log.py).") |
|
139 | 139 | # |
|
140 | 140 | # # quick is harder to implement |
|
141 | 141 | frontend_flags['quick']=( |
|
142 | 142 | {'TerminalIPythonApp' : {'quick' : True}}, |
|
143 | 143 | "Enable quick startup with no config files." |
|
144 | 144 | ) |
|
145 | 145 | |
|
146 | 146 | frontend_flags['i'] = ( |
|
147 | 147 | {'TerminalIPythonApp' : {'force_interact' : True}}, |
|
148 | 148 | """If running code from the command line, become interactive afterwards. |
|
149 | 149 | It is often useful to follow this with `--` to treat remaining flags as |
|
150 | 150 | script arguments. |
|
151 | 151 | """ |
|
152 | 152 | ) |
|
153 | 153 | flags.update(frontend_flags) |
|
154 | 154 | |
|
155 | 155 | aliases = dict(base_aliases) |
|
156 | 156 | aliases.update(shell_aliases) |
|
157 | 157 | |
|
158 | 158 | #----------------------------------------------------------------------------- |
|
159 | 159 | # Main classes and functions |
|
160 | 160 | #----------------------------------------------------------------------------- |
|
161 | 161 | |
|
162 | 162 | |
|
163 | 163 | class LocateIPythonApp(BaseIPythonApplication): |
|
164 | 164 | description = """print the path to the IPython dir""" |
|
165 | 165 | subcommands = Dict(dict( |
|
166 | 166 | profile=('IPython.core.profileapp.ProfileLocate', |
|
167 | 167 | "print the path to an IPython profile directory", |
|
168 | 168 | ), |
|
169 | 169 | )) |
|
170 | 170 | def start(self): |
|
171 | 171 | if self.subapp is not None: |
|
172 | 172 | return self.subapp.start() |
|
173 | 173 | else: |
|
174 | 174 | print(self.ipython_dir) |
|
175 | 175 | |
|
176 | 176 | |
|
177 | 177 | class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): |
|
178 | 178 | name = u'ipython' |
|
179 | 179 | description = usage.cl_usage |
|
180 | 180 | crash_handler_class = IPAppCrashHandler |
|
181 | 181 | examples = _examples |
|
182 | 182 | |
|
183 | 183 | flags = Dict(flags) |
|
184 | 184 | aliases = Dict(aliases) |
|
185 | 185 | classes = List() |
|
186 | 186 | def _classes_default(self): |
|
187 | 187 | """This has to be in a method, for TerminalIPythonApp to be available.""" |
|
188 | 188 | return [ |
|
189 | 189 | InteractiveShellApp, # ShellApp comes before TerminalApp, because |
|
190 | 190 | self.__class__, # it will also affect subclasses (e.g. QtConsole) |
|
191 | 191 | TerminalInteractiveShell, |
|
192 | 192 | PromptManager, |
|
193 | 193 | HistoryManager, |
|
194 | 194 | ProfileDir, |
|
195 | 195 | PlainTextFormatter, |
|
196 | 196 | IPCompleter, |
|
197 | 197 | ScriptMagics, |
|
198 | 198 | StoreMagics, |
|
199 | 199 | ] |
|
200 | 200 | |
|
201 | 201 | deprecated_subcommands = dict( |
|
202 | 202 | qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp', |
|
203 | """DEPRECATD: Launch the Jupyter Qt Console.""" | |
|
203 | """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter Qt Console.""" | |
|
204 | 204 | ), |
|
205 | 205 | notebook=('notebook.notebookapp.NotebookApp', |
|
206 | """DEPRECATED: Launch the Jupyter HTML Notebook Server.""" | |
|
206 | """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter HTML Notebook Server.""" | |
|
207 | 207 | ), |
|
208 | 208 | console=('jupyter_console.app.ZMQTerminalIPythonApp', |
|
209 | """DEPRECATED: Launch the Jupyter terminal-based Console.""" | |
|
209 | """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter terminal-based Console.""" | |
|
210 | 210 | ), |
|
211 | 211 | nbconvert=('nbconvert.nbconvertapp.NbConvertApp', |
|
212 | "DEPRECATED: Convert notebooks to/from other formats." | |
|
212 | "DEPRECATED, Will be removed in IPython 6.0 : Convert notebooks to/from other formats." | |
|
213 | 213 | ), |
|
214 | 214 | trust=('nbformat.sign.TrustNotebookApp', |
|
215 | "DEPRECATED: Sign notebooks to trust their potentially unsafe contents at load." | |
|
215 | "DEPRECATED, Will be removed in IPython 6.0 : Sign notebooks to trust their potentially unsafe contents at load." | |
|
216 | 216 | ), |
|
217 | 217 | kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp', |
|
218 | "DEPRECATED: Manage Jupyter kernel specifications." | |
|
218 | "DEPRECATED, Will be removed in IPython 6.0 : Manage Jupyter kernel specifications." | |
|
219 | 219 | ), |
|
220 | 220 | ) |
|
221 | 221 | subcommands = dict( |
|
222 | 222 | profile = ("IPython.core.profileapp.ProfileApp", |
|
223 | 223 | "Create and manage IPython profiles." |
|
224 | 224 | ), |
|
225 | 225 | kernel = ("ipykernel.kernelapp.IPKernelApp", |
|
226 | 226 | "Start a kernel without an attached frontend." |
|
227 | 227 | ), |
|
228 | 228 | locate=('IPython.terminal.ipapp.LocateIPythonApp', |
|
229 | 229 | LocateIPythonApp.description |
|
230 | 230 | ), |
|
231 | 231 | history=('IPython.core.historyapp.HistoryApp', |
|
232 | 232 | "Manage the IPython history database." |
|
233 | 233 | ), |
|
234 | 234 | ) |
|
235 | 235 | deprecated_subcommands['install-nbextension'] = ( |
|
236 | 236 | "notebook.nbextensions.InstallNBExtensionApp", |
|
237 | "DEPRECATED: Install Jupyter notebook extension files" | |
|
237 | "DEPRECATED, Will be removed in IPython 6.0 : Install Jupyter notebook extension files" | |
|
238 | 238 | ) |
|
239 | 239 | subcommands.update(deprecated_subcommands) |
|
240 | 240 | |
|
241 | 241 | # *do* autocreate requested profile, but don't create the config file. |
|
242 | 242 | auto_create=Bool(True) |
|
243 | 243 | # configurables |
|
244 | 244 | quick = Bool(False, config=True, |
|
245 | 245 | help="""Start IPython quickly by skipping the loading of config files.""" |
|
246 | 246 | ) |
|
247 | 247 | def _quick_changed(self, name, old, new): |
|
248 | 248 | if new: |
|
249 | 249 | self.load_config_file = lambda *a, **kw: None |
|
250 | 250 | |
|
251 | 251 | display_banner = Bool(True, config=True, |
|
252 | 252 | help="Whether to display a banner upon starting IPython." |
|
253 | 253 | ) |
|
254 | 254 | |
|
255 | 255 | # if there is code of files to run from the cmd line, don't interact |
|
256 | 256 | # unless the --i flag (App.force_interact) is true. |
|
257 | 257 | force_interact = Bool(False, config=True, |
|
258 | 258 | help="""If a command or file is given via the command-line, |
|
259 | 259 | e.g. 'ipython foo.py', start an interactive shell after executing the |
|
260 | 260 | file or command.""" |
|
261 | 261 | ) |
|
262 | 262 | def _force_interact_changed(self, name, old, new): |
|
263 | 263 | if new: |
|
264 | 264 | self.interact = True |
|
265 | 265 | |
|
266 | 266 | def _file_to_run_changed(self, name, old, new): |
|
267 | 267 | if new: |
|
268 | 268 | self.something_to_run = True |
|
269 | 269 | if new and not self.force_interact: |
|
270 | 270 | self.interact = False |
|
271 | 271 | _code_to_run_changed = _file_to_run_changed |
|
272 | 272 | _module_to_run_changed = _file_to_run_changed |
|
273 | 273 | |
|
274 | 274 | # internal, not-configurable |
|
275 | 275 | interact=Bool(True) |
|
276 | 276 | something_to_run=Bool(False) |
|
277 | 277 | |
|
278 | 278 | def parse_command_line(self, argv=None): |
|
279 | 279 | """override to allow old '-pylab' flag with deprecation warning""" |
|
280 | 280 | |
|
281 | 281 | argv = sys.argv[1:] if argv is None else argv |
|
282 | 282 | |
|
283 | 283 | if '-pylab' in argv: |
|
284 | 284 | # deprecated `-pylab` given, |
|
285 | 285 | # warn and transform into current syntax |
|
286 | 286 | argv = argv[:] # copy, don't clobber |
|
287 | 287 | idx = argv.index('-pylab') |
|
288 | 288 | warn.warn("`-pylab` flag has been deprecated.\n" |
|
289 | 289 | " Use `--matplotlib <backend>` and import pylab manually.") |
|
290 | 290 | argv[idx] = '--pylab' |
|
291 | 291 | |
|
292 | 292 | return super(TerminalIPythonApp, self).parse_command_line(argv) |
|
293 | 293 | |
|
294 | 294 | @catch_config_error |
|
295 | 295 | def initialize(self, argv=None): |
|
296 | 296 | """Do actions after construct, but before starting the app.""" |
|
297 | 297 | super(TerminalIPythonApp, self).initialize(argv) |
|
298 | 298 | if self.subapp is not None: |
|
299 | 299 | # don't bother initializing further, starting subapp |
|
300 | 300 | return |
|
301 | 301 | # print self.extra_args |
|
302 | 302 | if self.extra_args and not self.something_to_run: |
|
303 | 303 | self.file_to_run = self.extra_args[0] |
|
304 | 304 | self.init_path() |
|
305 | 305 | # create the shell |
|
306 | 306 | self.init_shell() |
|
307 | 307 | # and draw the banner |
|
308 | 308 | self.init_banner() |
|
309 | 309 | # Now a variety of things that happen after the banner is printed. |
|
310 | 310 | self.init_gui_pylab() |
|
311 | 311 | self.init_extensions() |
|
312 | 312 | self.init_code() |
|
313 | 313 | |
|
314 | 314 | def init_shell(self): |
|
315 | 315 | """initialize the InteractiveShell instance""" |
|
316 | 316 | # Create an InteractiveShell instance. |
|
317 | 317 | # shell.display_banner should always be False for the terminal |
|
318 | 318 | # based app, because we call shell.show_banner() by hand below |
|
319 | 319 | # so the banner shows *before* all extension loading stuff. |
|
320 | 320 | self.shell = TerminalInteractiveShell.instance(parent=self, |
|
321 | 321 | display_banner=False, profile_dir=self.profile_dir, |
|
322 | 322 | ipython_dir=self.ipython_dir, user_ns=self.user_ns) |
|
323 | 323 | self.shell.configurables.append(self) |
|
324 | 324 | |
|
325 | 325 | def init_banner(self): |
|
326 | 326 | """optionally display the banner""" |
|
327 | 327 | if self.display_banner and self.interact: |
|
328 | 328 | self.shell.show_banner() |
|
329 | 329 | # Make sure there is a space below the banner. |
|
330 | 330 | if self.log_level <= logging.INFO: print() |
|
331 | 331 | |
|
332 | 332 | def _pylab_changed(self, name, old, new): |
|
333 | 333 | """Replace --pylab='inline' with --pylab='auto'""" |
|
334 | 334 | if new == 'inline': |
|
335 | 335 | warn.warn("'inline' not available as pylab backend, " |
|
336 | 336 | "using 'auto' instead.") |
|
337 | 337 | self.pylab = 'auto' |
|
338 | 338 | |
|
339 | 339 | def start(self): |
|
340 | 340 | if self.subapp is not None: |
|
341 | 341 | return self.subapp.start() |
|
342 | 342 | # perform any prexec steps: |
|
343 | 343 | if self.interact: |
|
344 | 344 | self.log.debug("Starting IPython's mainloop...") |
|
345 | 345 | self.shell.mainloop() |
|
346 | 346 | else: |
|
347 | 347 | self.log.debug("IPython not interactive...") |
|
348 | 348 | |
|
349 | 349 | def load_default_config(ipython_dir=None): |
|
350 | 350 | """Load the default config file from the default ipython_dir. |
|
351 | 351 | |
|
352 | 352 | This is useful for embedded shells. |
|
353 | 353 | """ |
|
354 | 354 | if ipython_dir is None: |
|
355 | 355 | ipython_dir = get_ipython_dir() |
|
356 | 356 | |
|
357 | 357 | profile_dir = os.path.join(ipython_dir, 'profile_default') |
|
358 | 358 | |
|
359 | 359 | config = Config() |
|
360 | 360 | for cf in Application._load_config_files("ipython_config", path=profile_dir): |
|
361 | 361 | config.update(cf) |
|
362 | 362 | |
|
363 | 363 | return config |
|
364 | 364 | |
|
365 | 365 | launch_new_instance = TerminalIPythonApp.launch_instance |
|
366 | 366 | |
|
367 | 367 | |
|
368 | 368 | if __name__ == '__main__': |
|
369 | 369 | launch_new_instance() |
@@ -1,379 +1,379 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Decorators for labeling test objects. |
|
3 | 3 | |
|
4 | 4 | Decorators that merely return a modified version of the original function |
|
5 | 5 | object are straightforward. Decorators that return a new function object need |
|
6 | 6 | to use nose.tools.make_decorator(original_function)(decorator) in returning the |
|
7 | 7 | decorator, in order to preserve metadata such as function name, setup and |
|
8 | 8 | teardown functions and so on - see nose.tools for more information. |
|
9 | 9 | |
|
10 | 10 | This module provides a set of useful decorators meant to be ready to use in |
|
11 | 11 | your own tests. See the bottom of the file for the ready-made ones, and if you |
|
12 | 12 | find yourself writing a new one that may be of generic use, add it here. |
|
13 | 13 | |
|
14 | 14 | Included decorators: |
|
15 | 15 | |
|
16 | 16 | |
|
17 | 17 | Lightweight testing that remains unittest-compatible. |
|
18 | 18 | |
|
19 | 19 | - An @as_unittest decorator can be used to tag any normal parameter-less |
|
20 | 20 | function as a unittest TestCase. Then, both nose and normal unittest will |
|
21 | 21 | recognize it as such. This will make it easier to migrate away from Nose if |
|
22 | 22 | we ever need/want to while maintaining very lightweight tests. |
|
23 | 23 | |
|
24 | 24 | NOTE: This file contains IPython-specific decorators. Using the machinery in |
|
25 | 25 | IPython.external.decorators, we import either numpy.testing.decorators if numpy is |
|
26 | 26 | available, OR use equivalent code in IPython.external._decorators, which |
|
27 | 27 | we've copied verbatim from numpy. |
|
28 | 28 | |
|
29 | 29 | """ |
|
30 | 30 | |
|
31 | 31 | # Copyright (c) IPython Development Team. |
|
32 | 32 | # Distributed under the terms of the Modified BSD License. |
|
33 | 33 | |
|
34 | 34 | import sys |
|
35 | 35 | import os |
|
36 | 36 | import tempfile |
|
37 | 37 | import unittest |
|
38 | 38 | import warnings |
|
39 | 39 | |
|
40 | 40 | from decorator import decorator |
|
41 | 41 | |
|
42 | 42 | # Expose the unittest-driven decorators |
|
43 | 43 | from .ipunittest import ipdoctest, ipdocstring |
|
44 | 44 | |
|
45 | 45 | # Grab the numpy-specific decorators which we keep in a file that we |
|
46 | 46 | # occasionally update from upstream: decorators.py is a copy of |
|
47 | 47 | # numpy.testing.decorators, we expose all of it here. |
|
48 | 48 | from IPython.external.decorators import * |
|
49 | 49 | |
|
50 | 50 | # For onlyif_cmd_exists decorator |
|
51 | 51 | from IPython.utils.py3compat import string_types, which, PY2, PY3 |
|
52 | 52 | |
|
53 | 53 | #----------------------------------------------------------------------------- |
|
54 | 54 | # Classes and functions |
|
55 | 55 | #----------------------------------------------------------------------------- |
|
56 | 56 | |
|
57 | 57 | # Simple example of the basic idea |
|
58 | 58 | def as_unittest(func): |
|
59 | 59 | """Decorator to make a simple function into a normal test via unittest.""" |
|
60 | 60 | class Tester(unittest.TestCase): |
|
61 | 61 | def test(self): |
|
62 | 62 | func() |
|
63 | 63 | |
|
64 | 64 | Tester.__name__ = func.__name__ |
|
65 | 65 | |
|
66 | 66 | return Tester |
|
67 | 67 | |
|
68 | 68 | # Utility functions |
|
69 | 69 | |
|
70 | 70 | def apply_wrapper(wrapper,func): |
|
71 | 71 | """Apply a wrapper to a function for decoration. |
|
72 | 72 | |
|
73 | 73 | This mixes Michele Simionato's decorator tool with nose's make_decorator, |
|
74 | 74 | to apply a wrapper in a decorator so that all nose attributes, as well as |
|
75 | 75 | function signature and other properties, survive the decoration cleanly. |
|
76 | 76 | This will ensure that wrapped functions can still be well introspected via |
|
77 | 77 | IPython, for example. |
|
78 | 78 | """ |
|
79 |
warnings.warn("The function `apply_wrapper` is deprecated and might be removed in |
|
|
79 | warnings.warn("The function `apply_wrapper` is deprecated and might be removed in IPython 5.0", DeprecationWarning) | |
|
80 | 80 | |
|
81 | 81 | import nose.tools |
|
82 | 82 | |
|
83 | 83 | return decorator(wrapper,nose.tools.make_decorator(func)(wrapper)) |
|
84 | 84 | |
|
85 | 85 | |
|
86 | 86 | def make_label_dec(label,ds=None): |
|
87 | 87 | """Factory function to create a decorator that applies one or more labels. |
|
88 | 88 | |
|
89 | 89 | Parameters |
|
90 | 90 | ---------- |
|
91 | 91 | label : string or sequence |
|
92 | 92 | One or more labels that will be applied by the decorator to the functions |
|
93 | 93 | it decorates. Labels are attributes of the decorated function with their |
|
94 | 94 | value set to True. |
|
95 | 95 | |
|
96 | 96 | ds : string |
|
97 | 97 | An optional docstring for the resulting decorator. If not given, a |
|
98 | 98 | default docstring is auto-generated. |
|
99 | 99 | |
|
100 | 100 | Returns |
|
101 | 101 | ------- |
|
102 | 102 | A decorator. |
|
103 | 103 | |
|
104 | 104 | Examples |
|
105 | 105 | -------- |
|
106 | 106 | |
|
107 | 107 | A simple labeling decorator: |
|
108 | 108 | |
|
109 | 109 | >>> slow = make_label_dec('slow') |
|
110 | 110 | >>> slow.__doc__ |
|
111 | 111 | "Labels a test as 'slow'." |
|
112 | 112 | |
|
113 | 113 | And one that uses multiple labels and a custom docstring: |
|
114 | 114 | |
|
115 | 115 | >>> rare = make_label_dec(['slow','hard'], |
|
116 | 116 | ... "Mix labels 'slow' and 'hard' for rare tests.") |
|
117 | 117 | >>> rare.__doc__ |
|
118 | 118 | "Mix labels 'slow' and 'hard' for rare tests." |
|
119 | 119 | |
|
120 | 120 | Now, let's test using this one: |
|
121 | 121 | >>> @rare |
|
122 | 122 | ... def f(): pass |
|
123 | 123 | ... |
|
124 | 124 | >>> |
|
125 | 125 | >>> f.slow |
|
126 | 126 | True |
|
127 | 127 | >>> f.hard |
|
128 | 128 | True |
|
129 | 129 | """ |
|
130 | 130 | |
|
131 |
warnings.warn("The function `make_label_dec` is deprecated and might be removed in |
|
|
131 | warnings.warn("The function `make_label_dec` is deprecated and might be removed in IPython 5.0", DeprecationWarning) | |
|
132 | 132 | if isinstance(label, string_types): |
|
133 | 133 | labels = [label] |
|
134 | 134 | else: |
|
135 | 135 | labels = label |
|
136 | 136 | |
|
137 | 137 | # Validate that the given label(s) are OK for use in setattr() by doing a |
|
138 | 138 | # dry run on a dummy function. |
|
139 | 139 | tmp = lambda : None |
|
140 | 140 | for label in labels: |
|
141 | 141 | setattr(tmp,label,True) |
|
142 | 142 | |
|
143 | 143 | # This is the actual decorator we'll return |
|
144 | 144 | def decor(f): |
|
145 | 145 | for label in labels: |
|
146 | 146 | setattr(f,label,True) |
|
147 | 147 | return f |
|
148 | 148 | |
|
149 | 149 | # Apply the user's docstring, or autogenerate a basic one |
|
150 | 150 | if ds is None: |
|
151 | 151 | ds = "Labels a test as %r." % label |
|
152 | 152 | decor.__doc__ = ds |
|
153 | 153 | |
|
154 | 154 | return decor |
|
155 | 155 | |
|
156 | 156 | |
|
157 | 157 | # Inspired by numpy's skipif, but uses the full apply_wrapper utility to |
|
158 | 158 | # preserve function metadata better and allows the skip condition to be a |
|
159 | 159 | # callable. |
|
160 | 160 | def skipif(skip_condition, msg=None): |
|
161 | 161 | ''' Make function raise SkipTest exception if skip_condition is true |
|
162 | 162 | |
|
163 | 163 | Parameters |
|
164 | 164 | ---------- |
|
165 | 165 | |
|
166 | 166 | skip_condition : bool or callable |
|
167 | 167 | Flag to determine whether to skip test. If the condition is a |
|
168 | 168 | callable, it is used at runtime to dynamically make the decision. This |
|
169 | 169 | is useful for tests that may require costly imports, to delay the cost |
|
170 | 170 | until the test suite is actually executed. |
|
171 | 171 | msg : string |
|
172 | 172 | Message to give on raising a SkipTest exception. |
|
173 | 173 | |
|
174 | 174 | Returns |
|
175 | 175 | ------- |
|
176 | 176 | decorator : function |
|
177 | 177 | Decorator, which, when applied to a function, causes SkipTest |
|
178 | 178 | to be raised when the skip_condition was True, and the function |
|
179 | 179 | to be called normally otherwise. |
|
180 | 180 | |
|
181 | 181 | Notes |
|
182 | 182 | ----- |
|
183 | 183 | You will see from the code that we had to further decorate the |
|
184 | 184 | decorator with the nose.tools.make_decorator function in order to |
|
185 | 185 | transmit function name, and various other metadata. |
|
186 | 186 | ''' |
|
187 | 187 | |
|
188 | 188 | def skip_decorator(f): |
|
189 | 189 | # Local import to avoid a hard nose dependency and only incur the |
|
190 | 190 | # import time overhead at actual test-time. |
|
191 | 191 | import nose |
|
192 | 192 | |
|
193 | 193 | # Allow for both boolean or callable skip conditions. |
|
194 | 194 | if callable(skip_condition): |
|
195 | 195 | skip_val = skip_condition |
|
196 | 196 | else: |
|
197 | 197 | skip_val = lambda : skip_condition |
|
198 | 198 | |
|
199 | 199 | def get_msg(func,msg=None): |
|
200 | 200 | """Skip message with information about function being skipped.""" |
|
201 | 201 | if msg is None: out = 'Test skipped due to test condition.' |
|
202 | 202 | else: out = msg |
|
203 | 203 | return "Skipping test: %s. %s" % (func.__name__,out) |
|
204 | 204 | |
|
205 | 205 | # We need to define *two* skippers because Python doesn't allow both |
|
206 | 206 | # return with value and yield inside the same function. |
|
207 | 207 | def skipper_func(*args, **kwargs): |
|
208 | 208 | """Skipper for normal test functions.""" |
|
209 | 209 | if skip_val(): |
|
210 | 210 | raise nose.SkipTest(get_msg(f,msg)) |
|
211 | 211 | else: |
|
212 | 212 | return f(*args, **kwargs) |
|
213 | 213 | |
|
214 | 214 | def skipper_gen(*args, **kwargs): |
|
215 | 215 | """Skipper for test generators.""" |
|
216 | 216 | if skip_val(): |
|
217 | 217 | raise nose.SkipTest(get_msg(f,msg)) |
|
218 | 218 | else: |
|
219 | 219 | for x in f(*args, **kwargs): |
|
220 | 220 | yield x |
|
221 | 221 | |
|
222 | 222 | # Choose the right skipper to use when building the actual generator. |
|
223 | 223 | if nose.util.isgenerator(f): |
|
224 | 224 | skipper = skipper_gen |
|
225 | 225 | else: |
|
226 | 226 | skipper = skipper_func |
|
227 | 227 | |
|
228 | 228 | return nose.tools.make_decorator(f)(skipper) |
|
229 | 229 | |
|
230 | 230 | return skip_decorator |
|
231 | 231 | |
|
232 | 232 | # A version with the condition set to true, common case just to attach a message |
|
233 | 233 | # to a skip decorator |
|
234 | 234 | def skip(msg=None): |
|
235 | 235 | """Decorator factory - mark a test function for skipping from test suite. |
|
236 | 236 | |
|
237 | 237 | Parameters |
|
238 | 238 | ---------- |
|
239 | 239 | msg : string |
|
240 | 240 | Optional message to be added. |
|
241 | 241 | |
|
242 | 242 | Returns |
|
243 | 243 | ------- |
|
244 | 244 | decorator : function |
|
245 | 245 | Decorator, which, when applied to a function, causes SkipTest |
|
246 | 246 | to be raised, with the optional message added. |
|
247 | 247 | """ |
|
248 | 248 | |
|
249 | 249 | return skipif(True,msg) |
|
250 | 250 | |
|
251 | 251 | |
|
252 | 252 | def onlyif(condition, msg): |
|
253 | 253 | """The reverse from skipif, see skipif for details.""" |
|
254 | 254 | |
|
255 | 255 | if callable(condition): |
|
256 | 256 | skip_condition = lambda : not condition() |
|
257 | 257 | else: |
|
258 | 258 | skip_condition = lambda : not condition |
|
259 | 259 | |
|
260 | 260 | return skipif(skip_condition, msg) |
|
261 | 261 | |
|
262 | 262 | #----------------------------------------------------------------------------- |
|
263 | 263 | # Utility functions for decorators |
|
264 | 264 | def module_not_available(module): |
|
265 | 265 | """Can module be imported? Returns true if module does NOT import. |
|
266 | 266 | |
|
267 | 267 | This is used to make a decorator to skip tests that require module to be |
|
268 | 268 | available, but delay the 'import numpy' to test execution time. |
|
269 | 269 | """ |
|
270 | 270 | try: |
|
271 | 271 | mod = __import__(module) |
|
272 | 272 | mod_not_avail = False |
|
273 | 273 | except ImportError: |
|
274 | 274 | mod_not_avail = True |
|
275 | 275 | |
|
276 | 276 | return mod_not_avail |
|
277 | 277 | |
|
278 | 278 | |
|
279 | 279 | def decorated_dummy(dec, name): |
|
280 | 280 | """Return a dummy function decorated with dec, with the given name. |
|
281 | 281 | |
|
282 | 282 | Examples |
|
283 | 283 | -------- |
|
284 | 284 | import IPython.testing.decorators as dec |
|
285 | 285 | setup = dec.decorated_dummy(dec.skip_if_no_x11, __name__) |
|
286 | 286 | """ |
|
287 |
warnings.warn("The function `make_label_dec` is deprecated and might be removed in |
|
|
287 | warnings.warn("The function `make_label_dec` is deprecated and might be removed in IPython 5.0", DeprecationWarning) | |
|
288 | 288 | dummy = lambda: None |
|
289 | 289 | dummy.__name__ = name |
|
290 | 290 | return dec(dummy) |
|
291 | 291 | |
|
292 | 292 | #----------------------------------------------------------------------------- |
|
293 | 293 | # Decorators for public use |
|
294 | 294 | |
|
295 | 295 | # Decorators to skip certain tests on specific platforms. |
|
296 | 296 | skip_win32 = skipif(sys.platform == 'win32', |
|
297 | 297 | "This test does not run under Windows") |
|
298 | 298 | skip_linux = skipif(sys.platform.startswith('linux'), |
|
299 | 299 | "This test does not run under Linux") |
|
300 | 300 | skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OS X") |
|
301 | 301 | |
|
302 | 302 | |
|
303 | 303 | # Decorators to skip tests if not on specific platforms. |
|
304 | 304 | skip_if_not_win32 = skipif(sys.platform != 'win32', |
|
305 | 305 | "This test only runs under Windows") |
|
306 | 306 | skip_if_not_linux = skipif(not sys.platform.startswith('linux'), |
|
307 | 307 | "This test only runs under Linux") |
|
308 | 308 | skip_if_not_osx = skipif(sys.platform != 'darwin', |
|
309 | 309 | "This test only runs under OSX") |
|
310 | 310 | |
|
311 | 311 | |
|
312 | 312 | _x11_skip_cond = (sys.platform not in ('darwin', 'win32') and |
|
313 | 313 | os.environ.get('DISPLAY', '') == '') |
|
314 | 314 | _x11_skip_msg = "Skipped under *nix when X11/XOrg not available" |
|
315 | 315 | |
|
316 | 316 | skip_if_no_x11 = skipif(_x11_skip_cond, _x11_skip_msg) |
|
317 | 317 | |
|
318 | 318 | # not a decorator itself, returns a dummy function to be used as setup |
|
319 | 319 | def skip_file_no_x11(name): |
|
320 |
warnings.warn("The function `skip_file_no_x11` is deprecated and might be removed in |
|
|
320 | warnings.warn("The function `skip_file_no_x11` is deprecated and might be removed in IPython 5.0", DeprecationWarning) | |
|
321 | 321 | return decorated_dummy(skip_if_no_x11, name) if _x11_skip_cond else None |
|
322 | 322 | |
|
323 | 323 | # Other skip decorators |
|
324 | 324 | |
|
325 | 325 | # generic skip without module |
|
326 | 326 | skip_without = lambda mod: skipif(module_not_available(mod), "This test requires %s" % mod) |
|
327 | 327 | |
|
328 | 328 | skipif_not_numpy = skip_without('numpy') |
|
329 | 329 | |
|
330 | 330 | skipif_not_matplotlib = skip_without('matplotlib') |
|
331 | 331 | |
|
332 | 332 | skipif_not_sympy = skip_without('sympy') |
|
333 | 333 | |
|
334 | 334 | skip_known_failure = knownfailureif(True,'This test is known to fail') |
|
335 | 335 | |
|
336 | 336 | known_failure_py3 = knownfailureif(sys.version_info[0] >= 3, |
|
337 | 337 | 'This test is known to fail on Python 3.') |
|
338 | 338 | |
|
339 | 339 | py2_only = skipif(PY3, "This test only runs on Python 2.") |
|
340 | 340 | py3_only = skipif(PY2, "This test only runs on Python 3.") |
|
341 | 341 | |
|
342 | 342 | # A null 'decorator', useful to make more readable code that needs to pick |
|
343 | 343 | # between different decorators based on OS or other conditions |
|
344 | 344 | null_deco = lambda f: f |
|
345 | 345 | |
|
346 | 346 | # Some tests only run where we can use unicode paths. Note that we can't just |
|
347 | 347 | # check os.path.supports_unicode_filenames, which is always False on Linux. |
|
348 | 348 | try: |
|
349 | 349 | f = tempfile.NamedTemporaryFile(prefix=u"tmpβ¬") |
|
350 | 350 | except UnicodeEncodeError: |
|
351 | 351 | unicode_paths = False |
|
352 | 352 | else: |
|
353 | 353 | unicode_paths = True |
|
354 | 354 | f.close() |
|
355 | 355 | |
|
356 | 356 | onlyif_unicode_paths = onlyif(unicode_paths, ("This test is only applicable " |
|
357 | 357 | "where we can use unicode in filenames.")) |
|
358 | 358 | |
|
359 | 359 | |
|
360 | 360 | def onlyif_cmds_exist(*commands): |
|
361 | 361 | """ |
|
362 | 362 | Decorator to skip test when at least one of `commands` is not found. |
|
363 | 363 | """ |
|
364 | 364 | for cmd in commands: |
|
365 | 365 | if not which(cmd): |
|
366 | 366 | return skip("This test runs only if command '{0}' " |
|
367 | 367 | "is installed".format(cmd)) |
|
368 | 368 | return null_deco |
|
369 | 369 | |
|
370 | 370 | def onlyif_any_cmd_exists(*commands): |
|
371 | 371 | """ |
|
372 | 372 | Decorator to skip test unless at least one of `commands` is found. |
|
373 | 373 | """ |
|
374 |
warnings.warn("The function `onlyif_any_cmd_exists` is deprecated and might be removed in |
|
|
374 | warnings.warn("The function `onlyif_any_cmd_exists` is deprecated and might be removed in IPython 5.0", DeprecationWarning) | |
|
375 | 375 | for cmd in commands: |
|
376 | 376 | if which(cmd): |
|
377 | 377 | return null_deco |
|
378 | 378 | return skip("This test runs only if one of the commands {0} " |
|
379 | 379 | "is installed".format(commands)) |
@@ -1,457 +1,441 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """IPython Test Suite Runner. |
|
3 | 3 | |
|
4 | 4 | This module provides a main entry point to a user script to test IPython |
|
5 | 5 | itself from the command line. There are two ways of running this script: |
|
6 | 6 | |
|
7 | 7 | 1. With the syntax `iptest all`. This runs our entire test suite by |
|
8 | 8 | calling this script (with different arguments) recursively. This |
|
9 | 9 | causes modules and package to be tested in different processes, using nose |
|
10 | 10 | or trial where appropriate. |
|
11 | 11 | 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form |
|
12 | 12 | the script simply calls nose, but with special command line flags and |
|
13 | 13 | plugins loaded. |
|
14 | 14 | |
|
15 | 15 | """ |
|
16 | 16 | |
|
17 | 17 | # Copyright (c) IPython Development Team. |
|
18 | 18 | # Distributed under the terms of the Modified BSD License. |
|
19 | 19 | |
|
20 | 20 | from __future__ import print_function |
|
21 | 21 | |
|
22 | 22 | import glob |
|
23 | 23 | from io import BytesIO |
|
24 | 24 | import os |
|
25 | 25 | import os.path as path |
|
26 | 26 | import sys |
|
27 | 27 | from threading import Thread, Lock, Event |
|
28 | 28 | import warnings |
|
29 | 29 | |
|
30 | 30 | import nose.plugins.builtin |
|
31 | 31 | from nose.plugins.xunit import Xunit |
|
32 | 32 | from nose import SkipTest |
|
33 | 33 | from nose.core import TestProgram |
|
34 | 34 | from nose.plugins import Plugin |
|
35 | 35 | from nose.util import safe_str |
|
36 | 36 | |
|
37 | 37 | from IPython import version_info |
|
38 | 38 | from IPython.utils.py3compat import bytes_to_str |
|
39 | 39 | from IPython.utils.importstring import import_item |
|
40 | 40 | from IPython.testing.plugin.ipdoctest import IPythonDoctest |
|
41 | 41 | from IPython.external.decorators import KnownFailure, knownfailureif |
|
42 | 42 | |
|
43 | 43 | pjoin = path.join |
|
44 | 44 | |
|
45 | #----------------------------------------------------------------------------- | |
|
46 | # Warnings control | |
|
47 | #----------------------------------------------------------------------------- | |
|
48 | ||
|
49 | # Twisted generates annoying warnings with Python 2.6, as will do other code | |
|
50 | # that imports 'sets' as of today | |
|
51 | warnings.filterwarnings('ignore', 'the sets module is deprecated', | |
|
52 | DeprecationWarning ) | |
|
53 | ||
|
54 | # This one also comes from Twisted | |
|
55 | warnings.filterwarnings('ignore', 'the sha module is deprecated', | |
|
56 | DeprecationWarning) | |
|
57 | ||
|
58 | # Wx on Fedora11 spits these out | |
|
59 | warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch', | |
|
60 | UserWarning) | |
|
61 | 45 | |
|
62 | 46 | # Enable printing all warnings raise by IPython's modules |
|
63 | 47 | warnings.filterwarnings('default', message='.*', category=Warning, module='IPy.*') |
|
64 | 48 | |
|
65 | 49 | |
|
66 | 50 | if version_info < (4,2): |
|
67 | 51 | # ignore some warnings from traitlets until 6.0 |
|
68 | 52 | warnings.filterwarnings('ignore', message='.*on_trait_change is deprecated: use observe instead.*') |
|
69 | 53 | warnings.filterwarnings('ignore', message='.*was set from the constructor.*', category=Warning, module='IPython.*') |
|
70 | 54 | else : |
|
71 | 55 | warnings.warn('iptest has been filtering out for Traitlets warnings messages, for 2 major versions (since 4.x), please consider updating to use new API') |
|
72 | 56 | |
|
73 | 57 | if version_info < (6,): |
|
74 | 58 | # nose.tools renames all things from `camelCase` to `snake_case` which raise an |
|
75 | 59 | # warning with the runner they also import from standard import library. (as of Dec 2015) |
|
76 | 60 | # Ignore, let's revisit that in a couple of years for IPython 6. |
|
77 | 61 | warnings.filterwarnings('ignore', message='.*Please use assertEqual instead', category=Warning, module='IPython.*') |
|
78 | 62 | |
|
79 | 63 | |
|
80 | 64 | # ------------------------------------------------------------------------------ |
|
81 | 65 | # Monkeypatch Xunit to count known failures as skipped. |
|
82 | 66 | # ------------------------------------------------------------------------------ |
|
83 | 67 | def monkeypatch_xunit(): |
|
84 | 68 | try: |
|
85 | 69 | knownfailureif(True)(lambda: None)() |
|
86 | 70 | except Exception as e: |
|
87 | 71 | KnownFailureTest = type(e) |
|
88 | 72 | |
|
89 | 73 | def addError(self, test, err, capt=None): |
|
90 | 74 | if issubclass(err[0], KnownFailureTest): |
|
91 | 75 | err = (SkipTest,) + err[1:] |
|
92 | 76 | return self.orig_addError(test, err, capt) |
|
93 | 77 | |
|
94 | 78 | Xunit.orig_addError = Xunit.addError |
|
95 | 79 | Xunit.addError = addError |
|
96 | 80 | |
|
97 | 81 | #----------------------------------------------------------------------------- |
|
98 | 82 | # Check which dependencies are installed and greater than minimum version. |
|
99 | 83 | #----------------------------------------------------------------------------- |
|
100 | 84 | def extract_version(mod): |
|
101 | 85 | return mod.__version__ |
|
102 | 86 | |
|
103 | 87 | def test_for(item, min_version=None, callback=extract_version): |
|
104 | 88 | """Test to see if item is importable, and optionally check against a minimum |
|
105 | 89 | version. |
|
106 | 90 | |
|
107 | 91 | If min_version is given, the default behavior is to check against the |
|
108 | 92 | `__version__` attribute of the item, but specifying `callback` allows you to |
|
109 | 93 | extract the value you are interested in. e.g:: |
|
110 | 94 | |
|
111 | 95 | In [1]: import sys |
|
112 | 96 | |
|
113 | 97 | In [2]: from IPython.testing.iptest import test_for |
|
114 | 98 | |
|
115 | 99 | In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info) |
|
116 | 100 | Out[3]: True |
|
117 | 101 | |
|
118 | 102 | """ |
|
119 | 103 | try: |
|
120 | 104 | check = import_item(item) |
|
121 | 105 | except (ImportError, RuntimeError): |
|
122 | 106 | # GTK reports Runtime error if it can't be initialized even if it's |
|
123 | 107 | # importable. |
|
124 | 108 | return False |
|
125 | 109 | else: |
|
126 | 110 | if min_version: |
|
127 | 111 | if callback: |
|
128 | 112 | # extra processing step to get version to compare |
|
129 | 113 | check = callback(check) |
|
130 | 114 | |
|
131 | 115 | return check >= min_version |
|
132 | 116 | else: |
|
133 | 117 | return True |
|
134 | 118 | |
|
135 | 119 | # Global dict where we can store information on what we have and what we don't |
|
136 | 120 | # have available at test run time |
|
137 | 121 | have = {'matplotlib': test_for('matplotlib'), |
|
138 | 122 | 'pygments': test_for('pygments'), |
|
139 | 123 | 'sqlite3': test_for('sqlite3')} |
|
140 | 124 | |
|
141 | 125 | #----------------------------------------------------------------------------- |
|
142 | 126 | # Test suite definitions |
|
143 | 127 | #----------------------------------------------------------------------------- |
|
144 | 128 | |
|
145 | 129 | test_group_names = ['core', |
|
146 | 130 | 'extensions', 'lib', 'terminal', 'testing', 'utils', |
|
147 | 131 | ] |
|
148 | 132 | |
|
149 | 133 | class TestSection(object): |
|
150 | 134 | def __init__(self, name, includes): |
|
151 | 135 | self.name = name |
|
152 | 136 | self.includes = includes |
|
153 | 137 | self.excludes = [] |
|
154 | 138 | self.dependencies = [] |
|
155 | 139 | self.enabled = True |
|
156 | 140 | |
|
157 | 141 | def exclude(self, module): |
|
158 | 142 | if not module.startswith('IPython'): |
|
159 | 143 | module = self.includes[0] + "." + module |
|
160 | 144 | self.excludes.append(module.replace('.', os.sep)) |
|
161 | 145 | |
|
162 | 146 | def requires(self, *packages): |
|
163 | 147 | self.dependencies.extend(packages) |
|
164 | 148 | |
|
165 | 149 | @property |
|
166 | 150 | def will_run(self): |
|
167 | 151 | return self.enabled and all(have[p] for p in self.dependencies) |
|
168 | 152 | |
|
169 | 153 | # Name -> (include, exclude, dependencies_met) |
|
170 | 154 | test_sections = {n:TestSection(n, ['IPython.%s' % n]) for n in test_group_names} |
|
171 | 155 | |
|
172 | 156 | |
|
173 | 157 | # Exclusions and dependencies |
|
174 | 158 | # --------------------------- |
|
175 | 159 | |
|
176 | 160 | # core: |
|
177 | 161 | sec = test_sections['core'] |
|
178 | 162 | if not have['sqlite3']: |
|
179 | 163 | sec.exclude('tests.test_history') |
|
180 | 164 | sec.exclude('history') |
|
181 | 165 | if not have['matplotlib']: |
|
182 | 166 | sec.exclude('pylabtools'), |
|
183 | 167 | sec.exclude('tests.test_pylabtools') |
|
184 | 168 | |
|
185 | 169 | # lib: |
|
186 | 170 | sec = test_sections['lib'] |
|
187 | 171 | sec.exclude('kernel') |
|
188 | 172 | if not have['pygments']: |
|
189 | 173 | sec.exclude('tests.test_lexers') |
|
190 | 174 | # We do this unconditionally, so that the test suite doesn't import |
|
191 | 175 | # gtk, changing the default encoding and masking some unicode bugs. |
|
192 | 176 | sec.exclude('inputhookgtk') |
|
193 | 177 | # We also do this unconditionally, because wx can interfere with Unix signals. |
|
194 | 178 | # There are currently no tests for it anyway. |
|
195 | 179 | sec.exclude('inputhookwx') |
|
196 | 180 | # Testing inputhook will need a lot of thought, to figure out |
|
197 | 181 | # how to have tests that don't lock up with the gui event |
|
198 | 182 | # loops in the picture |
|
199 | 183 | sec.exclude('inputhook') |
|
200 | 184 | |
|
201 | 185 | # testing: |
|
202 | 186 | sec = test_sections['testing'] |
|
203 | 187 | # These have to be skipped on win32 because they use echo, rm, cd, etc. |
|
204 | 188 | # See ticket https://github.com/ipython/ipython/issues/87 |
|
205 | 189 | if sys.platform == 'win32': |
|
206 | 190 | sec.exclude('plugin.test_exampleip') |
|
207 | 191 | sec.exclude('plugin.dtexample') |
|
208 | 192 | |
|
209 | 193 | # don't run jupyter_console tests found via shim |
|
210 | 194 | test_sections['terminal'].exclude('console') |
|
211 | 195 | |
|
212 | 196 | # extensions: |
|
213 | 197 | sec = test_sections['extensions'] |
|
214 | 198 | # This is deprecated in favour of rpy2 |
|
215 | 199 | sec.exclude('rmagic') |
|
216 | 200 | # autoreload does some strange stuff, so move it to its own test section |
|
217 | 201 | sec.exclude('autoreload') |
|
218 | 202 | sec.exclude('tests.test_autoreload') |
|
219 | 203 | test_sections['autoreload'] = TestSection('autoreload', |
|
220 | 204 | ['IPython.extensions.autoreload', 'IPython.extensions.tests.test_autoreload']) |
|
221 | 205 | test_group_names.append('autoreload') |
|
222 | 206 | |
|
223 | 207 | |
|
224 | 208 | #----------------------------------------------------------------------------- |
|
225 | 209 | # Functions and classes |
|
226 | 210 | #----------------------------------------------------------------------------- |
|
227 | 211 | |
|
228 | 212 | def check_exclusions_exist(): |
|
229 | 213 | from IPython.paths import get_ipython_package_dir |
|
230 | 214 | from IPython.utils.warn import warn |
|
231 | 215 | parent = os.path.dirname(get_ipython_package_dir()) |
|
232 | 216 | for sec in test_sections: |
|
233 | 217 | for pattern in sec.exclusions: |
|
234 | 218 | fullpath = pjoin(parent, pattern) |
|
235 | 219 | if not os.path.exists(fullpath) and not glob.glob(fullpath + '.*'): |
|
236 | 220 | warn("Excluding nonexistent file: %r" % pattern) |
|
237 | 221 | |
|
238 | 222 | |
|
239 | 223 | class ExclusionPlugin(Plugin): |
|
240 | 224 | """A nose plugin to effect our exclusions of files and directories. |
|
241 | 225 | """ |
|
242 | 226 | name = 'exclusions' |
|
243 | 227 | score = 3000 # Should come before any other plugins |
|
244 | 228 | |
|
245 | 229 | def __init__(self, exclude_patterns=None): |
|
246 | 230 | """ |
|
247 | 231 | Parameters |
|
248 | 232 | ---------- |
|
249 | 233 | |
|
250 | 234 | exclude_patterns : sequence of strings, optional |
|
251 | 235 | Filenames containing these patterns (as raw strings, not as regular |
|
252 | 236 | expressions) are excluded from the tests. |
|
253 | 237 | """ |
|
254 | 238 | self.exclude_patterns = exclude_patterns or [] |
|
255 | 239 | super(ExclusionPlugin, self).__init__() |
|
256 | 240 | |
|
257 | 241 | def options(self, parser, env=os.environ): |
|
258 | 242 | Plugin.options(self, parser, env) |
|
259 | 243 | |
|
260 | 244 | def configure(self, options, config): |
|
261 | 245 | Plugin.configure(self, options, config) |
|
262 | 246 | # Override nose trying to disable plugin. |
|
263 | 247 | self.enabled = True |
|
264 | 248 | |
|
265 | 249 | def wantFile(self, filename): |
|
266 | 250 | """Return whether the given filename should be scanned for tests. |
|
267 | 251 | """ |
|
268 | 252 | if any(pat in filename for pat in self.exclude_patterns): |
|
269 | 253 | return False |
|
270 | 254 | return None |
|
271 | 255 | |
|
272 | 256 | def wantDirectory(self, directory): |
|
273 | 257 | """Return whether the given directory should be scanned for tests. |
|
274 | 258 | """ |
|
275 | 259 | if any(pat in directory for pat in self.exclude_patterns): |
|
276 | 260 | return False |
|
277 | 261 | return None |
|
278 | 262 | |
|
279 | 263 | |
|
280 | 264 | class StreamCapturer(Thread): |
|
281 | 265 | daemon = True # Don't hang if main thread crashes |
|
282 | 266 | started = False |
|
283 | 267 | def __init__(self, echo=False): |
|
284 | 268 | super(StreamCapturer, self).__init__() |
|
285 | 269 | self.echo = echo |
|
286 | 270 | self.streams = [] |
|
287 | 271 | self.buffer = BytesIO() |
|
288 | 272 | self.readfd, self.writefd = os.pipe() |
|
289 | 273 | self.buffer_lock = Lock() |
|
290 | 274 | self.stop = Event() |
|
291 | 275 | |
|
292 | 276 | def run(self): |
|
293 | 277 | self.started = True |
|
294 | 278 | |
|
295 | 279 | while not self.stop.is_set(): |
|
296 | 280 | chunk = os.read(self.readfd, 1024) |
|
297 | 281 | |
|
298 | 282 | with self.buffer_lock: |
|
299 | 283 | self.buffer.write(chunk) |
|
300 | 284 | if self.echo: |
|
301 | 285 | sys.stdout.write(bytes_to_str(chunk)) |
|
302 | 286 | |
|
303 | 287 | os.close(self.readfd) |
|
304 | 288 | os.close(self.writefd) |
|
305 | 289 | |
|
306 | 290 | def reset_buffer(self): |
|
307 | 291 | with self.buffer_lock: |
|
308 | 292 | self.buffer.truncate(0) |
|
309 | 293 | self.buffer.seek(0) |
|
310 | 294 | |
|
311 | 295 | def get_buffer(self): |
|
312 | 296 | with self.buffer_lock: |
|
313 | 297 | return self.buffer.getvalue() |
|
314 | 298 | |
|
315 | 299 | def ensure_started(self): |
|
316 | 300 | if not self.started: |
|
317 | 301 | self.start() |
|
318 | 302 | |
|
319 | 303 | def halt(self): |
|
320 | 304 | """Safely stop the thread.""" |
|
321 | 305 | if not self.started: |
|
322 | 306 | return |
|
323 | 307 | |
|
324 | 308 | self.stop.set() |
|
325 | 309 | os.write(self.writefd, b'\0') # Ensure we're not locked in a read() |
|
326 | 310 | self.join() |
|
327 | 311 | |
|
328 | 312 | class SubprocessStreamCapturePlugin(Plugin): |
|
329 | 313 | name='subprocstreams' |
|
330 | 314 | def __init__(self): |
|
331 | 315 | Plugin.__init__(self) |
|
332 | 316 | self.stream_capturer = StreamCapturer() |
|
333 | 317 | self.destination = os.environ.get('IPTEST_SUBPROC_STREAMS', 'capture') |
|
334 | 318 | # This is ugly, but distant parts of the test machinery need to be able |
|
335 | 319 | # to redirect streams, so we make the object globally accessible. |
|
336 | 320 | nose.iptest_stdstreams_fileno = self.get_write_fileno |
|
337 | 321 | |
|
338 | 322 | def get_write_fileno(self): |
|
339 | 323 | if self.destination == 'capture': |
|
340 | 324 | self.stream_capturer.ensure_started() |
|
341 | 325 | return self.stream_capturer.writefd |
|
342 | 326 | elif self.destination == 'discard': |
|
343 | 327 | return os.open(os.devnull, os.O_WRONLY) |
|
344 | 328 | else: |
|
345 | 329 | return sys.__stdout__.fileno() |
|
346 | 330 | |
|
347 | 331 | def configure(self, options, config): |
|
348 | 332 | Plugin.configure(self, options, config) |
|
349 | 333 | # Override nose trying to disable plugin. |
|
350 | 334 | if self.destination == 'capture': |
|
351 | 335 | self.enabled = True |
|
352 | 336 | |
|
353 | 337 | def startTest(self, test): |
|
354 | 338 | # Reset log capture |
|
355 | 339 | self.stream_capturer.reset_buffer() |
|
356 | 340 | |
|
357 | 341 | def formatFailure(self, test, err): |
|
358 | 342 | # Show output |
|
359 | 343 | ec, ev, tb = err |
|
360 | 344 | captured = self.stream_capturer.get_buffer().decode('utf-8', 'replace') |
|
361 | 345 | if captured.strip(): |
|
362 | 346 | ev = safe_str(ev) |
|
363 | 347 | out = [ev, '>> begin captured subprocess output <<', |
|
364 | 348 | captured, |
|
365 | 349 | '>> end captured subprocess output <<'] |
|
366 | 350 | return ec, '\n'.join(out), tb |
|
367 | 351 | |
|
368 | 352 | return err |
|
369 | 353 | |
|
370 | 354 | formatError = formatFailure |
|
371 | 355 | |
|
372 | 356 | def finalize(self, result): |
|
373 | 357 | self.stream_capturer.halt() |
|
374 | 358 | |
|
375 | 359 | |
|
376 | 360 | def run_iptest(): |
|
377 | 361 | """Run the IPython test suite using nose. |
|
378 | 362 | |
|
379 | 363 | This function is called when this script is **not** called with the form |
|
380 | 364 | `iptest all`. It simply calls nose with appropriate command line flags |
|
381 | 365 | and accepts all of the standard nose arguments. |
|
382 | 366 | """ |
|
383 | 367 | # Apply our monkeypatch to Xunit |
|
384 | 368 | if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'): |
|
385 | 369 | monkeypatch_xunit() |
|
386 | 370 | |
|
387 | 371 | warnings.filterwarnings('ignore', |
|
388 | 372 | 'This will be removed soon. Use IPython.testing.util instead') |
|
389 | 373 | |
|
390 | 374 | arg1 = sys.argv[1] |
|
391 | 375 | if arg1 in test_sections: |
|
392 | 376 | section = test_sections[arg1] |
|
393 | 377 | sys.argv[1:2] = section.includes |
|
394 | 378 | elif arg1.startswith('IPython.') and arg1[8:] in test_sections: |
|
395 | 379 | section = test_sections[arg1[8:]] |
|
396 | 380 | sys.argv[1:2] = section.includes |
|
397 | 381 | else: |
|
398 | 382 | section = TestSection(arg1, includes=[arg1]) |
|
399 | 383 | |
|
400 | 384 | |
|
401 | 385 | argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks |
|
402 | 386 | # We add --exe because of setuptools' imbecility (it |
|
403 | 387 | # blindly does chmod +x on ALL files). Nose does the |
|
404 | 388 | # right thing and it tries to avoid executables, |
|
405 | 389 | # setuptools unfortunately forces our hand here. This |
|
406 | 390 | # has been discussed on the distutils list and the |
|
407 | 391 | # setuptools devs refuse to fix this problem! |
|
408 | 392 | '--exe', |
|
409 | 393 | ] |
|
410 | 394 | if '-a' not in argv and '-A' not in argv: |
|
411 | 395 | argv = argv + ['-a', '!crash'] |
|
412 | 396 | |
|
413 | 397 | if nose.__version__ >= '0.11': |
|
414 | 398 | # I don't fully understand why we need this one, but depending on what |
|
415 | 399 | # directory the test suite is run from, if we don't give it, 0 tests |
|
416 | 400 | # get run. Specifically, if the test suite is run from the source dir |
|
417 | 401 | # with an argument (like 'iptest.py IPython.core', 0 tests are run, |
|
418 | 402 | # even if the same call done in this directory works fine). It appears |
|
419 | 403 | # that if the requested package is in the current dir, nose bails early |
|
420 | 404 | # by default. Since it's otherwise harmless, leave it in by default |
|
421 | 405 | # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it. |
|
422 | 406 | argv.append('--traverse-namespace') |
|
423 | 407 | |
|
424 | 408 | plugins = [ ExclusionPlugin(section.excludes), KnownFailure(), |
|
425 | 409 | SubprocessStreamCapturePlugin() ] |
|
426 | 410 | |
|
427 | 411 | # we still have some vestigial doctests in core |
|
428 | 412 | if (section.name.startswith(('core', 'IPython.core'))): |
|
429 | 413 | plugins.append(IPythonDoctest()) |
|
430 | 414 | argv.extend([ |
|
431 | 415 | '--with-ipdoctest', |
|
432 | 416 | '--ipdoctest-tests', |
|
433 | 417 | '--ipdoctest-extension=txt', |
|
434 | 418 | ]) |
|
435 | 419 | |
|
436 | 420 | |
|
437 | 421 | # Use working directory set by parent process (see iptestcontroller) |
|
438 | 422 | if 'IPTEST_WORKING_DIR' in os.environ: |
|
439 | 423 | os.chdir(os.environ['IPTEST_WORKING_DIR']) |
|
440 | 424 | |
|
441 | 425 | # We need a global ipython running in this process, but the special |
|
442 | 426 | # in-process group spawns its own IPython kernels, so for *that* group we |
|
443 | 427 | # must avoid also opening the global one (otherwise there's a conflict of |
|
444 | 428 | # singletons). Ultimately the solution to this problem is to refactor our |
|
445 | 429 | # assumptions about what needs to be a singleton and what doesn't (app |
|
446 | 430 | # objects should, individual shells shouldn't). But for now, this |
|
447 | 431 | # workaround allows the test suite for the inprocess module to complete. |
|
448 | 432 | if 'kernel.inprocess' not in section.name: |
|
449 | 433 | from IPython.testing import globalipapp |
|
450 | 434 | globalipapp.start_ipython() |
|
451 | 435 | |
|
452 | 436 | # Now nose can run |
|
453 | 437 | TestProgram(argv=argv, addplugins=plugins) |
|
454 | 438 | |
|
455 | 439 | if __name__ == '__main__': |
|
456 | 440 | run_iptest() |
|
457 | 441 |
General Comments 0
You need to be logged in to leave comments.
Login now