##// END OF EJS Templates
Explicits deprecation warnings removal versions....
Matthias Bussonnier -
Show More
@@ -1,114 +1,114 b''
1 """
1 """
2 A context manager for managing things injected into :mod:`__builtin__`.
2 A context manager for managing things injected into :mod:`__builtin__`.
3
3
4 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 * Fernando Perez
7 * Fernando Perez
8 """
8 """
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2010-2011 The IPython Development Team.
10 # Copyright (C) 2010-2011 The IPython Development Team.
11 #
11 #
12 # Distributed under the terms of the BSD License.
12 # Distributed under the terms of the BSD License.
13 #
13 #
14 # Complete license in the file COPYING.txt, distributed with this software.
14 # Complete license in the file COPYING.txt, distributed with this software.
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 from traitlets.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
22
22
23 from IPython.utils.py3compat import builtin_mod, iteritems
23 from IPython.utils.py3compat import builtin_mod, iteritems
24 from traitlets import Instance
24 from traitlets import Instance
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Classes and functions
27 # Classes and functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class __BuiltinUndefined(object): pass
30 class __BuiltinUndefined(object): pass
31 BuiltinUndefined = __BuiltinUndefined()
31 BuiltinUndefined = __BuiltinUndefined()
32
32
33 class __HideBuiltin(object): pass
33 class __HideBuiltin(object): pass
34 HideBuiltin = __HideBuiltin()
34 HideBuiltin = __HideBuiltin()
35
35
36
36
37 class BuiltinTrap(Configurable):
37 class BuiltinTrap(Configurable):
38
38
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
40 allow_none=True)
40 allow_none=True)
41
41
42 def __init__(self, shell=None):
42 def __init__(self, shell=None):
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
44 self._orig_builtins = {}
44 self._orig_builtins = {}
45 # We define this to track if a single BuiltinTrap is nested.
45 # We define this to track if a single BuiltinTrap is nested.
46 # Only turn off the trap when the outermost call to __exit__ is made.
46 # Only turn off the trap when the outermost call to __exit__ is made.
47 self._nested_level = 0
47 self._nested_level = 0
48 self.shell = shell
48 self.shell = shell
49 # builtins we always add - if set to HideBuiltin, they will just
49 # builtins we always add - if set to HideBuiltin, they will just
50 # be removed instead of being replaced by something else
50 # be removed instead of being replaced by something else
51 self.auto_builtins = {'exit': HideBuiltin,
51 self.auto_builtins = {'exit': HideBuiltin,
52 'quit': HideBuiltin,
52 'quit': HideBuiltin,
53 'get_ipython': self.shell.get_ipython,
53 'get_ipython': self.shell.get_ipython,
54 }
54 }
55 # Recursive reload function
55 # Recursive reload function
56 try:
56 try:
57 from IPython.lib import deepreload
57 from IPython.lib import deepreload
58 if self.shell.deep_reload:
58 if self.shell.deep_reload:
59 from warnings import warn
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 self.auto_builtins['reload'] = deepreload._dreload
61 self.auto_builtins['reload'] = deepreload._dreload
62 else:
62 else:
63 self.auto_builtins['dreload']= deepreload._dreload
63 self.auto_builtins['dreload']= deepreload._dreload
64 except ImportError:
64 except ImportError:
65 pass
65 pass
66
66
67 def __enter__(self):
67 def __enter__(self):
68 if self._nested_level == 0:
68 if self._nested_level == 0:
69 self.activate()
69 self.activate()
70 self._nested_level += 1
70 self._nested_level += 1
71 # I return self, so callers can use add_builtin in a with clause.
71 # I return self, so callers can use add_builtin in a with clause.
72 return self
72 return self
73
73
74 def __exit__(self, type, value, traceback):
74 def __exit__(self, type, value, traceback):
75 if self._nested_level == 1:
75 if self._nested_level == 1:
76 self.deactivate()
76 self.deactivate()
77 self._nested_level -= 1
77 self._nested_level -= 1
78 # Returning False will cause exceptions to propagate
78 # Returning False will cause exceptions to propagate
79 return False
79 return False
80
80
81 def add_builtin(self, key, value):
81 def add_builtin(self, key, value):
82 """Add a builtin and save the original."""
82 """Add a builtin and save the original."""
83 bdict = builtin_mod.__dict__
83 bdict = builtin_mod.__dict__
84 orig = bdict.get(key, BuiltinUndefined)
84 orig = bdict.get(key, BuiltinUndefined)
85 if value is HideBuiltin:
85 if value is HideBuiltin:
86 if orig is not BuiltinUndefined: #same as 'key in bdict'
86 if orig is not BuiltinUndefined: #same as 'key in bdict'
87 self._orig_builtins[key] = orig
87 self._orig_builtins[key] = orig
88 del bdict[key]
88 del bdict[key]
89 else:
89 else:
90 self._orig_builtins[key] = orig
90 self._orig_builtins[key] = orig
91 bdict[key] = value
91 bdict[key] = value
92
92
93 def remove_builtin(self, key, orig):
93 def remove_builtin(self, key, orig):
94 """Remove an added builtin and re-set the original."""
94 """Remove an added builtin and re-set the original."""
95 if orig is BuiltinUndefined:
95 if orig is BuiltinUndefined:
96 del builtin_mod.__dict__[key]
96 del builtin_mod.__dict__[key]
97 else:
97 else:
98 builtin_mod.__dict__[key] = orig
98 builtin_mod.__dict__[key] = orig
99
99
100 def activate(self):
100 def activate(self):
101 """Store ipython references in the __builtin__ namespace."""
101 """Store ipython references in the __builtin__ namespace."""
102
102
103 add_builtin = self.add_builtin
103 add_builtin = self.add_builtin
104 for name, func in iteritems(self.auto_builtins):
104 for name, func in iteritems(self.auto_builtins):
105 add_builtin(name, func)
105 add_builtin(name, func)
106
106
107 def deactivate(self):
107 def deactivate(self):
108 """Remove any builtins which might have been added by add_builtins, or
108 """Remove any builtins which might have been added by add_builtins, or
109 restore overwritten ones to their previous values."""
109 restore overwritten ones to their previous values."""
110 remove_builtin = self.remove_builtin
110 remove_builtin = self.remove_builtin
111 for key, val in iteritems(self._orig_builtins):
111 for key, val in iteritems(self._orig_builtins):
112 remove_builtin(key, val)
112 remove_builtin(key, val)
113 self._orig_builtins.clear()
113 self._orig_builtins.clear()
114 self._builtins_added = False
114 self._builtins_added = False
@@ -1,147 +1,147 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Color schemes for exception handling code in IPython.
3 Color schemes for exception handling code in IPython.
4 """
4 """
5
5
6 import warnings
6 import warnings
7
7
8 #*****************************************************************************
8 #*****************************************************************************
9 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
9 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #*****************************************************************************
13 #*****************************************************************************
14
14
15 from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
15 from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
16
16
17 def exception_colors():
17 def exception_colors():
18 """Return a color table with fields for exception reporting.
18 """Return a color table with fields for exception reporting.
19
19
20 The table is an instance of ColorSchemeTable with schemes added for
20 The table is an instance of ColorSchemeTable with schemes added for
21 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
21 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
22 in.
22 in.
23
23
24 Examples:
24 Examples:
25
25
26 >>> ec = exception_colors()
26 >>> ec = exception_colors()
27 >>> ec.active_scheme_name
27 >>> ec.active_scheme_name
28 ''
28 ''
29 >>> print(ec.active_colors)
29 >>> print(ec.active_colors)
30 None
30 None
31
31
32 Now we activate a color scheme:
32 Now we activate a color scheme:
33 >>> ec.set_active_scheme('NoColor')
33 >>> ec.set_active_scheme('NoColor')
34 >>> ec.active_scheme_name
34 >>> ec.active_scheme_name
35 'NoColor'
35 'NoColor'
36 >>> sorted(ec.active_colors.keys())
36 >>> sorted(ec.active_colors.keys())
37 ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
37 ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
38 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
38 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
39 'val', 'valEm']
39 'val', 'valEm']
40 """
40 """
41
41
42 ex_colors = ColorSchemeTable()
42 ex_colors = ColorSchemeTable()
43
43
44 # Populate it with color schemes
44 # Populate it with color schemes
45 C = TermColors # shorthand and local lookup
45 C = TermColors # shorthand and local lookup
46 ex_colors.add_scheme(ColorScheme(
46 ex_colors.add_scheme(ColorScheme(
47 'NoColor',
47 'NoColor',
48 # The color to be used for the top line
48 # The color to be used for the top line
49 topline = C.NoColor,
49 topline = C.NoColor,
50
50
51 # The colors to be used in the traceback
51 # The colors to be used in the traceback
52 filename = C.NoColor,
52 filename = C.NoColor,
53 lineno = C.NoColor,
53 lineno = C.NoColor,
54 name = C.NoColor,
54 name = C.NoColor,
55 vName = C.NoColor,
55 vName = C.NoColor,
56 val = C.NoColor,
56 val = C.NoColor,
57 em = C.NoColor,
57 em = C.NoColor,
58
58
59 # Emphasized colors for the last frame of the traceback
59 # Emphasized colors for the last frame of the traceback
60 normalEm = C.NoColor,
60 normalEm = C.NoColor,
61 filenameEm = C.NoColor,
61 filenameEm = C.NoColor,
62 linenoEm = C.NoColor,
62 linenoEm = C.NoColor,
63 nameEm = C.NoColor,
63 nameEm = C.NoColor,
64 valEm = C.NoColor,
64 valEm = C.NoColor,
65
65
66 # Colors for printing the exception
66 # Colors for printing the exception
67 excName = C.NoColor,
67 excName = C.NoColor,
68 line = C.NoColor,
68 line = C.NoColor,
69 caret = C.NoColor,
69 caret = C.NoColor,
70 Normal = C.NoColor
70 Normal = C.NoColor
71 ))
71 ))
72
72
73 # make some schemes as instances so we can copy them for modification easily
73 # make some schemes as instances so we can copy them for modification easily
74 ex_colors.add_scheme(ColorScheme(
74 ex_colors.add_scheme(ColorScheme(
75 'Linux',
75 'Linux',
76 # The color to be used for the top line
76 # The color to be used for the top line
77 topline = C.LightRed,
77 topline = C.LightRed,
78
78
79 # The colors to be used in the traceback
79 # The colors to be used in the traceback
80 filename = C.Green,
80 filename = C.Green,
81 lineno = C.Green,
81 lineno = C.Green,
82 name = C.Purple,
82 name = C.Purple,
83 vName = C.Cyan,
83 vName = C.Cyan,
84 val = C.Green,
84 val = C.Green,
85 em = C.LightCyan,
85 em = C.LightCyan,
86
86
87 # Emphasized colors for the last frame of the traceback
87 # Emphasized colors for the last frame of the traceback
88 normalEm = C.LightCyan,
88 normalEm = C.LightCyan,
89 filenameEm = C.LightGreen,
89 filenameEm = C.LightGreen,
90 linenoEm = C.LightGreen,
90 linenoEm = C.LightGreen,
91 nameEm = C.LightPurple,
91 nameEm = C.LightPurple,
92 valEm = C.LightBlue,
92 valEm = C.LightBlue,
93
93
94 # Colors for printing the exception
94 # Colors for printing the exception
95 excName = C.LightRed,
95 excName = C.LightRed,
96 line = C.Yellow,
96 line = C.Yellow,
97 caret = C.White,
97 caret = C.White,
98 Normal = C.Normal
98 Normal = C.Normal
99 ))
99 ))
100
100
101 # For light backgrounds, swap dark/light colors
101 # For light backgrounds, swap dark/light colors
102 ex_colors.add_scheme(ColorScheme(
102 ex_colors.add_scheme(ColorScheme(
103 'LightBG',
103 'LightBG',
104 # The color to be used for the top line
104 # The color to be used for the top line
105 topline = C.Red,
105 topline = C.Red,
106
106
107 # The colors to be used in the traceback
107 # The colors to be used in the traceback
108 filename = C.LightGreen,
108 filename = C.LightGreen,
109 lineno = C.LightGreen,
109 lineno = C.LightGreen,
110 name = C.LightPurple,
110 name = C.LightPurple,
111 vName = C.Cyan,
111 vName = C.Cyan,
112 val = C.LightGreen,
112 val = C.LightGreen,
113 em = C.Cyan,
113 em = C.Cyan,
114
114
115 # Emphasized colors for the last frame of the traceback
115 # Emphasized colors for the last frame of the traceback
116 normalEm = C.Cyan,
116 normalEm = C.Cyan,
117 filenameEm = C.Green,
117 filenameEm = C.Green,
118 linenoEm = C.Green,
118 linenoEm = C.Green,
119 nameEm = C.Purple,
119 nameEm = C.Purple,
120 valEm = C.Blue,
120 valEm = C.Blue,
121
121
122 # Colors for printing the exception
122 # Colors for printing the exception
123 excName = C.Red,
123 excName = C.Red,
124 #line = C.Brown, # brown often is displayed as yellow
124 #line = C.Brown, # brown often is displayed as yellow
125 line = C.Red,
125 line = C.Red,
126 caret = C.Normal,
126 caret = C.Normal,
127 Normal = C.Normal,
127 Normal = C.Normal,
128 ))
128 ))
129
129
130 return ex_colors
130 return ex_colors
131
131
132 class Deprec(object):
132 class Deprec(object):
133
133
134 def __init__(self, wrapped_obj):
134 def __init__(self, wrapped_obj):
135 self.wrapped=wrapped_obj
135 self.wrapped=wrapped_obj
136
136
137 def __getattr__(self, name):
137 def __getattr__(self, name):
138 val = getattr(self.wrapped, name)
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 # using getattr after warnings break ipydoctest in weird way for 3.5
140 # using getattr after warnings break ipydoctest in weird way for 3.5
141 return val
141 return val
142
142
143 # For backwards compatibility, keep around a single global object. Note that
143 # For backwards compatibility, keep around a single global object. Note that
144 # this should NOT be used, the factory function should be used instead, since
144 # this should NOT be used, the factory function should be used instead, since
145 # these objects are stateful and it's very easy to get strange bugs if any code
145 # these objects are stateful and it's very easy to get strange bugs if any code
146 # modifies the module-level object's state.
146 # modifies the module-level object's state.
147 ExceptionColors = Deprec(exception_colors())
147 ExceptionColors = Deprec(exception_colors())
@@ -1,972 +1,974 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Display formatters.
2 """Display formatters.
3
3
4 Inheritance diagram:
4 Inheritance diagram:
5
5
6 .. inheritance-diagram:: IPython.core.formatters
6 .. inheritance-diagram:: IPython.core.formatters
7 :parts: 3
7 :parts: 3
8 """
8 """
9
9
10 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12
12
13 import abc
13 import abc
14 import inspect
14 import inspect
15 import json
15 import json
16 import sys
16 import sys
17 import traceback
17 import traceback
18 import warnings
18 import warnings
19
19
20 from decorator import decorator
20 from decorator import decorator
21
21
22 from traitlets.config.configurable import Configurable
22 from traitlets.config.configurable import Configurable
23 from IPython.core.getipython import get_ipython
23 from IPython.core.getipython import get_ipython
24 from IPython.utils.sentinel import Sentinel
24 from IPython.utils.sentinel import Sentinel
25 from IPython.lib import pretty
25 from IPython.lib import pretty
26 from traitlets import (
26 from traitlets import (
27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 ForwardDeclaredInstance,
28 ForwardDeclaredInstance,
29 )
29 )
30 from IPython.utils.py3compat import (
30 from IPython.utils.py3compat import (
31 with_metaclass, string_types, unicode_type,
31 with_metaclass, string_types, unicode_type,
32 )
32 )
33
33
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36 # The main DisplayFormatter class
36 # The main DisplayFormatter class
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38
38
39
39
40 def _safe_get_formatter_method(obj, name):
40 def _safe_get_formatter_method(obj, name):
41 """Safely get a formatter method
41 """Safely get a formatter method
42
42
43 - Classes cannot have formatter methods, only instance
43 - Classes cannot have formatter methods, only instance
44 - protect against proxy objects that claim to have everything
44 - protect against proxy objects that claim to have everything
45 """
45 """
46 if inspect.isclass(obj):
46 if inspect.isclass(obj):
47 # repr methods only make sense on instances, not classes
47 # repr methods only make sense on instances, not classes
48 return None
48 return None
49 method = pretty._safe_getattr(obj, name, None)
49 method = pretty._safe_getattr(obj, name, None)
50 if callable(method):
50 if callable(method):
51 # obj claims to have repr method...
51 # obj claims to have repr method...
52 if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)):
52 if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)):
53 # ...but don't trust proxy objects that claim to have everything
53 # ...but don't trust proxy objects that claim to have everything
54 return None
54 return None
55 return method
55 return method
56
56
57
57
58 class DisplayFormatter(Configurable):
58 class DisplayFormatter(Configurable):
59
59
60 # When set to true only the default plain text formatter will be used.
60 # When set to true only the default plain text formatter will be used.
61 plain_text_only = Bool(False, config=True)
61 plain_text_only = Bool(False, config=True)
62 def _plain_text_only_changed(self, name, old, new):
62 def _plain_text_only_changed(self, name, old, new):
63 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
63 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
64
64
65 It will be removed in IPython 5.0
66
65 Use DisplayFormatter.active_types = ['text/plain']
67 Use DisplayFormatter.active_types = ['text/plain']
66 for the same effect.
68 for the same effect.
67 """, DeprecationWarning)
69 """, DeprecationWarning)
68 if new:
70 if new:
69 self.active_types = ['text/plain']
71 self.active_types = ['text/plain']
70 else:
72 else:
71 self.active_types = self.format_types
73 self.active_types = self.format_types
72
74
73 active_types = List(Unicode(), config=True,
75 active_types = List(Unicode(), config=True,
74 help="""List of currently active mime-types to display.
76 help="""List of currently active mime-types to display.
75 You can use this to set a white-list for formats to display.
77 You can use this to set a white-list for formats to display.
76
78
77 Most users will not need to change this value.
79 Most users will not need to change this value.
78 """)
80 """)
79 def _active_types_default(self):
81 def _active_types_default(self):
80 return self.format_types
82 return self.format_types
81
83
82 def _active_types_changed(self, name, old, new):
84 def _active_types_changed(self, name, old, new):
83 for key, formatter in self.formatters.items():
85 for key, formatter in self.formatters.items():
84 if key in new:
86 if key in new:
85 formatter.enabled = True
87 formatter.enabled = True
86 else:
88 else:
87 formatter.enabled = False
89 formatter.enabled = False
88
90
89 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
91 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
90 def _ipython_display_formatter_default(self):
92 def _ipython_display_formatter_default(self):
91 return IPythonDisplayFormatter(parent=self)
93 return IPythonDisplayFormatter(parent=self)
92
94
93 # A dict of formatter whose keys are format types (MIME types) and whose
95 # A dict of formatter whose keys are format types (MIME types) and whose
94 # values are subclasses of BaseFormatter.
96 # values are subclasses of BaseFormatter.
95 formatters = Dict()
97 formatters = Dict()
96 def _formatters_default(self):
98 def _formatters_default(self):
97 """Activate the default formatters."""
99 """Activate the default formatters."""
98 formatter_classes = [
100 formatter_classes = [
99 PlainTextFormatter,
101 PlainTextFormatter,
100 HTMLFormatter,
102 HTMLFormatter,
101 MarkdownFormatter,
103 MarkdownFormatter,
102 SVGFormatter,
104 SVGFormatter,
103 PNGFormatter,
105 PNGFormatter,
104 PDFFormatter,
106 PDFFormatter,
105 JPEGFormatter,
107 JPEGFormatter,
106 LatexFormatter,
108 LatexFormatter,
107 JSONFormatter,
109 JSONFormatter,
108 JavascriptFormatter
110 JavascriptFormatter
109 ]
111 ]
110 d = {}
112 d = {}
111 for cls in formatter_classes:
113 for cls in formatter_classes:
112 f = cls(parent=self)
114 f = cls(parent=self)
113 d[f.format_type] = f
115 d[f.format_type] = f
114 return d
116 return d
115
117
116 def format(self, obj, include=None, exclude=None):
118 def format(self, obj, include=None, exclude=None):
117 """Return a format data dict for an object.
119 """Return a format data dict for an object.
118
120
119 By default all format types will be computed.
121 By default all format types will be computed.
120
122
121 The following MIME types are currently implemented:
123 The following MIME types are currently implemented:
122
124
123 * text/plain
125 * text/plain
124 * text/html
126 * text/html
125 * text/markdown
127 * text/markdown
126 * text/latex
128 * text/latex
127 * application/json
129 * application/json
128 * application/javascript
130 * application/javascript
129 * application/pdf
131 * application/pdf
130 * image/png
132 * image/png
131 * image/jpeg
133 * image/jpeg
132 * image/svg+xml
134 * image/svg+xml
133
135
134 Parameters
136 Parameters
135 ----------
137 ----------
136 obj : object
138 obj : object
137 The Python object whose format data will be computed.
139 The Python object whose format data will be computed.
138 include : list or tuple, optional
140 include : list or tuple, optional
139 A list of format type strings (MIME types) to include in the
141 A list of format type strings (MIME types) to include in the
140 format data dict. If this is set *only* the format types included
142 format data dict. If this is set *only* the format types included
141 in this list will be computed.
143 in this list will be computed.
142 exclude : list or tuple, optional
144 exclude : list or tuple, optional
143 A list of format type string (MIME types) to exclude in the format
145 A list of format type string (MIME types) to exclude in the format
144 data dict. If this is set all format types will be computed,
146 data dict. If this is set all format types will be computed,
145 except for those included in this argument.
147 except for those included in this argument.
146
148
147 Returns
149 Returns
148 -------
150 -------
149 (format_dict, metadata_dict) : tuple of two dicts
151 (format_dict, metadata_dict) : tuple of two dicts
150
152
151 format_dict is a dictionary of key/value pairs, one of each format that was
153 format_dict is a dictionary of key/value pairs, one of each format that was
152 generated for the object. The keys are the format types, which
154 generated for the object. The keys are the format types, which
153 will usually be MIME type strings and the values and JSON'able
155 will usually be MIME type strings and the values and JSON'able
154 data structure containing the raw data for the representation in
156 data structure containing the raw data for the representation in
155 that format.
157 that format.
156
158
157 metadata_dict is a dictionary of metadata about each mime-type output.
159 metadata_dict is a dictionary of metadata about each mime-type output.
158 Its keys will be a strict subset of the keys in format_dict.
160 Its keys will be a strict subset of the keys in format_dict.
159 """
161 """
160 format_dict = {}
162 format_dict = {}
161 md_dict = {}
163 md_dict = {}
162
164
163 if self.ipython_display_formatter(obj):
165 if self.ipython_display_formatter(obj):
164 # object handled itself, don't proceed
166 # object handled itself, don't proceed
165 return {}, {}
167 return {}, {}
166
168
167 for format_type, formatter in self.formatters.items():
169 for format_type, formatter in self.formatters.items():
168 if include and format_type not in include:
170 if include and format_type not in include:
169 continue
171 continue
170 if exclude and format_type in exclude:
172 if exclude and format_type in exclude:
171 continue
173 continue
172
174
173 md = None
175 md = None
174 try:
176 try:
175 data = formatter(obj)
177 data = formatter(obj)
176 except:
178 except:
177 # FIXME: log the exception
179 # FIXME: log the exception
178 raise
180 raise
179
181
180 # formatters can return raw data or (data, metadata)
182 # formatters can return raw data or (data, metadata)
181 if isinstance(data, tuple) and len(data) == 2:
183 if isinstance(data, tuple) and len(data) == 2:
182 data, md = data
184 data, md = data
183
185
184 if data is not None:
186 if data is not None:
185 format_dict[format_type] = data
187 format_dict[format_type] = data
186 if md is not None:
188 if md is not None:
187 md_dict[format_type] = md
189 md_dict[format_type] = md
188
190
189 return format_dict, md_dict
191 return format_dict, md_dict
190
192
191 @property
193 @property
192 def format_types(self):
194 def format_types(self):
193 """Return the format types (MIME types) of the active formatters."""
195 """Return the format types (MIME types) of the active formatters."""
194 return list(self.formatters.keys())
196 return list(self.formatters.keys())
195
197
196
198
197 #-----------------------------------------------------------------------------
199 #-----------------------------------------------------------------------------
198 # Formatters for specific format types (text, html, svg, etc.)
200 # Formatters for specific format types (text, html, svg, etc.)
199 #-----------------------------------------------------------------------------
201 #-----------------------------------------------------------------------------
200
202
201
203
202 def _safe_repr(obj):
204 def _safe_repr(obj):
203 """Try to return a repr of an object
205 """Try to return a repr of an object
204
206
205 always returns a string, at least.
207 always returns a string, at least.
206 """
208 """
207 try:
209 try:
208 return repr(obj)
210 return repr(obj)
209 except Exception as e:
211 except Exception as e:
210 return "un-repr-able object (%r)" % e
212 return "un-repr-able object (%r)" % e
211
213
212
214
213 class FormatterWarning(UserWarning):
215 class FormatterWarning(UserWarning):
214 """Warning class for errors in formatters"""
216 """Warning class for errors in formatters"""
215
217
216 @decorator
218 @decorator
217 def catch_format_error(method, self, *args, **kwargs):
219 def catch_format_error(method, self, *args, **kwargs):
218 """show traceback on failed format call"""
220 """show traceback on failed format call"""
219 try:
221 try:
220 r = method(self, *args, **kwargs)
222 r = method(self, *args, **kwargs)
221 except NotImplementedError:
223 except NotImplementedError:
222 # don't warn on NotImplementedErrors
224 # don't warn on NotImplementedErrors
223 return None
225 return None
224 except Exception:
226 except Exception:
225 exc_info = sys.exc_info()
227 exc_info = sys.exc_info()
226 ip = get_ipython()
228 ip = get_ipython()
227 if ip is not None:
229 if ip is not None:
228 ip.showtraceback(exc_info)
230 ip.showtraceback(exc_info)
229 else:
231 else:
230 traceback.print_exception(*exc_info)
232 traceback.print_exception(*exc_info)
231 return None
233 return None
232 return self._check_return(r, args[0])
234 return self._check_return(r, args[0])
233
235
234
236
235 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
237 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
236 """ Abstract base class for Formatters.
238 """ Abstract base class for Formatters.
237
239
238 A formatter is a callable class that is responsible for computing the
240 A formatter is a callable class that is responsible for computing the
239 raw format data for a particular format type (MIME type). For example,
241 raw format data for a particular format type (MIME type). For example,
240 an HTML formatter would have a format type of `text/html` and would return
242 an HTML formatter would have a format type of `text/html` and would return
241 the HTML representation of the object when called.
243 the HTML representation of the object when called.
242 """
244 """
243
245
244 # The format type of the data returned, usually a MIME type.
246 # The format type of the data returned, usually a MIME type.
245 format_type = 'text/plain'
247 format_type = 'text/plain'
246
248
247 # Is the formatter enabled...
249 # Is the formatter enabled...
248 enabled = True
250 enabled = True
249
251
250 @abc.abstractmethod
252 @abc.abstractmethod
251 def __call__(self, obj):
253 def __call__(self, obj):
252 """Return a JSON'able representation of the object.
254 """Return a JSON'able representation of the object.
253
255
254 If the object cannot be formatted by this formatter,
256 If the object cannot be formatted by this formatter,
255 warn and return None.
257 warn and return None.
256 """
258 """
257 return repr(obj)
259 return repr(obj)
258
260
259
261
260 def _mod_name_key(typ):
262 def _mod_name_key(typ):
261 """Return a (__module__, __name__) tuple for a type.
263 """Return a (__module__, __name__) tuple for a type.
262
264
263 Used as key in Formatter.deferred_printers.
265 Used as key in Formatter.deferred_printers.
264 """
266 """
265 module = getattr(typ, '__module__', None)
267 module = getattr(typ, '__module__', None)
266 name = getattr(typ, '__name__', None)
268 name = getattr(typ, '__name__', None)
267 return (module, name)
269 return (module, name)
268
270
269
271
270 def _get_type(obj):
272 def _get_type(obj):
271 """Return the type of an instance (old and new-style)"""
273 """Return the type of an instance (old and new-style)"""
272 return getattr(obj, '__class__', None) or type(obj)
274 return getattr(obj, '__class__', None) or type(obj)
273
275
274
276
275 _raise_key_error = Sentinel('_raise_key_error', __name__,
277 _raise_key_error = Sentinel('_raise_key_error', __name__,
276 """
278 """
277 Special value to raise a KeyError
279 Special value to raise a KeyError
278
280
279 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
281 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
280 """)
282 """)
281
283
282
284
283 class BaseFormatter(Configurable):
285 class BaseFormatter(Configurable):
284 """A base formatter class that is configurable.
286 """A base formatter class that is configurable.
285
287
286 This formatter should usually be used as the base class of all formatters.
288 This formatter should usually be used as the base class of all formatters.
287 It is a traited :class:`Configurable` class and includes an extensible
289 It is a traited :class:`Configurable` class and includes an extensible
288 API for users to determine how their objects are formatted. The following
290 API for users to determine how their objects are formatted. The following
289 logic is used to find a function to format an given object.
291 logic is used to find a function to format an given object.
290
292
291 1. The object is introspected to see if it has a method with the name
293 1. The object is introspected to see if it has a method with the name
292 :attr:`print_method`. If is does, that object is passed to that method
294 :attr:`print_method`. If is does, that object is passed to that method
293 for formatting.
295 for formatting.
294 2. If no print method is found, three internal dictionaries are consulted
296 2. If no print method is found, three internal dictionaries are consulted
295 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
297 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
296 and :attr:`deferred_printers`.
298 and :attr:`deferred_printers`.
297
299
298 Users should use these dictionaries to register functions that will be
300 Users should use these dictionaries to register functions that will be
299 used to compute the format data for their objects (if those objects don't
301 used to compute the format data for their objects (if those objects don't
300 have the special print methods). The easiest way of using these
302 have the special print methods). The easiest way of using these
301 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
303 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
302 methods.
304 methods.
303
305
304 If no function/callable is found to compute the format data, ``None`` is
306 If no function/callable is found to compute the format data, ``None`` is
305 returned and this format type is not used.
307 returned and this format type is not used.
306 """
308 """
307
309
308 format_type = Unicode('text/plain')
310 format_type = Unicode('text/plain')
309 _return_type = string_types
311 _return_type = string_types
310
312
311 enabled = Bool(True, config=True)
313 enabled = Bool(True, config=True)
312
314
313 print_method = ObjectName('__repr__')
315 print_method = ObjectName('__repr__')
314
316
315 # The singleton printers.
317 # The singleton printers.
316 # Maps the IDs of the builtin singleton objects to the format functions.
318 # Maps the IDs of the builtin singleton objects to the format functions.
317 singleton_printers = Dict(config=True)
319 singleton_printers = Dict(config=True)
318
320
319 # The type-specific printers.
321 # The type-specific printers.
320 # Map type objects to the format functions.
322 # Map type objects to the format functions.
321 type_printers = Dict(config=True)
323 type_printers = Dict(config=True)
322
324
323 # The deferred-import type-specific printers.
325 # The deferred-import type-specific printers.
324 # Map (modulename, classname) pairs to the format functions.
326 # Map (modulename, classname) pairs to the format functions.
325 deferred_printers = Dict(config=True)
327 deferred_printers = Dict(config=True)
326
328
327 @catch_format_error
329 @catch_format_error
328 def __call__(self, obj):
330 def __call__(self, obj):
329 """Compute the format for an object."""
331 """Compute the format for an object."""
330 if self.enabled:
332 if self.enabled:
331 # lookup registered printer
333 # lookup registered printer
332 try:
334 try:
333 printer = self.lookup(obj)
335 printer = self.lookup(obj)
334 except KeyError:
336 except KeyError:
335 pass
337 pass
336 else:
338 else:
337 return printer(obj)
339 return printer(obj)
338 # Finally look for special method names
340 # Finally look for special method names
339 method = _safe_get_formatter_method(obj, self.print_method)
341 method = _safe_get_formatter_method(obj, self.print_method)
340 if method is not None:
342 if method is not None:
341 return method()
343 return method()
342 return None
344 return None
343 else:
345 else:
344 return None
346 return None
345
347
346 def __contains__(self, typ):
348 def __contains__(self, typ):
347 """map in to lookup_by_type"""
349 """map in to lookup_by_type"""
348 try:
350 try:
349 self.lookup_by_type(typ)
351 self.lookup_by_type(typ)
350 except KeyError:
352 except KeyError:
351 return False
353 return False
352 else:
354 else:
353 return True
355 return True
354
356
355 def _check_return(self, r, obj):
357 def _check_return(self, r, obj):
356 """Check that a return value is appropriate
358 """Check that a return value is appropriate
357
359
358 Return the value if so, None otherwise, warning if invalid.
360 Return the value if so, None otherwise, warning if invalid.
359 """
361 """
360 if r is None or isinstance(r, self._return_type) or \
362 if r is None or isinstance(r, self._return_type) or \
361 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
363 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
362 return r
364 return r
363 else:
365 else:
364 warnings.warn(
366 warnings.warn(
365 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
367 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
366 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
368 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
367 FormatterWarning
369 FormatterWarning
368 )
370 )
369
371
370 def lookup(self, obj):
372 def lookup(self, obj):
371 """Look up the formatter for a given instance.
373 """Look up the formatter for a given instance.
372
374
373 Parameters
375 Parameters
374 ----------
376 ----------
375 obj : object instance
377 obj : object instance
376
378
377 Returns
379 Returns
378 -------
380 -------
379 f : callable
381 f : callable
380 The registered formatting callable for the type.
382 The registered formatting callable for the type.
381
383
382 Raises
384 Raises
383 ------
385 ------
384 KeyError if the type has not been registered.
386 KeyError if the type has not been registered.
385 """
387 """
386 # look for singleton first
388 # look for singleton first
387 obj_id = id(obj)
389 obj_id = id(obj)
388 if obj_id in self.singleton_printers:
390 if obj_id in self.singleton_printers:
389 return self.singleton_printers[obj_id]
391 return self.singleton_printers[obj_id]
390 # then lookup by type
392 # then lookup by type
391 return self.lookup_by_type(_get_type(obj))
393 return self.lookup_by_type(_get_type(obj))
392
394
393 def lookup_by_type(self, typ):
395 def lookup_by_type(self, typ):
394 """Look up the registered formatter for a type.
396 """Look up the registered formatter for a type.
395
397
396 Parameters
398 Parameters
397 ----------
399 ----------
398 typ : type or '__module__.__name__' string for a type
400 typ : type or '__module__.__name__' string for a type
399
401
400 Returns
402 Returns
401 -------
403 -------
402 f : callable
404 f : callable
403 The registered formatting callable for the type.
405 The registered formatting callable for the type.
404
406
405 Raises
407 Raises
406 ------
408 ------
407 KeyError if the type has not been registered.
409 KeyError if the type has not been registered.
408 """
410 """
409 if isinstance(typ, string_types):
411 if isinstance(typ, string_types):
410 typ_key = tuple(typ.rsplit('.',1))
412 typ_key = tuple(typ.rsplit('.',1))
411 if typ_key not in self.deferred_printers:
413 if typ_key not in self.deferred_printers:
412 # We may have it cached in the type map. We will have to
414 # We may have it cached in the type map. We will have to
413 # iterate over all of the types to check.
415 # iterate over all of the types to check.
414 for cls in self.type_printers:
416 for cls in self.type_printers:
415 if _mod_name_key(cls) == typ_key:
417 if _mod_name_key(cls) == typ_key:
416 return self.type_printers[cls]
418 return self.type_printers[cls]
417 else:
419 else:
418 return self.deferred_printers[typ_key]
420 return self.deferred_printers[typ_key]
419 else:
421 else:
420 for cls in pretty._get_mro(typ):
422 for cls in pretty._get_mro(typ):
421 if cls in self.type_printers or self._in_deferred_types(cls):
423 if cls in self.type_printers or self._in_deferred_types(cls):
422 return self.type_printers[cls]
424 return self.type_printers[cls]
423
425
424 # If we have reached here, the lookup failed.
426 # If we have reached here, the lookup failed.
425 raise KeyError("No registered printer for {0!r}".format(typ))
427 raise KeyError("No registered printer for {0!r}".format(typ))
426
428
427 def for_type(self, typ, func=None):
429 def for_type(self, typ, func=None):
428 """Add a format function for a given type.
430 """Add a format function for a given type.
429
431
430 Parameters
432 Parameters
431 -----------
433 -----------
432 typ : type or '__module__.__name__' string for a type
434 typ : type or '__module__.__name__' string for a type
433 The class of the object that will be formatted using `func`.
435 The class of the object that will be formatted using `func`.
434 func : callable
436 func : callable
435 A callable for computing the format data.
437 A callable for computing the format data.
436 `func` will be called with the object to be formatted,
438 `func` will be called with the object to be formatted,
437 and will return the raw data in this formatter's format.
439 and will return the raw data in this formatter's format.
438 Subclasses may use a different call signature for the
440 Subclasses may use a different call signature for the
439 `func` argument.
441 `func` argument.
440
442
441 If `func` is None or not specified, there will be no change,
443 If `func` is None or not specified, there will be no change,
442 only returning the current value.
444 only returning the current value.
443
445
444 Returns
446 Returns
445 -------
447 -------
446 oldfunc : callable
448 oldfunc : callable
447 The currently registered callable.
449 The currently registered callable.
448 If you are registering a new formatter,
450 If you are registering a new formatter,
449 this will be the previous value (to enable restoring later).
451 this will be the previous value (to enable restoring later).
450 """
452 """
451 # if string given, interpret as 'pkg.module.class_name'
453 # if string given, interpret as 'pkg.module.class_name'
452 if isinstance(typ, string_types):
454 if isinstance(typ, string_types):
453 type_module, type_name = typ.rsplit('.', 1)
455 type_module, type_name = typ.rsplit('.', 1)
454 return self.for_type_by_name(type_module, type_name, func)
456 return self.for_type_by_name(type_module, type_name, func)
455
457
456 try:
458 try:
457 oldfunc = self.lookup_by_type(typ)
459 oldfunc = self.lookup_by_type(typ)
458 except KeyError:
460 except KeyError:
459 oldfunc = None
461 oldfunc = None
460
462
461 if func is not None:
463 if func is not None:
462 self.type_printers[typ] = func
464 self.type_printers[typ] = func
463
465
464 return oldfunc
466 return oldfunc
465
467
466 def for_type_by_name(self, type_module, type_name, func=None):
468 def for_type_by_name(self, type_module, type_name, func=None):
467 """Add a format function for a type specified by the full dotted
469 """Add a format function for a type specified by the full dotted
468 module and name of the type, rather than the type of the object.
470 module and name of the type, rather than the type of the object.
469
471
470 Parameters
472 Parameters
471 ----------
473 ----------
472 type_module : str
474 type_module : str
473 The full dotted name of the module the type is defined in, like
475 The full dotted name of the module the type is defined in, like
474 ``numpy``.
476 ``numpy``.
475 type_name : str
477 type_name : str
476 The name of the type (the class name), like ``dtype``
478 The name of the type (the class name), like ``dtype``
477 func : callable
479 func : callable
478 A callable for computing the format data.
480 A callable for computing the format data.
479 `func` will be called with the object to be formatted,
481 `func` will be called with the object to be formatted,
480 and will return the raw data in this formatter's format.
482 and will return the raw data in this formatter's format.
481 Subclasses may use a different call signature for the
483 Subclasses may use a different call signature for the
482 `func` argument.
484 `func` argument.
483
485
484 If `func` is None or unspecified, there will be no change,
486 If `func` is None or unspecified, there will be no change,
485 only returning the current value.
487 only returning the current value.
486
488
487 Returns
489 Returns
488 -------
490 -------
489 oldfunc : callable
491 oldfunc : callable
490 The currently registered callable.
492 The currently registered callable.
491 If you are registering a new formatter,
493 If you are registering a new formatter,
492 this will be the previous value (to enable restoring later).
494 this will be the previous value (to enable restoring later).
493 """
495 """
494 key = (type_module, type_name)
496 key = (type_module, type_name)
495
497
496 try:
498 try:
497 oldfunc = self.lookup_by_type("%s.%s" % key)
499 oldfunc = self.lookup_by_type("%s.%s" % key)
498 except KeyError:
500 except KeyError:
499 oldfunc = None
501 oldfunc = None
500
502
501 if func is not None:
503 if func is not None:
502 self.deferred_printers[key] = func
504 self.deferred_printers[key] = func
503 return oldfunc
505 return oldfunc
504
506
505 def pop(self, typ, default=_raise_key_error):
507 def pop(self, typ, default=_raise_key_error):
506 """Pop a formatter for the given type.
508 """Pop a formatter for the given type.
507
509
508 Parameters
510 Parameters
509 ----------
511 ----------
510 typ : type or '__module__.__name__' string for a type
512 typ : type or '__module__.__name__' string for a type
511 default : object
513 default : object
512 value to be returned if no formatter is registered for typ.
514 value to be returned if no formatter is registered for typ.
513
515
514 Returns
516 Returns
515 -------
517 -------
516 obj : object
518 obj : object
517 The last registered object for the type.
519 The last registered object for the type.
518
520
519 Raises
521 Raises
520 ------
522 ------
521 KeyError if the type is not registered and default is not specified.
523 KeyError if the type is not registered and default is not specified.
522 """
524 """
523
525
524 if isinstance(typ, string_types):
526 if isinstance(typ, string_types):
525 typ_key = tuple(typ.rsplit('.',1))
527 typ_key = tuple(typ.rsplit('.',1))
526 if typ_key not in self.deferred_printers:
528 if typ_key not in self.deferred_printers:
527 # We may have it cached in the type map. We will have to
529 # We may have it cached in the type map. We will have to
528 # iterate over all of the types to check.
530 # iterate over all of the types to check.
529 for cls in self.type_printers:
531 for cls in self.type_printers:
530 if _mod_name_key(cls) == typ_key:
532 if _mod_name_key(cls) == typ_key:
531 old = self.type_printers.pop(cls)
533 old = self.type_printers.pop(cls)
532 break
534 break
533 else:
535 else:
534 old = default
536 old = default
535 else:
537 else:
536 old = self.deferred_printers.pop(typ_key)
538 old = self.deferred_printers.pop(typ_key)
537 else:
539 else:
538 if typ in self.type_printers:
540 if typ in self.type_printers:
539 old = self.type_printers.pop(typ)
541 old = self.type_printers.pop(typ)
540 else:
542 else:
541 old = self.deferred_printers.pop(_mod_name_key(typ), default)
543 old = self.deferred_printers.pop(_mod_name_key(typ), default)
542 if old is _raise_key_error:
544 if old is _raise_key_error:
543 raise KeyError("No registered value for {0!r}".format(typ))
545 raise KeyError("No registered value for {0!r}".format(typ))
544 return old
546 return old
545
547
546 def _in_deferred_types(self, cls):
548 def _in_deferred_types(self, cls):
547 """
549 """
548 Check if the given class is specified in the deferred type registry.
550 Check if the given class is specified in the deferred type registry.
549
551
550 Successful matches will be moved to the regular type registry for future use.
552 Successful matches will be moved to the regular type registry for future use.
551 """
553 """
552 mod = getattr(cls, '__module__', None)
554 mod = getattr(cls, '__module__', None)
553 name = getattr(cls, '__name__', None)
555 name = getattr(cls, '__name__', None)
554 key = (mod, name)
556 key = (mod, name)
555 if key in self.deferred_printers:
557 if key in self.deferred_printers:
556 # Move the printer over to the regular registry.
558 # Move the printer over to the regular registry.
557 printer = self.deferred_printers.pop(key)
559 printer = self.deferred_printers.pop(key)
558 self.type_printers[cls] = printer
560 self.type_printers[cls] = printer
559 return True
561 return True
560 return False
562 return False
561
563
562
564
563 class PlainTextFormatter(BaseFormatter):
565 class PlainTextFormatter(BaseFormatter):
564 """The default pretty-printer.
566 """The default pretty-printer.
565
567
566 This uses :mod:`IPython.lib.pretty` to compute the format data of
568 This uses :mod:`IPython.lib.pretty` to compute the format data of
567 the object. If the object cannot be pretty printed, :func:`repr` is used.
569 the object. If the object cannot be pretty printed, :func:`repr` is used.
568 See the documentation of :mod:`IPython.lib.pretty` for details on
570 See the documentation of :mod:`IPython.lib.pretty` for details on
569 how to write pretty printers. Here is a simple example::
571 how to write pretty printers. Here is a simple example::
570
572
571 def dtype_pprinter(obj, p, cycle):
573 def dtype_pprinter(obj, p, cycle):
572 if cycle:
574 if cycle:
573 return p.text('dtype(...)')
575 return p.text('dtype(...)')
574 if hasattr(obj, 'fields'):
576 if hasattr(obj, 'fields'):
575 if obj.fields is None:
577 if obj.fields is None:
576 p.text(repr(obj))
578 p.text(repr(obj))
577 else:
579 else:
578 p.begin_group(7, 'dtype([')
580 p.begin_group(7, 'dtype([')
579 for i, field in enumerate(obj.descr):
581 for i, field in enumerate(obj.descr):
580 if i > 0:
582 if i > 0:
581 p.text(',')
583 p.text(',')
582 p.breakable()
584 p.breakable()
583 p.pretty(field)
585 p.pretty(field)
584 p.end_group(7, '])')
586 p.end_group(7, '])')
585 """
587 """
586
588
587 # The format type of data returned.
589 # The format type of data returned.
588 format_type = Unicode('text/plain')
590 format_type = Unicode('text/plain')
589
591
590 # This subclass ignores this attribute as it always need to return
592 # This subclass ignores this attribute as it always need to return
591 # something.
593 # something.
592 enabled = Bool(True, config=False)
594 enabled = Bool(True, config=False)
593
595
594 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True,
596 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True,
595 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
597 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
596
598
597 Set to 0 to disable truncation.
599 Set to 0 to disable truncation.
598 """
600 """
599 )
601 )
600
602
601 # Look for a _repr_pretty_ methods to use for pretty printing.
603 # Look for a _repr_pretty_ methods to use for pretty printing.
602 print_method = ObjectName('_repr_pretty_')
604 print_method = ObjectName('_repr_pretty_')
603
605
604 # Whether to pretty-print or not.
606 # Whether to pretty-print or not.
605 pprint = Bool(True, config=True)
607 pprint = Bool(True, config=True)
606
608
607 # Whether to be verbose or not.
609 # Whether to be verbose or not.
608 verbose = Bool(False, config=True)
610 verbose = Bool(False, config=True)
609
611
610 # The maximum width.
612 # The maximum width.
611 max_width = Integer(79, config=True)
613 max_width = Integer(79, config=True)
612
614
613 # The newline character.
615 # The newline character.
614 newline = Unicode('\n', config=True)
616 newline = Unicode('\n', config=True)
615
617
616 # format-string for pprinting floats
618 # format-string for pprinting floats
617 float_format = Unicode('%r')
619 float_format = Unicode('%r')
618 # setter for float precision, either int or direct format-string
620 # setter for float precision, either int or direct format-string
619 float_precision = CUnicode('', config=True)
621 float_precision = CUnicode('', config=True)
620
622
621 def _float_precision_changed(self, name, old, new):
623 def _float_precision_changed(self, name, old, new):
622 """float_precision changed, set float_format accordingly.
624 """float_precision changed, set float_format accordingly.
623
625
624 float_precision can be set by int or str.
626 float_precision can be set by int or str.
625 This will set float_format, after interpreting input.
627 This will set float_format, after interpreting input.
626 If numpy has been imported, numpy print precision will also be set.
628 If numpy has been imported, numpy print precision will also be set.
627
629
628 integer `n` sets format to '%.nf', otherwise, format set directly.
630 integer `n` sets format to '%.nf', otherwise, format set directly.
629
631
630 An empty string returns to defaults (repr for float, 8 for numpy).
632 An empty string returns to defaults (repr for float, 8 for numpy).
631
633
632 This parameter can be set via the '%precision' magic.
634 This parameter can be set via the '%precision' magic.
633 """
635 """
634
636
635 if '%' in new:
637 if '%' in new:
636 # got explicit format string
638 # got explicit format string
637 fmt = new
639 fmt = new
638 try:
640 try:
639 fmt%3.14159
641 fmt%3.14159
640 except Exception:
642 except Exception:
641 raise ValueError("Precision must be int or format string, not %r"%new)
643 raise ValueError("Precision must be int or format string, not %r"%new)
642 elif new:
644 elif new:
643 # otherwise, should be an int
645 # otherwise, should be an int
644 try:
646 try:
645 i = int(new)
647 i = int(new)
646 assert i >= 0
648 assert i >= 0
647 except ValueError:
649 except ValueError:
648 raise ValueError("Precision must be int or format string, not %r"%new)
650 raise ValueError("Precision must be int or format string, not %r"%new)
649 except AssertionError:
651 except AssertionError:
650 raise ValueError("int precision must be non-negative, not %r"%i)
652 raise ValueError("int precision must be non-negative, not %r"%i)
651
653
652 fmt = '%%.%if'%i
654 fmt = '%%.%if'%i
653 if 'numpy' in sys.modules:
655 if 'numpy' in sys.modules:
654 # set numpy precision if it has been imported
656 # set numpy precision if it has been imported
655 import numpy
657 import numpy
656 numpy.set_printoptions(precision=i)
658 numpy.set_printoptions(precision=i)
657 else:
659 else:
658 # default back to repr
660 # default back to repr
659 fmt = '%r'
661 fmt = '%r'
660 if 'numpy' in sys.modules:
662 if 'numpy' in sys.modules:
661 import numpy
663 import numpy
662 # numpy default is 8
664 # numpy default is 8
663 numpy.set_printoptions(precision=8)
665 numpy.set_printoptions(precision=8)
664 self.float_format = fmt
666 self.float_format = fmt
665
667
666 # Use the default pretty printers from IPython.lib.pretty.
668 # Use the default pretty printers from IPython.lib.pretty.
667 def _singleton_printers_default(self):
669 def _singleton_printers_default(self):
668 return pretty._singleton_pprinters.copy()
670 return pretty._singleton_pprinters.copy()
669
671
670 def _type_printers_default(self):
672 def _type_printers_default(self):
671 d = pretty._type_pprinters.copy()
673 d = pretty._type_pprinters.copy()
672 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
674 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
673 return d
675 return d
674
676
675 def _deferred_printers_default(self):
677 def _deferred_printers_default(self):
676 return pretty._deferred_type_pprinters.copy()
678 return pretty._deferred_type_pprinters.copy()
677
679
678 #### FormatterABC interface ####
680 #### FormatterABC interface ####
679
681
680 @catch_format_error
682 @catch_format_error
681 def __call__(self, obj):
683 def __call__(self, obj):
682 """Compute the pretty representation of the object."""
684 """Compute the pretty representation of the object."""
683 if not self.pprint:
685 if not self.pprint:
684 return repr(obj)
686 return repr(obj)
685 else:
687 else:
686 # handle str and unicode on Python 2
688 # handle str and unicode on Python 2
687 # io.StringIO only accepts unicode,
689 # io.StringIO only accepts unicode,
688 # cStringIO doesn't handle unicode on py2,
690 # cStringIO doesn't handle unicode on py2,
689 # StringIO allows str, unicode but only ascii str
691 # StringIO allows str, unicode but only ascii str
690 stream = pretty.CUnicodeIO()
692 stream = pretty.CUnicodeIO()
691 printer = pretty.RepresentationPrinter(stream, self.verbose,
693 printer = pretty.RepresentationPrinter(stream, self.verbose,
692 self.max_width, self.newline,
694 self.max_width, self.newline,
693 max_seq_length=self.max_seq_length,
695 max_seq_length=self.max_seq_length,
694 singleton_pprinters=self.singleton_printers,
696 singleton_pprinters=self.singleton_printers,
695 type_pprinters=self.type_printers,
697 type_pprinters=self.type_printers,
696 deferred_pprinters=self.deferred_printers)
698 deferred_pprinters=self.deferred_printers)
697 printer.pretty(obj)
699 printer.pretty(obj)
698 printer.flush()
700 printer.flush()
699 return stream.getvalue()
701 return stream.getvalue()
700
702
701
703
702 class HTMLFormatter(BaseFormatter):
704 class HTMLFormatter(BaseFormatter):
703 """An HTML formatter.
705 """An HTML formatter.
704
706
705 To define the callables that compute the HTML representation of your
707 To define the callables that compute the HTML representation of your
706 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
708 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
707 or :meth:`for_type_by_name` methods to register functions that handle
709 or :meth:`for_type_by_name` methods to register functions that handle
708 this.
710 this.
709
711
710 The return value of this formatter should be a valid HTML snippet that
712 The return value of this formatter should be a valid HTML snippet that
711 could be injected into an existing DOM. It should *not* include the
713 could be injected into an existing DOM. It should *not* include the
712 ```<html>`` or ```<body>`` tags.
714 ```<html>`` or ```<body>`` tags.
713 """
715 """
714 format_type = Unicode('text/html')
716 format_type = Unicode('text/html')
715
717
716 print_method = ObjectName('_repr_html_')
718 print_method = ObjectName('_repr_html_')
717
719
718
720
719 class MarkdownFormatter(BaseFormatter):
721 class MarkdownFormatter(BaseFormatter):
720 """A Markdown formatter.
722 """A Markdown formatter.
721
723
722 To define the callables that compute the Markdown representation of your
724 To define the callables that compute the Markdown representation of your
723 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
725 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
724 or :meth:`for_type_by_name` methods to register functions that handle
726 or :meth:`for_type_by_name` methods to register functions that handle
725 this.
727 this.
726
728
727 The return value of this formatter should be a valid Markdown.
729 The return value of this formatter should be a valid Markdown.
728 """
730 """
729 format_type = Unicode('text/markdown')
731 format_type = Unicode('text/markdown')
730
732
731 print_method = ObjectName('_repr_markdown_')
733 print_method = ObjectName('_repr_markdown_')
732
734
733 class SVGFormatter(BaseFormatter):
735 class SVGFormatter(BaseFormatter):
734 """An SVG formatter.
736 """An SVG formatter.
735
737
736 To define the callables that compute the SVG representation of your
738 To define the callables that compute the SVG representation of your
737 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
739 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
738 or :meth:`for_type_by_name` methods to register functions that handle
740 or :meth:`for_type_by_name` methods to register functions that handle
739 this.
741 this.
740
742
741 The return value of this formatter should be valid SVG enclosed in
743 The return value of this formatter should be valid SVG enclosed in
742 ```<svg>``` tags, that could be injected into an existing DOM. It should
744 ```<svg>``` tags, that could be injected into an existing DOM. It should
743 *not* include the ```<html>`` or ```<body>`` tags.
745 *not* include the ```<html>`` or ```<body>`` tags.
744 """
746 """
745 format_type = Unicode('image/svg+xml')
747 format_type = Unicode('image/svg+xml')
746
748
747 print_method = ObjectName('_repr_svg_')
749 print_method = ObjectName('_repr_svg_')
748
750
749
751
750 class PNGFormatter(BaseFormatter):
752 class PNGFormatter(BaseFormatter):
751 """A PNG formatter.
753 """A PNG formatter.
752
754
753 To define the callables that compute the PNG representation of your
755 To define the callables that compute the PNG representation of your
754 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
756 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
755 or :meth:`for_type_by_name` methods to register functions that handle
757 or :meth:`for_type_by_name` methods to register functions that handle
756 this.
758 this.
757
759
758 The return value of this formatter should be raw PNG data, *not*
760 The return value of this formatter should be raw PNG data, *not*
759 base64 encoded.
761 base64 encoded.
760 """
762 """
761 format_type = Unicode('image/png')
763 format_type = Unicode('image/png')
762
764
763 print_method = ObjectName('_repr_png_')
765 print_method = ObjectName('_repr_png_')
764
766
765 _return_type = (bytes, unicode_type)
767 _return_type = (bytes, unicode_type)
766
768
767
769
768 class JPEGFormatter(BaseFormatter):
770 class JPEGFormatter(BaseFormatter):
769 """A JPEG formatter.
771 """A JPEG formatter.
770
772
771 To define the callables that compute the JPEG representation of your
773 To define the callables that compute the JPEG representation of your
772 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
774 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
773 or :meth:`for_type_by_name` methods to register functions that handle
775 or :meth:`for_type_by_name` methods to register functions that handle
774 this.
776 this.
775
777
776 The return value of this formatter should be raw JPEG data, *not*
778 The return value of this formatter should be raw JPEG data, *not*
777 base64 encoded.
779 base64 encoded.
778 """
780 """
779 format_type = Unicode('image/jpeg')
781 format_type = Unicode('image/jpeg')
780
782
781 print_method = ObjectName('_repr_jpeg_')
783 print_method = ObjectName('_repr_jpeg_')
782
784
783 _return_type = (bytes, unicode_type)
785 _return_type = (bytes, unicode_type)
784
786
785
787
786 class LatexFormatter(BaseFormatter):
788 class LatexFormatter(BaseFormatter):
787 """A LaTeX formatter.
789 """A LaTeX formatter.
788
790
789 To define the callables that compute the LaTeX representation of your
791 To define the callables that compute the LaTeX representation of your
790 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
792 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
791 or :meth:`for_type_by_name` methods to register functions that handle
793 or :meth:`for_type_by_name` methods to register functions that handle
792 this.
794 this.
793
795
794 The return value of this formatter should be a valid LaTeX equation,
796 The return value of this formatter should be a valid LaTeX equation,
795 enclosed in either ```$```, ```$$``` or another LaTeX equation
797 enclosed in either ```$```, ```$$``` or another LaTeX equation
796 environment.
798 environment.
797 """
799 """
798 format_type = Unicode('text/latex')
800 format_type = Unicode('text/latex')
799
801
800 print_method = ObjectName('_repr_latex_')
802 print_method = ObjectName('_repr_latex_')
801
803
802
804
803 class JSONFormatter(BaseFormatter):
805 class JSONFormatter(BaseFormatter):
804 """A JSON string formatter.
806 """A JSON string formatter.
805
807
806 To define the callables that compute the JSONable representation of
808 To define the callables that compute the JSONable representation of
807 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
809 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
808 or :meth:`for_type_by_name` methods to register functions that handle
810 or :meth:`for_type_by_name` methods to register functions that handle
809 this.
811 this.
810
812
811 The return value of this formatter should be a JSONable list or dict.
813 The return value of this formatter should be a JSONable list or dict.
812 JSON scalars (None, number, string) are not allowed, only dict or list containers.
814 JSON scalars (None, number, string) are not allowed, only dict or list containers.
813 """
815 """
814 format_type = Unicode('application/json')
816 format_type = Unicode('application/json')
815 _return_type = (list, dict)
817 _return_type = (list, dict)
816
818
817 print_method = ObjectName('_repr_json_')
819 print_method = ObjectName('_repr_json_')
818
820
819 def _check_return(self, r, obj):
821 def _check_return(self, r, obj):
820 """Check that a return value is appropriate
822 """Check that a return value is appropriate
821
823
822 Return the value if so, None otherwise, warning if invalid.
824 Return the value if so, None otherwise, warning if invalid.
823 """
825 """
824 if r is None:
826 if r is None:
825 return
827 return
826 md = None
828 md = None
827 if isinstance(r, tuple):
829 if isinstance(r, tuple):
828 # unpack data, metadata tuple for type checking on first element
830 # unpack data, metadata tuple for type checking on first element
829 r, md = r
831 r, md = r
830
832
831 # handle deprecated JSON-as-string form from IPython < 3
833 # handle deprecated JSON-as-string form from IPython < 3
832 if isinstance(r, string_types):
834 if isinstance(r, string_types):
833 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
835 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
834 FormatterWarning)
836 FormatterWarning)
835 r = json.loads(r)
837 r = json.loads(r)
836
838
837 if md is not None:
839 if md is not None:
838 # put the tuple back together
840 # put the tuple back together
839 r = (r, md)
841 r = (r, md)
840 return super(JSONFormatter, self)._check_return(r, obj)
842 return super(JSONFormatter, self)._check_return(r, obj)
841
843
842
844
843 class JavascriptFormatter(BaseFormatter):
845 class JavascriptFormatter(BaseFormatter):
844 """A Javascript formatter.
846 """A Javascript formatter.
845
847
846 To define the callables that compute the Javascript representation of
848 To define the callables that compute the Javascript representation of
847 your objects, define a :meth:`_repr_javascript_` method or use the
849 your objects, define a :meth:`_repr_javascript_` method or use the
848 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
850 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
849 that handle this.
851 that handle this.
850
852
851 The return value of this formatter should be valid Javascript code and
853 The return value of this formatter should be valid Javascript code and
852 should *not* be enclosed in ```<script>``` tags.
854 should *not* be enclosed in ```<script>``` tags.
853 """
855 """
854 format_type = Unicode('application/javascript')
856 format_type = Unicode('application/javascript')
855
857
856 print_method = ObjectName('_repr_javascript_')
858 print_method = ObjectName('_repr_javascript_')
857
859
858
860
859 class PDFFormatter(BaseFormatter):
861 class PDFFormatter(BaseFormatter):
860 """A PDF formatter.
862 """A PDF formatter.
861
863
862 To define the callables that compute the PDF representation of your
864 To define the callables that compute the PDF representation of your
863 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
865 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
864 or :meth:`for_type_by_name` methods to register functions that handle
866 or :meth:`for_type_by_name` methods to register functions that handle
865 this.
867 this.
866
868
867 The return value of this formatter should be raw PDF data, *not*
869 The return value of this formatter should be raw PDF data, *not*
868 base64 encoded.
870 base64 encoded.
869 """
871 """
870 format_type = Unicode('application/pdf')
872 format_type = Unicode('application/pdf')
871
873
872 print_method = ObjectName('_repr_pdf_')
874 print_method = ObjectName('_repr_pdf_')
873
875
874 _return_type = (bytes, unicode_type)
876 _return_type = (bytes, unicode_type)
875
877
876 class IPythonDisplayFormatter(BaseFormatter):
878 class IPythonDisplayFormatter(BaseFormatter):
877 """A Formatter for objects that know how to display themselves.
879 """A Formatter for objects that know how to display themselves.
878
880
879 To define the callables that compute the representation of your
881 To define the callables that compute the representation of your
880 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
882 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
881 or :meth:`for_type_by_name` methods to register functions that handle
883 or :meth:`for_type_by_name` methods to register functions that handle
882 this. Unlike mime-type displays, this method should not return anything,
884 this. Unlike mime-type displays, this method should not return anything,
883 instead calling any appropriate display methods itself.
885 instead calling any appropriate display methods itself.
884
886
885 This display formatter has highest priority.
887 This display formatter has highest priority.
886 If it fires, no other display formatter will be called.
888 If it fires, no other display formatter will be called.
887 """
889 """
888 print_method = ObjectName('_ipython_display_')
890 print_method = ObjectName('_ipython_display_')
889 _return_type = (type(None), bool)
891 _return_type = (type(None), bool)
890
892
891
893
892 @catch_format_error
894 @catch_format_error
893 def __call__(self, obj):
895 def __call__(self, obj):
894 """Compute the format for an object."""
896 """Compute the format for an object."""
895 if self.enabled:
897 if self.enabled:
896 # lookup registered printer
898 # lookup registered printer
897 try:
899 try:
898 printer = self.lookup(obj)
900 printer = self.lookup(obj)
899 except KeyError:
901 except KeyError:
900 pass
902 pass
901 else:
903 else:
902 printer(obj)
904 printer(obj)
903 return True
905 return True
904 # Finally look for special method names
906 # Finally look for special method names
905 method = _safe_get_formatter_method(obj, self.print_method)
907 method = _safe_get_formatter_method(obj, self.print_method)
906 if method is not None:
908 if method is not None:
907 method()
909 method()
908 return True
910 return True
909
911
910
912
911 FormatterABC.register(BaseFormatter)
913 FormatterABC.register(BaseFormatter)
912 FormatterABC.register(PlainTextFormatter)
914 FormatterABC.register(PlainTextFormatter)
913 FormatterABC.register(HTMLFormatter)
915 FormatterABC.register(HTMLFormatter)
914 FormatterABC.register(MarkdownFormatter)
916 FormatterABC.register(MarkdownFormatter)
915 FormatterABC.register(SVGFormatter)
917 FormatterABC.register(SVGFormatter)
916 FormatterABC.register(PNGFormatter)
918 FormatterABC.register(PNGFormatter)
917 FormatterABC.register(PDFFormatter)
919 FormatterABC.register(PDFFormatter)
918 FormatterABC.register(JPEGFormatter)
920 FormatterABC.register(JPEGFormatter)
919 FormatterABC.register(LatexFormatter)
921 FormatterABC.register(LatexFormatter)
920 FormatterABC.register(JSONFormatter)
922 FormatterABC.register(JSONFormatter)
921 FormatterABC.register(JavascriptFormatter)
923 FormatterABC.register(JavascriptFormatter)
922 FormatterABC.register(IPythonDisplayFormatter)
924 FormatterABC.register(IPythonDisplayFormatter)
923
925
924
926
925 def format_display_data(obj, include=None, exclude=None):
927 def format_display_data(obj, include=None, exclude=None):
926 """Return a format data dict for an object.
928 """Return a format data dict for an object.
927
929
928 By default all format types will be computed.
930 By default all format types will be computed.
929
931
930 The following MIME types are currently implemented:
932 The following MIME types are currently implemented:
931
933
932 * text/plain
934 * text/plain
933 * text/html
935 * text/html
934 * text/markdown
936 * text/markdown
935 * text/latex
937 * text/latex
936 * application/json
938 * application/json
937 * application/javascript
939 * application/javascript
938 * application/pdf
940 * application/pdf
939 * image/png
941 * image/png
940 * image/jpeg
942 * image/jpeg
941 * image/svg+xml
943 * image/svg+xml
942
944
943 Parameters
945 Parameters
944 ----------
946 ----------
945 obj : object
947 obj : object
946 The Python object whose format data will be computed.
948 The Python object whose format data will be computed.
947
949
948 Returns
950 Returns
949 -------
951 -------
950 format_dict : dict
952 format_dict : dict
951 A dictionary of key/value pairs, one or each format that was
953 A dictionary of key/value pairs, one or each format that was
952 generated for the object. The keys are the format types, which
954 generated for the object. The keys are the format types, which
953 will usually be MIME type strings and the values and JSON'able
955 will usually be MIME type strings and the values and JSON'able
954 data structure containing the raw data for the representation in
956 data structure containing the raw data for the representation in
955 that format.
957 that format.
956 include : list or tuple, optional
958 include : list or tuple, optional
957 A list of format type strings (MIME types) to include in the
959 A list of format type strings (MIME types) to include in the
958 format data dict. If this is set *only* the format types included
960 format data dict. If this is set *only* the format types included
959 in this list will be computed.
961 in this list will be computed.
960 exclude : list or tuple, optional
962 exclude : list or tuple, optional
961 A list of format type string (MIME types) to exclue in the format
963 A list of format type string (MIME types) to exclue in the format
962 data dict. If this is set all format types will be computed,
964 data dict. If this is set all format types will be computed,
963 except for those included in this argument.
965 except for those included in this argument.
964 """
966 """
965 from IPython.core.interactiveshell import InteractiveShell
967 from IPython.core.interactiveshell import InteractiveShell
966
968
967 InteractiveShell.instance().display_formatter.format(
969 InteractiveShell.instance().display_formatter.format(
968 obj,
970 obj,
969 include,
971 include,
970 exclude
972 exclude
971 )
973 )
972
974
@@ -1,3413 +1,3415 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 from __future__ import absolute_import, print_function
13 from __future__ import absolute_import, print_function
14
14
15 import __future__
15 import __future__
16 import abc
16 import abc
17 import ast
17 import ast
18 import atexit
18 import atexit
19 import functools
19 import functools
20 import os
20 import os
21 import re
21 import re
22 import runpy
22 import runpy
23 import sys
23 import sys
24 import tempfile
24 import tempfile
25 import traceback
25 import traceback
26 import types
26 import types
27 import subprocess
27 import subprocess
28 import warnings
28 import warnings
29 from io import open as io_open
29 from io import open as io_open
30
30
31 from pickleshare import PickleShareDB
31 from pickleshare import PickleShareDB
32
32
33 from traitlets.config.configurable import SingletonConfigurable
33 from traitlets.config.configurable import SingletonConfigurable
34 from IPython.core import debugger, oinspect
34 from IPython.core import debugger, oinspect
35 from IPython.core import magic
35 from IPython.core import magic
36 from IPython.core import page
36 from IPython.core import page
37 from IPython.core import prefilter
37 from IPython.core import prefilter
38 from IPython.core import shadowns
38 from IPython.core import shadowns
39 from IPython.core import ultratb
39 from IPython.core import ultratb
40 from IPython.core.alias import Alias, AliasManager
40 from IPython.core.alias import Alias, AliasManager
41 from IPython.core.autocall import ExitAutocall
41 from IPython.core.autocall import ExitAutocall
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.events import EventManager, available_events
43 from IPython.core.events import EventManager, available_events
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import InputRejected, UsageError
48 from IPython.core.error import InputRejected, UsageError
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.formatters import DisplayFormatter
50 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.history import HistoryManager
51 from IPython.core.history import HistoryManager
52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.logger import Logger
53 from IPython.core.logger import Logger
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.payload import PayloadManager
55 from IPython.core.payload import PayloadManager
56 from IPython.core.prefilter import PrefilterManager
56 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.profiledir import ProfileDir
57 from IPython.core.profiledir import ProfileDir
58 from IPython.core.prompts import PromptManager
58 from IPython.core.prompts import PromptManager
59 from IPython.core.usage import default_banner
59 from IPython.core.usage import default_banner
60 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest
61 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils import py3compat
63 from IPython.utils import py3compat
64 from IPython.utils import openpy
64 from IPython.utils import openpy
65 from IPython.utils.decorators import undoc
65 from IPython.utils.decorators import undoc
66 from IPython.utils.io import ask_yes_no
66 from IPython.utils.io import ask_yes_no
67 from IPython.utils.ipstruct import Struct
67 from IPython.utils.ipstruct import Struct
68 from IPython.paths import get_ipython_dir
68 from IPython.paths import get_ipython_dir
69 from IPython.utils.path import get_home_dir, get_py_filename, unquote_filename, ensure_dir_exists
69 from IPython.utils.path import get_home_dir, get_py_filename, unquote_filename, ensure_dir_exists
70 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 with_metaclass, iteritems)
72 with_metaclass, iteritems)
73 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.text import (format_screen, LSString, SList,
75 from IPython.utils.text import (format_screen, LSString, SList,
76 DollarFormatter)
76 DollarFormatter)
77 from traitlets import (Integer, Bool, CBool, CaselessStrEnum, Enum,
77 from traitlets import (Integer, Bool, CBool, CaselessStrEnum, Enum,
78 List, Dict, Unicode, Instance, Type)
78 List, Dict, Unicode, Instance, Type)
79 from IPython.utils.warn import warn, error
79 from IPython.utils.warn import warn, error
80 import IPython.core.hooks
80 import IPython.core.hooks
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 # Globals
83 # Globals
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85
85
86 # compiled regexps for autoindent management
86 # compiled regexps for autoindent management
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88
88
89 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
90 # Utilities
90 # Utilities
91 #-----------------------------------------------------------------------------
91 #-----------------------------------------------------------------------------
92
92
93 @undoc
93 @undoc
94 def softspace(file, newvalue):
94 def softspace(file, newvalue):
95 """Copied from code.py, to remove the dependency"""
95 """Copied from code.py, to remove the dependency"""
96
96
97 oldvalue = 0
97 oldvalue = 0
98 try:
98 try:
99 oldvalue = file.softspace
99 oldvalue = file.softspace
100 except AttributeError:
100 except AttributeError:
101 pass
101 pass
102 try:
102 try:
103 file.softspace = newvalue
103 file.softspace = newvalue
104 except (AttributeError, TypeError):
104 except (AttributeError, TypeError):
105 # "attribute-less object" or "read-only attributes"
105 # "attribute-less object" or "read-only attributes"
106 pass
106 pass
107 return oldvalue
107 return oldvalue
108
108
109 @undoc
109 @undoc
110 def no_op(*a, **kw): pass
110 def no_op(*a, **kw): pass
111
111
112 @undoc
112 @undoc
113 class NoOpContext(object):
113 class NoOpContext(object):
114 def __enter__(self): pass
114 def __enter__(self): pass
115 def __exit__(self, type, value, traceback): pass
115 def __exit__(self, type, value, traceback): pass
116 no_op_context = NoOpContext()
116 no_op_context = NoOpContext()
117
117
118 class SpaceInInput(Exception): pass
118 class SpaceInInput(Exception): pass
119
119
120 @undoc
120 @undoc
121 class Bunch: pass
121 class Bunch: pass
122
122
123
123
124 def get_default_colors():
124 def get_default_colors():
125 if sys.platform=='darwin':
125 if sys.platform=='darwin':
126 return "LightBG"
126 return "LightBG"
127 elif os.name=='nt':
127 elif os.name=='nt':
128 return 'Linux'
128 return 'Linux'
129 else:
129 else:
130 return 'Linux'
130 return 'Linux'
131
131
132
132
133 class SeparateUnicode(Unicode):
133 class SeparateUnicode(Unicode):
134 r"""A Unicode subclass to validate separate_in, separate_out, etc.
134 r"""A Unicode subclass to validate separate_in, separate_out, etc.
135
135
136 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
136 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
137 """
137 """
138
138
139 def validate(self, obj, value):
139 def validate(self, obj, value):
140 if value == '0': value = ''
140 if value == '0': value = ''
141 value = value.replace('\\n','\n')
141 value = value.replace('\\n','\n')
142 return super(SeparateUnicode, self).validate(obj, value)
142 return super(SeparateUnicode, self).validate(obj, value)
143
143
144
144
145 class ReadlineNoRecord(object):
145 class ReadlineNoRecord(object):
146 """Context manager to execute some code, then reload readline history
146 """Context manager to execute some code, then reload readline history
147 so that interactive input to the code doesn't appear when pressing up."""
147 so that interactive input to the code doesn't appear when pressing up."""
148 def __init__(self, shell):
148 def __init__(self, shell):
149 self.shell = shell
149 self.shell = shell
150 self._nested_level = 0
150 self._nested_level = 0
151
151
152 def __enter__(self):
152 def __enter__(self):
153 if self._nested_level == 0:
153 if self._nested_level == 0:
154 try:
154 try:
155 self.orig_length = self.current_length()
155 self.orig_length = self.current_length()
156 self.readline_tail = self.get_readline_tail()
156 self.readline_tail = self.get_readline_tail()
157 except (AttributeError, IndexError): # Can fail with pyreadline
157 except (AttributeError, IndexError): # Can fail with pyreadline
158 self.orig_length, self.readline_tail = 999999, []
158 self.orig_length, self.readline_tail = 999999, []
159 self._nested_level += 1
159 self._nested_level += 1
160
160
161 def __exit__(self, type, value, traceback):
161 def __exit__(self, type, value, traceback):
162 self._nested_level -= 1
162 self._nested_level -= 1
163 if self._nested_level == 0:
163 if self._nested_level == 0:
164 # Try clipping the end if it's got longer
164 # Try clipping the end if it's got longer
165 try:
165 try:
166 e = self.current_length() - self.orig_length
166 e = self.current_length() - self.orig_length
167 if e > 0:
167 if e > 0:
168 for _ in range(e):
168 for _ in range(e):
169 self.shell.readline.remove_history_item(self.orig_length)
169 self.shell.readline.remove_history_item(self.orig_length)
170
170
171 # If it still doesn't match, just reload readline history.
171 # If it still doesn't match, just reload readline history.
172 if self.current_length() != self.orig_length \
172 if self.current_length() != self.orig_length \
173 or self.get_readline_tail() != self.readline_tail:
173 or self.get_readline_tail() != self.readline_tail:
174 self.shell.refill_readline_hist()
174 self.shell.refill_readline_hist()
175 except (AttributeError, IndexError):
175 except (AttributeError, IndexError):
176 pass
176 pass
177 # Returning False will cause exceptions to propagate
177 # Returning False will cause exceptions to propagate
178 return False
178 return False
179
179
180 def current_length(self):
180 def current_length(self):
181 return self.shell.readline.get_current_history_length()
181 return self.shell.readline.get_current_history_length()
182
182
183 def get_readline_tail(self, n=10):
183 def get_readline_tail(self, n=10):
184 """Get the last n items in readline history."""
184 """Get the last n items in readline history."""
185 end = self.shell.readline.get_current_history_length() + 1
185 end = self.shell.readline.get_current_history_length() + 1
186 start = max(end-n, 1)
186 start = max(end-n, 1)
187 ghi = self.shell.readline.get_history_item
187 ghi = self.shell.readline.get_history_item
188 return [ghi(x) for x in range(start, end)]
188 return [ghi(x) for x in range(start, end)]
189
189
190
190
191 @undoc
191 @undoc
192 class DummyMod(object):
192 class DummyMod(object):
193 """A dummy module used for IPython's interactive module when
193 """A dummy module used for IPython's interactive module when
194 a namespace must be assigned to the module's __dict__."""
194 a namespace must be assigned to the module's __dict__."""
195 pass
195 pass
196
196
197
197
198 class ExecutionResult(object):
198 class ExecutionResult(object):
199 """The result of a call to :meth:`InteractiveShell.run_cell`
199 """The result of a call to :meth:`InteractiveShell.run_cell`
200
200
201 Stores information about what took place.
201 Stores information about what took place.
202 """
202 """
203 execution_count = None
203 execution_count = None
204 error_before_exec = None
204 error_before_exec = None
205 error_in_exec = None
205 error_in_exec = None
206 result = None
206 result = None
207
207
208 @property
208 @property
209 def success(self):
209 def success(self):
210 return (self.error_before_exec is None) and (self.error_in_exec is None)
210 return (self.error_before_exec is None) and (self.error_in_exec is None)
211
211
212 def raise_error(self):
212 def raise_error(self):
213 """Reraises error if `success` is `False`, otherwise does nothing"""
213 """Reraises error if `success` is `False`, otherwise does nothing"""
214 if self.error_before_exec is not None:
214 if self.error_before_exec is not None:
215 raise self.error_before_exec
215 raise self.error_before_exec
216 if self.error_in_exec is not None:
216 if self.error_in_exec is not None:
217 raise self.error_in_exec
217 raise self.error_in_exec
218
218
219
219
220 class InteractiveShell(SingletonConfigurable):
220 class InteractiveShell(SingletonConfigurable):
221 """An enhanced, interactive shell for Python."""
221 """An enhanced, interactive shell for Python."""
222
222
223 _instance = None
223 _instance = None
224
224
225 ast_transformers = List([], config=True, help=
225 ast_transformers = List([], config=True, help=
226 """
226 """
227 A list of ast.NodeTransformer subclass instances, which will be applied
227 A list of ast.NodeTransformer subclass instances, which will be applied
228 to user input before code is run.
228 to user input before code is run.
229 """
229 """
230 )
230 )
231
231
232 autocall = Enum((0,1,2), default_value=0, config=True, help=
232 autocall = Enum((0,1,2), default_value=0, config=True, help=
233 """
233 """
234 Make IPython automatically call any callable object even if you didn't
234 Make IPython automatically call any callable object even if you didn't
235 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
235 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
236 automatically. The value can be '0' to disable the feature, '1' for
236 automatically. The value can be '0' to disable the feature, '1' for
237 'smart' autocall, where it is not applied if there are no more
237 'smart' autocall, where it is not applied if there are no more
238 arguments on the line, and '2' for 'full' autocall, where all callable
238 arguments on the line, and '2' for 'full' autocall, where all callable
239 objects are automatically called (even if no arguments are present).
239 objects are automatically called (even if no arguments are present).
240 """
240 """
241 )
241 )
242 # TODO: remove all autoindent logic and put into frontends.
242 # TODO: remove all autoindent logic and put into frontends.
243 # We can't do this yet because even runlines uses the autoindent.
243 # We can't do this yet because even runlines uses the autoindent.
244 autoindent = CBool(True, config=True, help=
244 autoindent = CBool(True, config=True, help=
245 """
245 """
246 Autoindent IPython code entered interactively.
246 Autoindent IPython code entered interactively.
247 """
247 """
248 )
248 )
249 automagic = CBool(True, config=True, help=
249 automagic = CBool(True, config=True, help=
250 """
250 """
251 Enable magic commands to be called without the leading %.
251 Enable magic commands to be called without the leading %.
252 """
252 """
253 )
253 )
254
254
255 banner1 = Unicode(default_banner, config=True,
255 banner1 = Unicode(default_banner, config=True,
256 help="""The part of the banner to be printed before the profile"""
256 help="""The part of the banner to be printed before the profile"""
257 )
257 )
258 banner2 = Unicode('', config=True,
258 banner2 = Unicode('', config=True,
259 help="""The part of the banner to be printed after the profile"""
259 help="""The part of the banner to be printed after the profile"""
260 )
260 )
261
261
262 cache_size = Integer(1000, config=True, help=
262 cache_size = Integer(1000, config=True, help=
263 """
263 """
264 Set the size of the output cache. The default is 1000, you can
264 Set the size of the output cache. The default is 1000, you can
265 change it permanently in your config file. Setting it to 0 completely
265 change it permanently in your config file. Setting it to 0 completely
266 disables the caching system, and the minimum value accepted is 20 (if
266 disables the caching system, and the minimum value accepted is 20 (if
267 you provide a value less than 20, it is reset to 0 and a warning is
267 you provide a value less than 20, it is reset to 0 and a warning is
268 issued). This limit is defined because otherwise you'll spend more
268 issued). This limit is defined because otherwise you'll spend more
269 time re-flushing a too small cache than working
269 time re-flushing a too small cache than working
270 """
270 """
271 )
271 )
272 color_info = CBool(True, config=True, help=
272 color_info = CBool(True, config=True, help=
273 """
273 """
274 Use colors for displaying information about objects. Because this
274 Use colors for displaying information about objects. Because this
275 information is passed through a pager (like 'less'), and some pagers
275 information is passed through a pager (like 'less'), and some pagers
276 get confused with color codes, this capability can be turned off.
276 get confused with color codes, this capability can be turned off.
277 """
277 """
278 )
278 )
279 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
279 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
280 default_value=get_default_colors(), config=True,
280 default_value=get_default_colors(), config=True,
281 help="Set the color scheme (NoColor, Linux, or LightBG)."
281 help="Set the color scheme (NoColor, Linux, or LightBG)."
282 )
282 )
283 colors_force = CBool(False, help=
283 colors_force = CBool(False, help=
284 """
284 """
285 Force use of ANSI color codes, regardless of OS and readline
285 Force use of ANSI color codes, regardless of OS and readline
286 availability.
286 availability.
287 """
287 """
288 # FIXME: This is essentially a hack to allow ZMQShell to show colors
288 # FIXME: This is essentially a hack to allow ZMQShell to show colors
289 # without readline on Win32. When the ZMQ formatting system is
289 # without readline on Win32. When the ZMQ formatting system is
290 # refactored, this should be removed.
290 # refactored, this should be removed.
291 )
291 )
292 debug = CBool(False, config=True)
292 debug = CBool(False, config=True)
293 deep_reload = CBool(False, config=True, help=
293 deep_reload = CBool(False, config=True, help=
294 """
294 """
295 **Deprecated**
295 **Deprecated**
296
296
297 Will be removed in IPython 6.0
298
297 Enable deep (recursive) reloading by default. IPython can use the
299 Enable deep (recursive) reloading by default. IPython can use the
298 deep_reload module which reloads changes in modules recursively (it
300 deep_reload module which reloads changes in modules recursively (it
299 replaces the reload() function, so you don't need to change anything to
301 replaces the reload() function, so you don't need to change anything to
300 use it). `deep_reload` forces a full reload of modules whose code may
302 use it). `deep_reload` forces a full reload of modules whose code may
301 have changed, which the default reload() function does not. When
303 have changed, which the default reload() function does not. When
302 deep_reload is off, IPython will use the normal reload(), but
304 deep_reload is off, IPython will use the normal reload(), but
303 deep_reload will still be available as dreload().
305 deep_reload will still be available as dreload().
304 """
306 """
305 )
307 )
306 disable_failing_post_execute = CBool(False, config=True,
308 disable_failing_post_execute = CBool(False, config=True,
307 help="Don't call post-execute functions that have failed in the past."
309 help="Don't call post-execute functions that have failed in the past."
308 )
310 )
309 display_formatter = Instance(DisplayFormatter, allow_none=True)
311 display_formatter = Instance(DisplayFormatter, allow_none=True)
310 displayhook_class = Type(DisplayHook)
312 displayhook_class = Type(DisplayHook)
311 display_pub_class = Type(DisplayPublisher)
313 display_pub_class = Type(DisplayPublisher)
312 data_pub_class = None
314 data_pub_class = None
313
315
314 exit_now = CBool(False)
316 exit_now = CBool(False)
315 exiter = Instance(ExitAutocall)
317 exiter = Instance(ExitAutocall)
316 def _exiter_default(self):
318 def _exiter_default(self):
317 return ExitAutocall(self)
319 return ExitAutocall(self)
318 # Monotonically increasing execution counter
320 # Monotonically increasing execution counter
319 execution_count = Integer(1)
321 execution_count = Integer(1)
320 filename = Unicode("<ipython console>")
322 filename = Unicode("<ipython console>")
321 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
323 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
322
324
323 # Input splitter, to transform input line by line and detect when a block
325 # Input splitter, to transform input line by line and detect when a block
324 # is ready to be executed.
326 # is ready to be executed.
325 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
327 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
326 (), {'line_input_checker': True})
328 (), {'line_input_checker': True})
327
329
328 # This InputSplitter instance is used to transform completed cells before
330 # This InputSplitter instance is used to transform completed cells before
329 # running them. It allows cell magics to contain blank lines.
331 # running them. It allows cell magics to contain blank lines.
330 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
332 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
331 (), {'line_input_checker': False})
333 (), {'line_input_checker': False})
332
334
333 logstart = CBool(False, config=True, help=
335 logstart = CBool(False, config=True, help=
334 """
336 """
335 Start logging to the default log file in overwrite mode.
337 Start logging to the default log file in overwrite mode.
336 Use `logappend` to specify a log file to **append** logs to.
338 Use `logappend` to specify a log file to **append** logs to.
337 """
339 """
338 )
340 )
339 logfile = Unicode('', config=True, help=
341 logfile = Unicode('', config=True, help=
340 """
342 """
341 The name of the logfile to use.
343 The name of the logfile to use.
342 """
344 """
343 )
345 )
344 logappend = Unicode('', config=True, help=
346 logappend = Unicode('', config=True, help=
345 """
347 """
346 Start logging to the given file in append mode.
348 Start logging to the given file in append mode.
347 Use `logfile` to specify a log file to **overwrite** logs to.
349 Use `logfile` to specify a log file to **overwrite** logs to.
348 """
350 """
349 )
351 )
350 object_info_string_level = Enum((0,1,2), default_value=0,
352 object_info_string_level = Enum((0,1,2), default_value=0,
351 config=True)
353 config=True)
352 pdb = CBool(False, config=True, help=
354 pdb = CBool(False, config=True, help=
353 """
355 """
354 Automatically call the pdb debugger after every exception.
356 Automatically call the pdb debugger after every exception.
355 """
357 """
356 )
358 )
357 multiline_history = CBool(sys.platform != 'win32', config=True,
359 multiline_history = CBool(sys.platform != 'win32', config=True,
358 help="Save multi-line entries as one entry in readline history"
360 help="Save multi-line entries as one entry in readline history"
359 )
361 )
360 display_page = Bool(False, config=True,
362 display_page = Bool(False, config=True,
361 help="""If True, anything that would be passed to the pager
363 help="""If True, anything that would be passed to the pager
362 will be displayed as regular output instead."""
364 will be displayed as regular output instead."""
363 )
365 )
364
366
365 # deprecated prompt traits:
367 # deprecated prompt traits:
366
368
367 prompt_in1 = Unicode('In [\\#]: ', config=True,
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 prompt_in2 = Unicode(' .\\D.: ', config=True,
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 prompt_out = Unicode('Out[\\#]: ', config=True,
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 prompts_pad_left = CBool(True, config=True,
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 def _prompt_trait_changed(self, name, old, new):
378 def _prompt_trait_changed(self, name, old, new):
377 table = {
379 table = {
378 'prompt_in1' : 'in_template',
380 'prompt_in1' : 'in_template',
379 'prompt_in2' : 'in2_template',
381 'prompt_in2' : 'in2_template',
380 'prompt_out' : 'out_template',
382 'prompt_out' : 'out_template',
381 'prompts_pad_left' : 'justify',
383 'prompts_pad_left' : 'justify',
382 }
384 }
383 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
385 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
384 name=name, newname=table[name])
386 name=name, newname=table[name])
385 )
387 )
386 # protect against weird cases where self.config may not exist:
388 # protect against weird cases where self.config may not exist:
387 if self.config is not None:
389 if self.config is not None:
388 # propagate to corresponding PromptManager trait
390 # propagate to corresponding PromptManager trait
389 setattr(self.config.PromptManager, table[name], new)
391 setattr(self.config.PromptManager, table[name], new)
390
392
391 _prompt_in1_changed = _prompt_trait_changed
393 _prompt_in1_changed = _prompt_trait_changed
392 _prompt_in2_changed = _prompt_trait_changed
394 _prompt_in2_changed = _prompt_trait_changed
393 _prompt_out_changed = _prompt_trait_changed
395 _prompt_out_changed = _prompt_trait_changed
394 _prompt_pad_left_changed = _prompt_trait_changed
396 _prompt_pad_left_changed = _prompt_trait_changed
395
397
396 show_rewritten_input = CBool(True, config=True,
398 show_rewritten_input = CBool(True, config=True,
397 help="Show rewritten input, e.g. for autocall."
399 help="Show rewritten input, e.g. for autocall."
398 )
400 )
399
401
400 quiet = CBool(False, config=True)
402 quiet = CBool(False, config=True)
401
403
402 history_length = Integer(10000, config=True)
404 history_length = Integer(10000, config=True)
403
405
404 history_load_length = Integer(1000, config=True, help=
406 history_load_length = Integer(1000, config=True, help=
405 """
407 """
406 The number of saved history entries to be loaded
408 The number of saved history entries to be loaded
407 into the readline buffer at startup.
409 into the readline buffer at startup.
408 """
410 """
409 )
411 )
410
412
411 # The readline stuff will eventually be moved to the terminal subclass
413 # The readline stuff will eventually be moved to the terminal subclass
412 # but for now, we can't do that as readline is welded in everywhere.
414 # but for now, we can't do that as readline is welded in everywhere.
413 readline_use = CBool(True, config=True)
415 readline_use = CBool(True, config=True)
414 readline_remove_delims = Unicode('-/~', config=True)
416 readline_remove_delims = Unicode('-/~', config=True)
415 readline_delims = Unicode() # set by init_readline()
417 readline_delims = Unicode() # set by init_readline()
416 # don't use \M- bindings by default, because they
418 # don't use \M- bindings by default, because they
417 # conflict with 8-bit encodings. See gh-58,gh-88
419 # conflict with 8-bit encodings. See gh-58,gh-88
418 readline_parse_and_bind = List([
420 readline_parse_and_bind = List([
419 'tab: complete',
421 'tab: complete',
420 '"\C-l": clear-screen',
422 '"\C-l": clear-screen',
421 'set show-all-if-ambiguous on',
423 'set show-all-if-ambiguous on',
422 '"\C-o": tab-insert',
424 '"\C-o": tab-insert',
423 '"\C-r": reverse-search-history',
425 '"\C-r": reverse-search-history',
424 '"\C-s": forward-search-history',
426 '"\C-s": forward-search-history',
425 '"\C-p": history-search-backward',
427 '"\C-p": history-search-backward',
426 '"\C-n": history-search-forward',
428 '"\C-n": history-search-forward',
427 '"\e[A": history-search-backward',
429 '"\e[A": history-search-backward',
428 '"\e[B": history-search-forward',
430 '"\e[B": history-search-forward',
429 '"\C-k": kill-line',
431 '"\C-k": kill-line',
430 '"\C-u": unix-line-discard',
432 '"\C-u": unix-line-discard',
431 ], config=True)
433 ], config=True)
432
434
433 _custom_readline_config = False
435 _custom_readline_config = False
434
436
435 def _readline_parse_and_bind_changed(self, name, old, new):
437 def _readline_parse_and_bind_changed(self, name, old, new):
436 # notice that readline config is customized
438 # notice that readline config is customized
437 # indicates that it should have higher priority than inputrc
439 # indicates that it should have higher priority than inputrc
438 self._custom_readline_config = True
440 self._custom_readline_config = True
439
441
440 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
442 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
441 default_value='last_expr', config=True,
443 default_value='last_expr', config=True,
442 help="""
444 help="""
443 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
445 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
444 run interactively (displaying output from expressions).""")
446 run interactively (displaying output from expressions).""")
445
447
446 # TODO: this part of prompt management should be moved to the frontends.
448 # TODO: this part of prompt management should be moved to the frontends.
447 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
449 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
448 separate_in = SeparateUnicode('\n', config=True)
450 separate_in = SeparateUnicode('\n', config=True)
449 separate_out = SeparateUnicode('', config=True)
451 separate_out = SeparateUnicode('', config=True)
450 separate_out2 = SeparateUnicode('', config=True)
452 separate_out2 = SeparateUnicode('', config=True)
451 wildcards_case_sensitive = CBool(True, config=True)
453 wildcards_case_sensitive = CBool(True, config=True)
452 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
454 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
453 default_value='Context', config=True)
455 default_value='Context', config=True)
454
456
455 # Subcomponents of InteractiveShell
457 # Subcomponents of InteractiveShell
456 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
458 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
457 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
459 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
458 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
460 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
459 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
461 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
460 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
462 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
461 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
463 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
462 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
464 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
463 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
465 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
464
466
465 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
467 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
466 @property
468 @property
467 def profile(self):
469 def profile(self):
468 if self.profile_dir is not None:
470 if self.profile_dir is not None:
469 name = os.path.basename(self.profile_dir.location)
471 name = os.path.basename(self.profile_dir.location)
470 return name.replace('profile_','')
472 return name.replace('profile_','')
471
473
472
474
473 # Private interface
475 # Private interface
474 _post_execute = Dict()
476 _post_execute = Dict()
475
477
476 # Tracks any GUI loop loaded for pylab
478 # Tracks any GUI loop loaded for pylab
477 pylab_gui_select = None
479 pylab_gui_select = None
478
480
479 def __init__(self, ipython_dir=None, profile_dir=None,
481 def __init__(self, ipython_dir=None, profile_dir=None,
480 user_module=None, user_ns=None,
482 user_module=None, user_ns=None,
481 custom_exceptions=((), None), **kwargs):
483 custom_exceptions=((), None), **kwargs):
482
484
483 # This is where traits with a config_key argument are updated
485 # This is where traits with a config_key argument are updated
484 # from the values on config.
486 # from the values on config.
485 super(InteractiveShell, self).__init__(**kwargs)
487 super(InteractiveShell, self).__init__(**kwargs)
486 self.configurables = [self]
488 self.configurables = [self]
487
489
488 # These are relatively independent and stateless
490 # These are relatively independent and stateless
489 self.init_ipython_dir(ipython_dir)
491 self.init_ipython_dir(ipython_dir)
490 self.init_profile_dir(profile_dir)
492 self.init_profile_dir(profile_dir)
491 self.init_instance_attrs()
493 self.init_instance_attrs()
492 self.init_environment()
494 self.init_environment()
493
495
494 # Check if we're in a virtualenv, and set up sys.path.
496 # Check if we're in a virtualenv, and set up sys.path.
495 self.init_virtualenv()
497 self.init_virtualenv()
496
498
497 # Create namespaces (user_ns, user_global_ns, etc.)
499 # Create namespaces (user_ns, user_global_ns, etc.)
498 self.init_create_namespaces(user_module, user_ns)
500 self.init_create_namespaces(user_module, user_ns)
499 # This has to be done after init_create_namespaces because it uses
501 # This has to be done after init_create_namespaces because it uses
500 # something in self.user_ns, but before init_sys_modules, which
502 # something in self.user_ns, but before init_sys_modules, which
501 # is the first thing to modify sys.
503 # is the first thing to modify sys.
502 # TODO: When we override sys.stdout and sys.stderr before this class
504 # TODO: When we override sys.stdout and sys.stderr before this class
503 # is created, we are saving the overridden ones here. Not sure if this
505 # is created, we are saving the overridden ones here. Not sure if this
504 # is what we want to do.
506 # is what we want to do.
505 self.save_sys_module_state()
507 self.save_sys_module_state()
506 self.init_sys_modules()
508 self.init_sys_modules()
507
509
508 # While we're trying to have each part of the code directly access what
510 # While we're trying to have each part of the code directly access what
509 # it needs without keeping redundant references to objects, we have too
511 # it needs without keeping redundant references to objects, we have too
510 # much legacy code that expects ip.db to exist.
512 # much legacy code that expects ip.db to exist.
511 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
513 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
512
514
513 self.init_history()
515 self.init_history()
514 self.init_encoding()
516 self.init_encoding()
515 self.init_prefilter()
517 self.init_prefilter()
516
518
517 self.init_syntax_highlighting()
519 self.init_syntax_highlighting()
518 self.init_hooks()
520 self.init_hooks()
519 self.init_events()
521 self.init_events()
520 self.init_pushd_popd_magic()
522 self.init_pushd_popd_magic()
521 # self.init_traceback_handlers use to be here, but we moved it below
523 # self.init_traceback_handlers use to be here, but we moved it below
522 # because it and init_io have to come after init_readline.
524 # because it and init_io have to come after init_readline.
523 self.init_user_ns()
525 self.init_user_ns()
524 self.init_logger()
526 self.init_logger()
525 self.init_builtins()
527 self.init_builtins()
526
528
527 # The following was in post_config_initialization
529 # The following was in post_config_initialization
528 self.init_inspector()
530 self.init_inspector()
529 # init_readline() must come before init_io(), because init_io uses
531 # init_readline() must come before init_io(), because init_io uses
530 # readline related things.
532 # readline related things.
531 self.init_readline()
533 self.init_readline()
532 # We save this here in case user code replaces raw_input, but it needs
534 # We save this here in case user code replaces raw_input, but it needs
533 # to be after init_readline(), because PyPy's readline works by replacing
535 # to be after init_readline(), because PyPy's readline works by replacing
534 # raw_input.
536 # raw_input.
535 if py3compat.PY3:
537 if py3compat.PY3:
536 self.raw_input_original = input
538 self.raw_input_original = input
537 else:
539 else:
538 self.raw_input_original = raw_input
540 self.raw_input_original = raw_input
539 # init_completer must come after init_readline, because it needs to
541 # init_completer must come after init_readline, because it needs to
540 # know whether readline is present or not system-wide to configure the
542 # know whether readline is present or not system-wide to configure the
541 # completers, since the completion machinery can now operate
543 # completers, since the completion machinery can now operate
542 # independently of readline (e.g. over the network)
544 # independently of readline (e.g. over the network)
543 self.init_completer()
545 self.init_completer()
544 # TODO: init_io() needs to happen before init_traceback handlers
546 # TODO: init_io() needs to happen before init_traceback handlers
545 # because the traceback handlers hardcode the stdout/stderr streams.
547 # because the traceback handlers hardcode the stdout/stderr streams.
546 # This logic in in debugger.Pdb and should eventually be changed.
548 # This logic in in debugger.Pdb and should eventually be changed.
547 self.init_io()
549 self.init_io()
548 self.init_traceback_handlers(custom_exceptions)
550 self.init_traceback_handlers(custom_exceptions)
549 self.init_prompts()
551 self.init_prompts()
550 self.init_display_formatter()
552 self.init_display_formatter()
551 self.init_display_pub()
553 self.init_display_pub()
552 self.init_data_pub()
554 self.init_data_pub()
553 self.init_displayhook()
555 self.init_displayhook()
554 self.init_magics()
556 self.init_magics()
555 self.init_alias()
557 self.init_alias()
556 self.init_logstart()
558 self.init_logstart()
557 self.init_pdb()
559 self.init_pdb()
558 self.init_extension_manager()
560 self.init_extension_manager()
559 self.init_payload()
561 self.init_payload()
560 self.init_deprecation_warnings()
562 self.init_deprecation_warnings()
561 self.hooks.late_startup_hook()
563 self.hooks.late_startup_hook()
562 self.events.trigger('shell_initialized', self)
564 self.events.trigger('shell_initialized', self)
563 atexit.register(self.atexit_operations)
565 atexit.register(self.atexit_operations)
564
566
565 def get_ipython(self):
567 def get_ipython(self):
566 """Return the currently running IPython instance."""
568 """Return the currently running IPython instance."""
567 return self
569 return self
568
570
569 #-------------------------------------------------------------------------
571 #-------------------------------------------------------------------------
570 # Trait changed handlers
572 # Trait changed handlers
571 #-------------------------------------------------------------------------
573 #-------------------------------------------------------------------------
572
574
573 def _ipython_dir_changed(self, name, new):
575 def _ipython_dir_changed(self, name, new):
574 ensure_dir_exists(new)
576 ensure_dir_exists(new)
575
577
576 def set_autoindent(self,value=None):
578 def set_autoindent(self,value=None):
577 """Set the autoindent flag, checking for readline support.
579 """Set the autoindent flag, checking for readline support.
578
580
579 If called with no arguments, it acts as a toggle."""
581 If called with no arguments, it acts as a toggle."""
580
582
581 if value != 0 and not self.has_readline:
583 if value != 0 and not self.has_readline:
582 if os.name == 'posix':
584 if os.name == 'posix':
583 warn("The auto-indent feature requires the readline library")
585 warn("The auto-indent feature requires the readline library")
584 self.autoindent = 0
586 self.autoindent = 0
585 return
587 return
586 if value is None:
588 if value is None:
587 self.autoindent = not self.autoindent
589 self.autoindent = not self.autoindent
588 else:
590 else:
589 self.autoindent = value
591 self.autoindent = value
590
592
591 #-------------------------------------------------------------------------
593 #-------------------------------------------------------------------------
592 # init_* methods called by __init__
594 # init_* methods called by __init__
593 #-------------------------------------------------------------------------
595 #-------------------------------------------------------------------------
594
596
595 def init_ipython_dir(self, ipython_dir):
597 def init_ipython_dir(self, ipython_dir):
596 if ipython_dir is not None:
598 if ipython_dir is not None:
597 self.ipython_dir = ipython_dir
599 self.ipython_dir = ipython_dir
598 return
600 return
599
601
600 self.ipython_dir = get_ipython_dir()
602 self.ipython_dir = get_ipython_dir()
601
603
602 def init_profile_dir(self, profile_dir):
604 def init_profile_dir(self, profile_dir):
603 if profile_dir is not None:
605 if profile_dir is not None:
604 self.profile_dir = profile_dir
606 self.profile_dir = profile_dir
605 return
607 return
606 self.profile_dir =\
608 self.profile_dir =\
607 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
609 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
608
610
609 def init_instance_attrs(self):
611 def init_instance_attrs(self):
610 self.more = False
612 self.more = False
611
613
612 # command compiler
614 # command compiler
613 self.compile = CachingCompiler()
615 self.compile = CachingCompiler()
614
616
615 # Make an empty namespace, which extension writers can rely on both
617 # Make an empty namespace, which extension writers can rely on both
616 # existing and NEVER being used by ipython itself. This gives them a
618 # existing and NEVER being used by ipython itself. This gives them a
617 # convenient location for storing additional information and state
619 # convenient location for storing additional information and state
618 # their extensions may require, without fear of collisions with other
620 # their extensions may require, without fear of collisions with other
619 # ipython names that may develop later.
621 # ipython names that may develop later.
620 self.meta = Struct()
622 self.meta = Struct()
621
623
622 # Temporary files used for various purposes. Deleted at exit.
624 # Temporary files used for various purposes. Deleted at exit.
623 self.tempfiles = []
625 self.tempfiles = []
624 self.tempdirs = []
626 self.tempdirs = []
625
627
626 # Keep track of readline usage (later set by init_readline)
628 # Keep track of readline usage (later set by init_readline)
627 self.has_readline = False
629 self.has_readline = False
628
630
629 # keep track of where we started running (mainly for crash post-mortem)
631 # keep track of where we started running (mainly for crash post-mortem)
630 # This is not being used anywhere currently.
632 # This is not being used anywhere currently.
631 self.starting_dir = py3compat.getcwd()
633 self.starting_dir = py3compat.getcwd()
632
634
633 # Indentation management
635 # Indentation management
634 self.indent_current_nsp = 0
636 self.indent_current_nsp = 0
635
637
636 # Dict to track post-execution functions that have been registered
638 # Dict to track post-execution functions that have been registered
637 self._post_execute = {}
639 self._post_execute = {}
638
640
639 def init_environment(self):
641 def init_environment(self):
640 """Any changes we need to make to the user's environment."""
642 """Any changes we need to make to the user's environment."""
641 pass
643 pass
642
644
643 def init_encoding(self):
645 def init_encoding(self):
644 # Get system encoding at startup time. Certain terminals (like Emacs
646 # Get system encoding at startup time. Certain terminals (like Emacs
645 # under Win32 have it set to None, and we need to have a known valid
647 # under Win32 have it set to None, and we need to have a known valid
646 # encoding to use in the raw_input() method
648 # encoding to use in the raw_input() method
647 try:
649 try:
648 self.stdin_encoding = sys.stdin.encoding or 'ascii'
650 self.stdin_encoding = sys.stdin.encoding or 'ascii'
649 except AttributeError:
651 except AttributeError:
650 self.stdin_encoding = 'ascii'
652 self.stdin_encoding = 'ascii'
651
653
652 def init_syntax_highlighting(self):
654 def init_syntax_highlighting(self):
653 # Python source parser/formatter for syntax highlighting
655 # Python source parser/formatter for syntax highlighting
654 pyformat = PyColorize.Parser().format
656 pyformat = PyColorize.Parser().format
655 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
657 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
656
658
657 def init_pushd_popd_magic(self):
659 def init_pushd_popd_magic(self):
658 # for pushd/popd management
660 # for pushd/popd management
659 self.home_dir = get_home_dir()
661 self.home_dir = get_home_dir()
660
662
661 self.dir_stack = []
663 self.dir_stack = []
662
664
663 def init_logger(self):
665 def init_logger(self):
664 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
666 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
665 logmode='rotate')
667 logmode='rotate')
666
668
667 def init_logstart(self):
669 def init_logstart(self):
668 """Initialize logging in case it was requested at the command line.
670 """Initialize logging in case it was requested at the command line.
669 """
671 """
670 if self.logappend:
672 if self.logappend:
671 self.magic('logstart %s append' % self.logappend)
673 self.magic('logstart %s append' % self.logappend)
672 elif self.logfile:
674 elif self.logfile:
673 self.magic('logstart %s' % self.logfile)
675 self.magic('logstart %s' % self.logfile)
674 elif self.logstart:
676 elif self.logstart:
675 self.magic('logstart')
677 self.magic('logstart')
676
678
677 def init_deprecation_warnings(self):
679 def init_deprecation_warnings(self):
678 """
680 """
679 register default filter for deprecation warning.
681 register default filter for deprecation warning.
680
682
681 This will allow deprecation warning of function used interactively to show
683 This will allow deprecation warning of function used interactively to show
682 warning to users, and still hide deprecation warning from libraries import.
684 warning to users, and still hide deprecation warning from libraries import.
683 """
685 """
684 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
686 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
685
687
686 def init_builtins(self):
688 def init_builtins(self):
687 # A single, static flag that we set to True. Its presence indicates
689 # A single, static flag that we set to True. Its presence indicates
688 # that an IPython shell has been created, and we make no attempts at
690 # that an IPython shell has been created, and we make no attempts at
689 # removing on exit or representing the existence of more than one
691 # removing on exit or representing the existence of more than one
690 # IPython at a time.
692 # IPython at a time.
691 builtin_mod.__dict__['__IPYTHON__'] = True
693 builtin_mod.__dict__['__IPYTHON__'] = True
692
694
693 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
695 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
694 # manage on enter/exit, but with all our shells it's virtually
696 # manage on enter/exit, but with all our shells it's virtually
695 # impossible to get all the cases right. We're leaving the name in for
697 # impossible to get all the cases right. We're leaving the name in for
696 # those who adapted their codes to check for this flag, but will
698 # those who adapted their codes to check for this flag, but will
697 # eventually remove it after a few more releases.
699 # eventually remove it after a few more releases.
698 builtin_mod.__dict__['__IPYTHON__active'] = \
700 builtin_mod.__dict__['__IPYTHON__active'] = \
699 'Deprecated, check for __IPYTHON__'
701 'Deprecated, check for __IPYTHON__'
700
702
701 self.builtin_trap = BuiltinTrap(shell=self)
703 self.builtin_trap = BuiltinTrap(shell=self)
702
704
703 def init_inspector(self):
705 def init_inspector(self):
704 # Object inspector
706 # Object inspector
705 self.inspector = oinspect.Inspector(oinspect.InspectColors,
707 self.inspector = oinspect.Inspector(oinspect.InspectColors,
706 PyColorize.ANSICodeColors,
708 PyColorize.ANSICodeColors,
707 'NoColor',
709 'NoColor',
708 self.object_info_string_level)
710 self.object_info_string_level)
709
711
710 def init_io(self):
712 def init_io(self):
711 # This will just use sys.stdout and sys.stderr. If you want to
713 # This will just use sys.stdout and sys.stderr. If you want to
712 # override sys.stdout and sys.stderr themselves, you need to do that
714 # override sys.stdout and sys.stderr themselves, you need to do that
713 # *before* instantiating this class, because io holds onto
715 # *before* instantiating this class, because io holds onto
714 # references to the underlying streams.
716 # references to the underlying streams.
715 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
717 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
716 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
718 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
717 else:
719 else:
718 io.stdout = io.IOStream(sys.stdout)
720 io.stdout = io.IOStream(sys.stdout)
719 io.stderr = io.IOStream(sys.stderr)
721 io.stderr = io.IOStream(sys.stderr)
720
722
721 def init_prompts(self):
723 def init_prompts(self):
722 self.prompt_manager = PromptManager(shell=self, parent=self)
724 self.prompt_manager = PromptManager(shell=self, parent=self)
723 self.configurables.append(self.prompt_manager)
725 self.configurables.append(self.prompt_manager)
724 # Set system prompts, so that scripts can decide if they are running
726 # Set system prompts, so that scripts can decide if they are running
725 # interactively.
727 # interactively.
726 sys.ps1 = 'In : '
728 sys.ps1 = 'In : '
727 sys.ps2 = '...: '
729 sys.ps2 = '...: '
728 sys.ps3 = 'Out: '
730 sys.ps3 = 'Out: '
729
731
730 def init_display_formatter(self):
732 def init_display_formatter(self):
731 self.display_formatter = DisplayFormatter(parent=self)
733 self.display_formatter = DisplayFormatter(parent=self)
732 self.configurables.append(self.display_formatter)
734 self.configurables.append(self.display_formatter)
733
735
734 def init_display_pub(self):
736 def init_display_pub(self):
735 self.display_pub = self.display_pub_class(parent=self)
737 self.display_pub = self.display_pub_class(parent=self)
736 self.configurables.append(self.display_pub)
738 self.configurables.append(self.display_pub)
737
739
738 def init_data_pub(self):
740 def init_data_pub(self):
739 if not self.data_pub_class:
741 if not self.data_pub_class:
740 self.data_pub = None
742 self.data_pub = None
741 return
743 return
742 self.data_pub = self.data_pub_class(parent=self)
744 self.data_pub = self.data_pub_class(parent=self)
743 self.configurables.append(self.data_pub)
745 self.configurables.append(self.data_pub)
744
746
745 def init_displayhook(self):
747 def init_displayhook(self):
746 # Initialize displayhook, set in/out prompts and printing system
748 # Initialize displayhook, set in/out prompts and printing system
747 self.displayhook = self.displayhook_class(
749 self.displayhook = self.displayhook_class(
748 parent=self,
750 parent=self,
749 shell=self,
751 shell=self,
750 cache_size=self.cache_size,
752 cache_size=self.cache_size,
751 )
753 )
752 self.configurables.append(self.displayhook)
754 self.configurables.append(self.displayhook)
753 # This is a context manager that installs/revmoes the displayhook at
755 # This is a context manager that installs/revmoes the displayhook at
754 # the appropriate time.
756 # the appropriate time.
755 self.display_trap = DisplayTrap(hook=self.displayhook)
757 self.display_trap = DisplayTrap(hook=self.displayhook)
756
758
757 def init_virtualenv(self):
759 def init_virtualenv(self):
758 """Add a virtualenv to sys.path so the user can import modules from it.
760 """Add a virtualenv to sys.path so the user can import modules from it.
759 This isn't perfect: it doesn't use the Python interpreter with which the
761 This isn't perfect: it doesn't use the Python interpreter with which the
760 virtualenv was built, and it ignores the --no-site-packages option. A
762 virtualenv was built, and it ignores the --no-site-packages option. A
761 warning will appear suggesting the user installs IPython in the
763 warning will appear suggesting the user installs IPython in the
762 virtualenv, but for many cases, it probably works well enough.
764 virtualenv, but for many cases, it probably works well enough.
763
765
764 Adapted from code snippets online.
766 Adapted from code snippets online.
765
767
766 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
768 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
767 """
769 """
768 if 'VIRTUAL_ENV' not in os.environ:
770 if 'VIRTUAL_ENV' not in os.environ:
769 # Not in a virtualenv
771 # Not in a virtualenv
770 return
772 return
771
773
772 # venv detection:
774 # venv detection:
773 # stdlib venv may symlink sys.executable, so we can't use realpath.
775 # stdlib venv may symlink sys.executable, so we can't use realpath.
774 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
776 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
775 # So we just check every item in the symlink tree (generally <= 3)
777 # So we just check every item in the symlink tree (generally <= 3)
776 p = os.path.normcase(sys.executable)
778 p = os.path.normcase(sys.executable)
777 paths = [p]
779 paths = [p]
778 while os.path.islink(p):
780 while os.path.islink(p):
779 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
781 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
780 paths.append(p)
782 paths.append(p)
781 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
783 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
782 if any(p.startswith(p_venv) for p in paths):
784 if any(p.startswith(p_venv) for p in paths):
783 # Running properly in the virtualenv, don't need to do anything
785 # Running properly in the virtualenv, don't need to do anything
784 return
786 return
785
787
786 warn("Attempting to work in a virtualenv. If you encounter problems, please "
788 warn("Attempting to work in a virtualenv. If you encounter problems, please "
787 "install IPython inside the virtualenv.")
789 "install IPython inside the virtualenv.")
788 if sys.platform == "win32":
790 if sys.platform == "win32":
789 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
791 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
790 else:
792 else:
791 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
793 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
792 'python%d.%d' % sys.version_info[:2], 'site-packages')
794 'python%d.%d' % sys.version_info[:2], 'site-packages')
793
795
794 import site
796 import site
795 sys.path.insert(0, virtual_env)
797 sys.path.insert(0, virtual_env)
796 site.addsitedir(virtual_env)
798 site.addsitedir(virtual_env)
797
799
798 #-------------------------------------------------------------------------
800 #-------------------------------------------------------------------------
799 # Things related to injections into the sys module
801 # Things related to injections into the sys module
800 #-------------------------------------------------------------------------
802 #-------------------------------------------------------------------------
801
803
802 def save_sys_module_state(self):
804 def save_sys_module_state(self):
803 """Save the state of hooks in the sys module.
805 """Save the state of hooks in the sys module.
804
806
805 This has to be called after self.user_module is created.
807 This has to be called after self.user_module is created.
806 """
808 """
807 self._orig_sys_module_state = {'stdin': sys.stdin,
809 self._orig_sys_module_state = {'stdin': sys.stdin,
808 'stdout': sys.stdout,
810 'stdout': sys.stdout,
809 'stderr': sys.stderr,
811 'stderr': sys.stderr,
810 'excepthook': sys.excepthook}
812 'excepthook': sys.excepthook}
811 self._orig_sys_modules_main_name = self.user_module.__name__
813 self._orig_sys_modules_main_name = self.user_module.__name__
812 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
814 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
813
815
814 def restore_sys_module_state(self):
816 def restore_sys_module_state(self):
815 """Restore the state of the sys module."""
817 """Restore the state of the sys module."""
816 try:
818 try:
817 for k, v in iteritems(self._orig_sys_module_state):
819 for k, v in iteritems(self._orig_sys_module_state):
818 setattr(sys, k, v)
820 setattr(sys, k, v)
819 except AttributeError:
821 except AttributeError:
820 pass
822 pass
821 # Reset what what done in self.init_sys_modules
823 # Reset what what done in self.init_sys_modules
822 if self._orig_sys_modules_main_mod is not None:
824 if self._orig_sys_modules_main_mod is not None:
823 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
825 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
824
826
825 #-------------------------------------------------------------------------
827 #-------------------------------------------------------------------------
826 # Things related to the banner
828 # Things related to the banner
827 #-------------------------------------------------------------------------
829 #-------------------------------------------------------------------------
828
830
829 @property
831 @property
830 def banner(self):
832 def banner(self):
831 banner = self.banner1
833 banner = self.banner1
832 if self.profile and self.profile != 'default':
834 if self.profile and self.profile != 'default':
833 banner += '\nIPython profile: %s\n' % self.profile
835 banner += '\nIPython profile: %s\n' % self.profile
834 if self.banner2:
836 if self.banner2:
835 banner += '\n' + self.banner2
837 banner += '\n' + self.banner2
836 return banner
838 return banner
837
839
838 def show_banner(self, banner=None):
840 def show_banner(self, banner=None):
839 if banner is None:
841 if banner is None:
840 banner = self.banner
842 banner = self.banner
841 self.write(banner)
843 self.write(banner)
842
844
843 #-------------------------------------------------------------------------
845 #-------------------------------------------------------------------------
844 # Things related to hooks
846 # Things related to hooks
845 #-------------------------------------------------------------------------
847 #-------------------------------------------------------------------------
846
848
847 def init_hooks(self):
849 def init_hooks(self):
848 # hooks holds pointers used for user-side customizations
850 # hooks holds pointers used for user-side customizations
849 self.hooks = Struct()
851 self.hooks = Struct()
850
852
851 self.strdispatchers = {}
853 self.strdispatchers = {}
852
854
853 # Set all default hooks, defined in the IPython.hooks module.
855 # Set all default hooks, defined in the IPython.hooks module.
854 hooks = IPython.core.hooks
856 hooks = IPython.core.hooks
855 for hook_name in hooks.__all__:
857 for hook_name in hooks.__all__:
856 # default hooks have priority 100, i.e. low; user hooks should have
858 # default hooks have priority 100, i.e. low; user hooks should have
857 # 0-100 priority
859 # 0-100 priority
858 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
860 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
859
861
860 if self.display_page:
862 if self.display_page:
861 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
863 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
862
864
863 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
865 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
864 _warn_deprecated=True):
866 _warn_deprecated=True):
865 """set_hook(name,hook) -> sets an internal IPython hook.
867 """set_hook(name,hook) -> sets an internal IPython hook.
866
868
867 IPython exposes some of its internal API as user-modifiable hooks. By
869 IPython exposes some of its internal API as user-modifiable hooks. By
868 adding your function to one of these hooks, you can modify IPython's
870 adding your function to one of these hooks, you can modify IPython's
869 behavior to call at runtime your own routines."""
871 behavior to call at runtime your own routines."""
870
872
871 # At some point in the future, this should validate the hook before it
873 # At some point in the future, this should validate the hook before it
872 # accepts it. Probably at least check that the hook takes the number
874 # accepts it. Probably at least check that the hook takes the number
873 # of args it's supposed to.
875 # of args it's supposed to.
874
876
875 f = types.MethodType(hook,self)
877 f = types.MethodType(hook,self)
876
878
877 # check if the hook is for strdispatcher first
879 # check if the hook is for strdispatcher first
878 if str_key is not None:
880 if str_key is not None:
879 sdp = self.strdispatchers.get(name, StrDispatch())
881 sdp = self.strdispatchers.get(name, StrDispatch())
880 sdp.add_s(str_key, f, priority )
882 sdp.add_s(str_key, f, priority )
881 self.strdispatchers[name] = sdp
883 self.strdispatchers[name] = sdp
882 return
884 return
883 if re_key is not None:
885 if re_key is not None:
884 sdp = self.strdispatchers.get(name, StrDispatch())
886 sdp = self.strdispatchers.get(name, StrDispatch())
885 sdp.add_re(re.compile(re_key), f, priority )
887 sdp.add_re(re.compile(re_key), f, priority )
886 self.strdispatchers[name] = sdp
888 self.strdispatchers[name] = sdp
887 return
889 return
888
890
889 dp = getattr(self.hooks, name, None)
891 dp = getattr(self.hooks, name, None)
890 if name not in IPython.core.hooks.__all__:
892 if name not in IPython.core.hooks.__all__:
891 print("Warning! Hook '%s' is not one of %s" % \
893 print("Warning! Hook '%s' is not one of %s" % \
892 (name, IPython.core.hooks.__all__ ))
894 (name, IPython.core.hooks.__all__ ))
893
895
894 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
896 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
895 alternative = IPython.core.hooks.deprecated[name]
897 alternative = IPython.core.hooks.deprecated[name]
896 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
898 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
897
899
898 if not dp:
900 if not dp:
899 dp = IPython.core.hooks.CommandChainDispatcher()
901 dp = IPython.core.hooks.CommandChainDispatcher()
900
902
901 try:
903 try:
902 dp.add(f,priority)
904 dp.add(f,priority)
903 except AttributeError:
905 except AttributeError:
904 # it was not commandchain, plain old func - replace
906 # it was not commandchain, plain old func - replace
905 dp = f
907 dp = f
906
908
907 setattr(self.hooks,name, dp)
909 setattr(self.hooks,name, dp)
908
910
909 #-------------------------------------------------------------------------
911 #-------------------------------------------------------------------------
910 # Things related to events
912 # Things related to events
911 #-------------------------------------------------------------------------
913 #-------------------------------------------------------------------------
912
914
913 def init_events(self):
915 def init_events(self):
914 self.events = EventManager(self, available_events)
916 self.events = EventManager(self, available_events)
915
917
916 self.events.register("pre_execute", self._clear_warning_registry)
918 self.events.register("pre_execute", self._clear_warning_registry)
917
919
918 def register_post_execute(self, func):
920 def register_post_execute(self, func):
919 """DEPRECATED: Use ip.events.register('post_run_cell', func)
921 """DEPRECATED: Use ip.events.register('post_run_cell', func)
920
922
921 Register a function for calling after code execution.
923 Register a function for calling after code execution.
922 """
924 """
923 warn("ip.register_post_execute is deprecated, use "
925 warn("ip.register_post_execute is deprecated, use "
924 "ip.events.register('post_run_cell', func) instead.")
926 "ip.events.register('post_run_cell', func) instead.")
925 self.events.register('post_run_cell', func)
927 self.events.register('post_run_cell', func)
926
928
927 def _clear_warning_registry(self):
929 def _clear_warning_registry(self):
928 # clear the warning registry, so that different code blocks with
930 # clear the warning registry, so that different code blocks with
929 # overlapping line number ranges don't cause spurious suppression of
931 # overlapping line number ranges don't cause spurious suppression of
930 # warnings (see gh-6611 for details)
932 # warnings (see gh-6611 for details)
931 if "__warningregistry__" in self.user_global_ns:
933 if "__warningregistry__" in self.user_global_ns:
932 del self.user_global_ns["__warningregistry__"]
934 del self.user_global_ns["__warningregistry__"]
933
935
934 #-------------------------------------------------------------------------
936 #-------------------------------------------------------------------------
935 # Things related to the "main" module
937 # Things related to the "main" module
936 #-------------------------------------------------------------------------
938 #-------------------------------------------------------------------------
937
939
938 def new_main_mod(self, filename, modname):
940 def new_main_mod(self, filename, modname):
939 """Return a new 'main' module object for user code execution.
941 """Return a new 'main' module object for user code execution.
940
942
941 ``filename`` should be the path of the script which will be run in the
943 ``filename`` should be the path of the script which will be run in the
942 module. Requests with the same filename will get the same module, with
944 module. Requests with the same filename will get the same module, with
943 its namespace cleared.
945 its namespace cleared.
944
946
945 ``modname`` should be the module name - normally either '__main__' or
947 ``modname`` should be the module name - normally either '__main__' or
946 the basename of the file without the extension.
948 the basename of the file without the extension.
947
949
948 When scripts are executed via %run, we must keep a reference to their
950 When scripts are executed via %run, we must keep a reference to their
949 __main__ module around so that Python doesn't
951 __main__ module around so that Python doesn't
950 clear it, rendering references to module globals useless.
952 clear it, rendering references to module globals useless.
951
953
952 This method keeps said reference in a private dict, keyed by the
954 This method keeps said reference in a private dict, keyed by the
953 absolute path of the script. This way, for multiple executions of the
955 absolute path of the script. This way, for multiple executions of the
954 same script we only keep one copy of the namespace (the last one),
956 same script we only keep one copy of the namespace (the last one),
955 thus preventing memory leaks from old references while allowing the
957 thus preventing memory leaks from old references while allowing the
956 objects from the last execution to be accessible.
958 objects from the last execution to be accessible.
957 """
959 """
958 filename = os.path.abspath(filename)
960 filename = os.path.abspath(filename)
959 try:
961 try:
960 main_mod = self._main_mod_cache[filename]
962 main_mod = self._main_mod_cache[filename]
961 except KeyError:
963 except KeyError:
962 main_mod = self._main_mod_cache[filename] = types.ModuleType(
964 main_mod = self._main_mod_cache[filename] = types.ModuleType(
963 py3compat.cast_bytes_py2(modname),
965 py3compat.cast_bytes_py2(modname),
964 doc="Module created for script run in IPython")
966 doc="Module created for script run in IPython")
965 else:
967 else:
966 main_mod.__dict__.clear()
968 main_mod.__dict__.clear()
967 main_mod.__name__ = modname
969 main_mod.__name__ = modname
968
970
969 main_mod.__file__ = filename
971 main_mod.__file__ = filename
970 # It seems pydoc (and perhaps others) needs any module instance to
972 # It seems pydoc (and perhaps others) needs any module instance to
971 # implement a __nonzero__ method
973 # implement a __nonzero__ method
972 main_mod.__nonzero__ = lambda : True
974 main_mod.__nonzero__ = lambda : True
973
975
974 return main_mod
976 return main_mod
975
977
976 def clear_main_mod_cache(self):
978 def clear_main_mod_cache(self):
977 """Clear the cache of main modules.
979 """Clear the cache of main modules.
978
980
979 Mainly for use by utilities like %reset.
981 Mainly for use by utilities like %reset.
980
982
981 Examples
983 Examples
982 --------
984 --------
983
985
984 In [15]: import IPython
986 In [15]: import IPython
985
987
986 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
988 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
987
989
988 In [17]: len(_ip._main_mod_cache) > 0
990 In [17]: len(_ip._main_mod_cache) > 0
989 Out[17]: True
991 Out[17]: True
990
992
991 In [18]: _ip.clear_main_mod_cache()
993 In [18]: _ip.clear_main_mod_cache()
992
994
993 In [19]: len(_ip._main_mod_cache) == 0
995 In [19]: len(_ip._main_mod_cache) == 0
994 Out[19]: True
996 Out[19]: True
995 """
997 """
996 self._main_mod_cache.clear()
998 self._main_mod_cache.clear()
997
999
998 #-------------------------------------------------------------------------
1000 #-------------------------------------------------------------------------
999 # Things related to debugging
1001 # Things related to debugging
1000 #-------------------------------------------------------------------------
1002 #-------------------------------------------------------------------------
1001
1003
1002 def init_pdb(self):
1004 def init_pdb(self):
1003 # Set calling of pdb on exceptions
1005 # Set calling of pdb on exceptions
1004 # self.call_pdb is a property
1006 # self.call_pdb is a property
1005 self.call_pdb = self.pdb
1007 self.call_pdb = self.pdb
1006
1008
1007 def _get_call_pdb(self):
1009 def _get_call_pdb(self):
1008 return self._call_pdb
1010 return self._call_pdb
1009
1011
1010 def _set_call_pdb(self,val):
1012 def _set_call_pdb(self,val):
1011
1013
1012 if val not in (0,1,False,True):
1014 if val not in (0,1,False,True):
1013 raise ValueError('new call_pdb value must be boolean')
1015 raise ValueError('new call_pdb value must be boolean')
1014
1016
1015 # store value in instance
1017 # store value in instance
1016 self._call_pdb = val
1018 self._call_pdb = val
1017
1019
1018 # notify the actual exception handlers
1020 # notify the actual exception handlers
1019 self.InteractiveTB.call_pdb = val
1021 self.InteractiveTB.call_pdb = val
1020
1022
1021 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1023 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1022 'Control auto-activation of pdb at exceptions')
1024 'Control auto-activation of pdb at exceptions')
1023
1025
1024 def debugger(self,force=False):
1026 def debugger(self,force=False):
1025 """Call the pydb/pdb debugger.
1027 """Call the pydb/pdb debugger.
1026
1028
1027 Keywords:
1029 Keywords:
1028
1030
1029 - force(False): by default, this routine checks the instance call_pdb
1031 - force(False): by default, this routine checks the instance call_pdb
1030 flag and does not actually invoke the debugger if the flag is false.
1032 flag and does not actually invoke the debugger if the flag is false.
1031 The 'force' option forces the debugger to activate even if the flag
1033 The 'force' option forces the debugger to activate even if the flag
1032 is false.
1034 is false.
1033 """
1035 """
1034
1036
1035 if not (force or self.call_pdb):
1037 if not (force or self.call_pdb):
1036 return
1038 return
1037
1039
1038 if not hasattr(sys,'last_traceback'):
1040 if not hasattr(sys,'last_traceback'):
1039 error('No traceback has been produced, nothing to debug.')
1041 error('No traceback has been produced, nothing to debug.')
1040 return
1042 return
1041
1043
1042 # use pydb if available
1044 # use pydb if available
1043 if debugger.has_pydb:
1045 if debugger.has_pydb:
1044 from pydb import pm
1046 from pydb import pm
1045 else:
1047 else:
1046 # fallback to our internal debugger
1048 # fallback to our internal debugger
1047 pm = lambda : self.InteractiveTB.debugger(force=True)
1049 pm = lambda : self.InteractiveTB.debugger(force=True)
1048
1050
1049 with self.readline_no_record:
1051 with self.readline_no_record:
1050 pm()
1052 pm()
1051
1053
1052 #-------------------------------------------------------------------------
1054 #-------------------------------------------------------------------------
1053 # Things related to IPython's various namespaces
1055 # Things related to IPython's various namespaces
1054 #-------------------------------------------------------------------------
1056 #-------------------------------------------------------------------------
1055 default_user_namespaces = True
1057 default_user_namespaces = True
1056
1058
1057 def init_create_namespaces(self, user_module=None, user_ns=None):
1059 def init_create_namespaces(self, user_module=None, user_ns=None):
1058 # Create the namespace where the user will operate. user_ns is
1060 # Create the namespace where the user will operate. user_ns is
1059 # normally the only one used, and it is passed to the exec calls as
1061 # normally the only one used, and it is passed to the exec calls as
1060 # the locals argument. But we do carry a user_global_ns namespace
1062 # the locals argument. But we do carry a user_global_ns namespace
1061 # given as the exec 'globals' argument, This is useful in embedding
1063 # given as the exec 'globals' argument, This is useful in embedding
1062 # situations where the ipython shell opens in a context where the
1064 # situations where the ipython shell opens in a context where the
1063 # distinction between locals and globals is meaningful. For
1065 # distinction between locals and globals is meaningful. For
1064 # non-embedded contexts, it is just the same object as the user_ns dict.
1066 # non-embedded contexts, it is just the same object as the user_ns dict.
1065
1067
1066 # FIXME. For some strange reason, __builtins__ is showing up at user
1068 # FIXME. For some strange reason, __builtins__ is showing up at user
1067 # level as a dict instead of a module. This is a manual fix, but I
1069 # level as a dict instead of a module. This is a manual fix, but I
1068 # should really track down where the problem is coming from. Alex
1070 # should really track down where the problem is coming from. Alex
1069 # Schmolck reported this problem first.
1071 # Schmolck reported this problem first.
1070
1072
1071 # A useful post by Alex Martelli on this topic:
1073 # A useful post by Alex Martelli on this topic:
1072 # Re: inconsistent value from __builtins__
1074 # Re: inconsistent value from __builtins__
1073 # Von: Alex Martelli <aleaxit@yahoo.com>
1075 # Von: Alex Martelli <aleaxit@yahoo.com>
1074 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1076 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1075 # Gruppen: comp.lang.python
1077 # Gruppen: comp.lang.python
1076
1078
1077 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1079 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1078 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1080 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1079 # > <type 'dict'>
1081 # > <type 'dict'>
1080 # > >>> print type(__builtins__)
1082 # > >>> print type(__builtins__)
1081 # > <type 'module'>
1083 # > <type 'module'>
1082 # > Is this difference in return value intentional?
1084 # > Is this difference in return value intentional?
1083
1085
1084 # Well, it's documented that '__builtins__' can be either a dictionary
1086 # Well, it's documented that '__builtins__' can be either a dictionary
1085 # or a module, and it's been that way for a long time. Whether it's
1087 # or a module, and it's been that way for a long time. Whether it's
1086 # intentional (or sensible), I don't know. In any case, the idea is
1088 # intentional (or sensible), I don't know. In any case, the idea is
1087 # that if you need to access the built-in namespace directly, you
1089 # that if you need to access the built-in namespace directly, you
1088 # should start with "import __builtin__" (note, no 's') which will
1090 # should start with "import __builtin__" (note, no 's') which will
1089 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1091 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1090
1092
1091 # These routines return a properly built module and dict as needed by
1093 # These routines return a properly built module and dict as needed by
1092 # the rest of the code, and can also be used by extension writers to
1094 # the rest of the code, and can also be used by extension writers to
1093 # generate properly initialized namespaces.
1095 # generate properly initialized namespaces.
1094 if (user_ns is not None) or (user_module is not None):
1096 if (user_ns is not None) or (user_module is not None):
1095 self.default_user_namespaces = False
1097 self.default_user_namespaces = False
1096 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1098 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1097
1099
1098 # A record of hidden variables we have added to the user namespace, so
1100 # A record of hidden variables we have added to the user namespace, so
1099 # we can list later only variables defined in actual interactive use.
1101 # we can list later only variables defined in actual interactive use.
1100 self.user_ns_hidden = {}
1102 self.user_ns_hidden = {}
1101
1103
1102 # Now that FakeModule produces a real module, we've run into a nasty
1104 # Now that FakeModule produces a real module, we've run into a nasty
1103 # problem: after script execution (via %run), the module where the user
1105 # problem: after script execution (via %run), the module where the user
1104 # code ran is deleted. Now that this object is a true module (needed
1106 # code ran is deleted. Now that this object is a true module (needed
1105 # so doctest and other tools work correctly), the Python module
1107 # so doctest and other tools work correctly), the Python module
1106 # teardown mechanism runs over it, and sets to None every variable
1108 # teardown mechanism runs over it, and sets to None every variable
1107 # present in that module. Top-level references to objects from the
1109 # present in that module. Top-level references to objects from the
1108 # script survive, because the user_ns is updated with them. However,
1110 # script survive, because the user_ns is updated with them. However,
1109 # calling functions defined in the script that use other things from
1111 # calling functions defined in the script that use other things from
1110 # the script will fail, because the function's closure had references
1112 # the script will fail, because the function's closure had references
1111 # to the original objects, which are now all None. So we must protect
1113 # to the original objects, which are now all None. So we must protect
1112 # these modules from deletion by keeping a cache.
1114 # these modules from deletion by keeping a cache.
1113 #
1115 #
1114 # To avoid keeping stale modules around (we only need the one from the
1116 # To avoid keeping stale modules around (we only need the one from the
1115 # last run), we use a dict keyed with the full path to the script, so
1117 # last run), we use a dict keyed with the full path to the script, so
1116 # only the last version of the module is held in the cache. Note,
1118 # only the last version of the module is held in the cache. Note,
1117 # however, that we must cache the module *namespace contents* (their
1119 # however, that we must cache the module *namespace contents* (their
1118 # __dict__). Because if we try to cache the actual modules, old ones
1120 # __dict__). Because if we try to cache the actual modules, old ones
1119 # (uncached) could be destroyed while still holding references (such as
1121 # (uncached) could be destroyed while still holding references (such as
1120 # those held by GUI objects that tend to be long-lived)>
1122 # those held by GUI objects that tend to be long-lived)>
1121 #
1123 #
1122 # The %reset command will flush this cache. See the cache_main_mod()
1124 # The %reset command will flush this cache. See the cache_main_mod()
1123 # and clear_main_mod_cache() methods for details on use.
1125 # and clear_main_mod_cache() methods for details on use.
1124
1126
1125 # This is the cache used for 'main' namespaces
1127 # This is the cache used for 'main' namespaces
1126 self._main_mod_cache = {}
1128 self._main_mod_cache = {}
1127
1129
1128 # A table holding all the namespaces IPython deals with, so that
1130 # A table holding all the namespaces IPython deals with, so that
1129 # introspection facilities can search easily.
1131 # introspection facilities can search easily.
1130 self.ns_table = {'user_global':self.user_module.__dict__,
1132 self.ns_table = {'user_global':self.user_module.__dict__,
1131 'user_local':self.user_ns,
1133 'user_local':self.user_ns,
1132 'builtin':builtin_mod.__dict__
1134 'builtin':builtin_mod.__dict__
1133 }
1135 }
1134
1136
1135 @property
1137 @property
1136 def user_global_ns(self):
1138 def user_global_ns(self):
1137 return self.user_module.__dict__
1139 return self.user_module.__dict__
1138
1140
1139 def prepare_user_module(self, user_module=None, user_ns=None):
1141 def prepare_user_module(self, user_module=None, user_ns=None):
1140 """Prepare the module and namespace in which user code will be run.
1142 """Prepare the module and namespace in which user code will be run.
1141
1143
1142 When IPython is started normally, both parameters are None: a new module
1144 When IPython is started normally, both parameters are None: a new module
1143 is created automatically, and its __dict__ used as the namespace.
1145 is created automatically, and its __dict__ used as the namespace.
1144
1146
1145 If only user_module is provided, its __dict__ is used as the namespace.
1147 If only user_module is provided, its __dict__ is used as the namespace.
1146 If only user_ns is provided, a dummy module is created, and user_ns
1148 If only user_ns is provided, a dummy module is created, and user_ns
1147 becomes the global namespace. If both are provided (as they may be
1149 becomes the global namespace. If both are provided (as they may be
1148 when embedding), user_ns is the local namespace, and user_module
1150 when embedding), user_ns is the local namespace, and user_module
1149 provides the global namespace.
1151 provides the global namespace.
1150
1152
1151 Parameters
1153 Parameters
1152 ----------
1154 ----------
1153 user_module : module, optional
1155 user_module : module, optional
1154 The current user module in which IPython is being run. If None,
1156 The current user module in which IPython is being run. If None,
1155 a clean module will be created.
1157 a clean module will be created.
1156 user_ns : dict, optional
1158 user_ns : dict, optional
1157 A namespace in which to run interactive commands.
1159 A namespace in which to run interactive commands.
1158
1160
1159 Returns
1161 Returns
1160 -------
1162 -------
1161 A tuple of user_module and user_ns, each properly initialised.
1163 A tuple of user_module and user_ns, each properly initialised.
1162 """
1164 """
1163 if user_module is None and user_ns is not None:
1165 if user_module is None and user_ns is not None:
1164 user_ns.setdefault("__name__", "__main__")
1166 user_ns.setdefault("__name__", "__main__")
1165 user_module = DummyMod()
1167 user_module = DummyMod()
1166 user_module.__dict__ = user_ns
1168 user_module.__dict__ = user_ns
1167
1169
1168 if user_module is None:
1170 if user_module is None:
1169 user_module = types.ModuleType("__main__",
1171 user_module = types.ModuleType("__main__",
1170 doc="Automatically created module for IPython interactive environment")
1172 doc="Automatically created module for IPython interactive environment")
1171
1173
1172 # We must ensure that __builtin__ (without the final 's') is always
1174 # We must ensure that __builtin__ (without the final 's') is always
1173 # available and pointing to the __builtin__ *module*. For more details:
1175 # available and pointing to the __builtin__ *module*. For more details:
1174 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1176 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1175 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1177 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1176 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1178 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1177
1179
1178 if user_ns is None:
1180 if user_ns is None:
1179 user_ns = user_module.__dict__
1181 user_ns = user_module.__dict__
1180
1182
1181 return user_module, user_ns
1183 return user_module, user_ns
1182
1184
1183 def init_sys_modules(self):
1185 def init_sys_modules(self):
1184 # We need to insert into sys.modules something that looks like a
1186 # We need to insert into sys.modules something that looks like a
1185 # module but which accesses the IPython namespace, for shelve and
1187 # module but which accesses the IPython namespace, for shelve and
1186 # pickle to work interactively. Normally they rely on getting
1188 # pickle to work interactively. Normally they rely on getting
1187 # everything out of __main__, but for embedding purposes each IPython
1189 # everything out of __main__, but for embedding purposes each IPython
1188 # instance has its own private namespace, so we can't go shoving
1190 # instance has its own private namespace, so we can't go shoving
1189 # everything into __main__.
1191 # everything into __main__.
1190
1192
1191 # note, however, that we should only do this for non-embedded
1193 # note, however, that we should only do this for non-embedded
1192 # ipythons, which really mimic the __main__.__dict__ with their own
1194 # ipythons, which really mimic the __main__.__dict__ with their own
1193 # namespace. Embedded instances, on the other hand, should not do
1195 # namespace. Embedded instances, on the other hand, should not do
1194 # this because they need to manage the user local/global namespaces
1196 # this because they need to manage the user local/global namespaces
1195 # only, but they live within a 'normal' __main__ (meaning, they
1197 # only, but they live within a 'normal' __main__ (meaning, they
1196 # shouldn't overtake the execution environment of the script they're
1198 # shouldn't overtake the execution environment of the script they're
1197 # embedded in).
1199 # embedded in).
1198
1200
1199 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1201 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1200 main_name = self.user_module.__name__
1202 main_name = self.user_module.__name__
1201 sys.modules[main_name] = self.user_module
1203 sys.modules[main_name] = self.user_module
1202
1204
1203 def init_user_ns(self):
1205 def init_user_ns(self):
1204 """Initialize all user-visible namespaces to their minimum defaults.
1206 """Initialize all user-visible namespaces to their minimum defaults.
1205
1207
1206 Certain history lists are also initialized here, as they effectively
1208 Certain history lists are also initialized here, as they effectively
1207 act as user namespaces.
1209 act as user namespaces.
1208
1210
1209 Notes
1211 Notes
1210 -----
1212 -----
1211 All data structures here are only filled in, they are NOT reset by this
1213 All data structures here are only filled in, they are NOT reset by this
1212 method. If they were not empty before, data will simply be added to
1214 method. If they were not empty before, data will simply be added to
1213 therm.
1215 therm.
1214 """
1216 """
1215 # This function works in two parts: first we put a few things in
1217 # This function works in two parts: first we put a few things in
1216 # user_ns, and we sync that contents into user_ns_hidden so that these
1218 # user_ns, and we sync that contents into user_ns_hidden so that these
1217 # initial variables aren't shown by %who. After the sync, we add the
1219 # initial variables aren't shown by %who. After the sync, we add the
1218 # rest of what we *do* want the user to see with %who even on a new
1220 # rest of what we *do* want the user to see with %who even on a new
1219 # session (probably nothing, so they really only see their own stuff)
1221 # session (probably nothing, so they really only see their own stuff)
1220
1222
1221 # The user dict must *always* have a __builtin__ reference to the
1223 # The user dict must *always* have a __builtin__ reference to the
1222 # Python standard __builtin__ namespace, which must be imported.
1224 # Python standard __builtin__ namespace, which must be imported.
1223 # This is so that certain operations in prompt evaluation can be
1225 # This is so that certain operations in prompt evaluation can be
1224 # reliably executed with builtins. Note that we can NOT use
1226 # reliably executed with builtins. Note that we can NOT use
1225 # __builtins__ (note the 's'), because that can either be a dict or a
1227 # __builtins__ (note the 's'), because that can either be a dict or a
1226 # module, and can even mutate at runtime, depending on the context
1228 # module, and can even mutate at runtime, depending on the context
1227 # (Python makes no guarantees on it). In contrast, __builtin__ is
1229 # (Python makes no guarantees on it). In contrast, __builtin__ is
1228 # always a module object, though it must be explicitly imported.
1230 # always a module object, though it must be explicitly imported.
1229
1231
1230 # For more details:
1232 # For more details:
1231 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1233 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1232 ns = dict()
1234 ns = dict()
1233
1235
1234 # make global variables for user access to the histories
1236 # make global variables for user access to the histories
1235 ns['_ih'] = self.history_manager.input_hist_parsed
1237 ns['_ih'] = self.history_manager.input_hist_parsed
1236 ns['_oh'] = self.history_manager.output_hist
1238 ns['_oh'] = self.history_manager.output_hist
1237 ns['_dh'] = self.history_manager.dir_hist
1239 ns['_dh'] = self.history_manager.dir_hist
1238
1240
1239 ns['_sh'] = shadowns
1241 ns['_sh'] = shadowns
1240
1242
1241 # user aliases to input and output histories. These shouldn't show up
1243 # user aliases to input and output histories. These shouldn't show up
1242 # in %who, as they can have very large reprs.
1244 # in %who, as they can have very large reprs.
1243 ns['In'] = self.history_manager.input_hist_parsed
1245 ns['In'] = self.history_manager.input_hist_parsed
1244 ns['Out'] = self.history_manager.output_hist
1246 ns['Out'] = self.history_manager.output_hist
1245
1247
1246 # Store myself as the public api!!!
1248 # Store myself as the public api!!!
1247 ns['get_ipython'] = self.get_ipython
1249 ns['get_ipython'] = self.get_ipython
1248
1250
1249 ns['exit'] = self.exiter
1251 ns['exit'] = self.exiter
1250 ns['quit'] = self.exiter
1252 ns['quit'] = self.exiter
1251
1253
1252 # Sync what we've added so far to user_ns_hidden so these aren't seen
1254 # Sync what we've added so far to user_ns_hidden so these aren't seen
1253 # by %who
1255 # by %who
1254 self.user_ns_hidden.update(ns)
1256 self.user_ns_hidden.update(ns)
1255
1257
1256 # Anything put into ns now would show up in %who. Think twice before
1258 # Anything put into ns now would show up in %who. Think twice before
1257 # putting anything here, as we really want %who to show the user their
1259 # putting anything here, as we really want %who to show the user their
1258 # stuff, not our variables.
1260 # stuff, not our variables.
1259
1261
1260 # Finally, update the real user's namespace
1262 # Finally, update the real user's namespace
1261 self.user_ns.update(ns)
1263 self.user_ns.update(ns)
1262
1264
1263 @property
1265 @property
1264 def all_ns_refs(self):
1266 def all_ns_refs(self):
1265 """Get a list of references to all the namespace dictionaries in which
1267 """Get a list of references to all the namespace dictionaries in which
1266 IPython might store a user-created object.
1268 IPython might store a user-created object.
1267
1269
1268 Note that this does not include the displayhook, which also caches
1270 Note that this does not include the displayhook, which also caches
1269 objects from the output."""
1271 objects from the output."""
1270 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1272 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1271 [m.__dict__ for m in self._main_mod_cache.values()]
1273 [m.__dict__ for m in self._main_mod_cache.values()]
1272
1274
1273 def reset(self, new_session=True):
1275 def reset(self, new_session=True):
1274 """Clear all internal namespaces, and attempt to release references to
1276 """Clear all internal namespaces, and attempt to release references to
1275 user objects.
1277 user objects.
1276
1278
1277 If new_session is True, a new history session will be opened.
1279 If new_session is True, a new history session will be opened.
1278 """
1280 """
1279 # Clear histories
1281 # Clear histories
1280 self.history_manager.reset(new_session)
1282 self.history_manager.reset(new_session)
1281 # Reset counter used to index all histories
1283 # Reset counter used to index all histories
1282 if new_session:
1284 if new_session:
1283 self.execution_count = 1
1285 self.execution_count = 1
1284
1286
1285 # Flush cached output items
1287 # Flush cached output items
1286 if self.displayhook.do_full_cache:
1288 if self.displayhook.do_full_cache:
1287 self.displayhook.flush()
1289 self.displayhook.flush()
1288
1290
1289 # The main execution namespaces must be cleared very carefully,
1291 # The main execution namespaces must be cleared very carefully,
1290 # skipping the deletion of the builtin-related keys, because doing so
1292 # skipping the deletion of the builtin-related keys, because doing so
1291 # would cause errors in many object's __del__ methods.
1293 # would cause errors in many object's __del__ methods.
1292 if self.user_ns is not self.user_global_ns:
1294 if self.user_ns is not self.user_global_ns:
1293 self.user_ns.clear()
1295 self.user_ns.clear()
1294 ns = self.user_global_ns
1296 ns = self.user_global_ns
1295 drop_keys = set(ns.keys())
1297 drop_keys = set(ns.keys())
1296 drop_keys.discard('__builtin__')
1298 drop_keys.discard('__builtin__')
1297 drop_keys.discard('__builtins__')
1299 drop_keys.discard('__builtins__')
1298 drop_keys.discard('__name__')
1300 drop_keys.discard('__name__')
1299 for k in drop_keys:
1301 for k in drop_keys:
1300 del ns[k]
1302 del ns[k]
1301
1303
1302 self.user_ns_hidden.clear()
1304 self.user_ns_hidden.clear()
1303
1305
1304 # Restore the user namespaces to minimal usability
1306 # Restore the user namespaces to minimal usability
1305 self.init_user_ns()
1307 self.init_user_ns()
1306
1308
1307 # Restore the default and user aliases
1309 # Restore the default and user aliases
1308 self.alias_manager.clear_aliases()
1310 self.alias_manager.clear_aliases()
1309 self.alias_manager.init_aliases()
1311 self.alias_manager.init_aliases()
1310
1312
1311 # Flush the private list of module references kept for script
1313 # Flush the private list of module references kept for script
1312 # execution protection
1314 # execution protection
1313 self.clear_main_mod_cache()
1315 self.clear_main_mod_cache()
1314
1316
1315 def del_var(self, varname, by_name=False):
1317 def del_var(self, varname, by_name=False):
1316 """Delete a variable from the various namespaces, so that, as
1318 """Delete a variable from the various namespaces, so that, as
1317 far as possible, we're not keeping any hidden references to it.
1319 far as possible, we're not keeping any hidden references to it.
1318
1320
1319 Parameters
1321 Parameters
1320 ----------
1322 ----------
1321 varname : str
1323 varname : str
1322 The name of the variable to delete.
1324 The name of the variable to delete.
1323 by_name : bool
1325 by_name : bool
1324 If True, delete variables with the given name in each
1326 If True, delete variables with the given name in each
1325 namespace. If False (default), find the variable in the user
1327 namespace. If False (default), find the variable in the user
1326 namespace, and delete references to it.
1328 namespace, and delete references to it.
1327 """
1329 """
1328 if varname in ('__builtin__', '__builtins__'):
1330 if varname in ('__builtin__', '__builtins__'):
1329 raise ValueError("Refusing to delete %s" % varname)
1331 raise ValueError("Refusing to delete %s" % varname)
1330
1332
1331 ns_refs = self.all_ns_refs
1333 ns_refs = self.all_ns_refs
1332
1334
1333 if by_name: # Delete by name
1335 if by_name: # Delete by name
1334 for ns in ns_refs:
1336 for ns in ns_refs:
1335 try:
1337 try:
1336 del ns[varname]
1338 del ns[varname]
1337 except KeyError:
1339 except KeyError:
1338 pass
1340 pass
1339 else: # Delete by object
1341 else: # Delete by object
1340 try:
1342 try:
1341 obj = self.user_ns[varname]
1343 obj = self.user_ns[varname]
1342 except KeyError:
1344 except KeyError:
1343 raise NameError("name '%s' is not defined" % varname)
1345 raise NameError("name '%s' is not defined" % varname)
1344 # Also check in output history
1346 # Also check in output history
1345 ns_refs.append(self.history_manager.output_hist)
1347 ns_refs.append(self.history_manager.output_hist)
1346 for ns in ns_refs:
1348 for ns in ns_refs:
1347 to_delete = [n for n, o in iteritems(ns) if o is obj]
1349 to_delete = [n for n, o in iteritems(ns) if o is obj]
1348 for name in to_delete:
1350 for name in to_delete:
1349 del ns[name]
1351 del ns[name]
1350
1352
1351 # displayhook keeps extra references, but not in a dictionary
1353 # displayhook keeps extra references, but not in a dictionary
1352 for name in ('_', '__', '___'):
1354 for name in ('_', '__', '___'):
1353 if getattr(self.displayhook, name) is obj:
1355 if getattr(self.displayhook, name) is obj:
1354 setattr(self.displayhook, name, None)
1356 setattr(self.displayhook, name, None)
1355
1357
1356 def reset_selective(self, regex=None):
1358 def reset_selective(self, regex=None):
1357 """Clear selective variables from internal namespaces based on a
1359 """Clear selective variables from internal namespaces based on a
1358 specified regular expression.
1360 specified regular expression.
1359
1361
1360 Parameters
1362 Parameters
1361 ----------
1363 ----------
1362 regex : string or compiled pattern, optional
1364 regex : string or compiled pattern, optional
1363 A regular expression pattern that will be used in searching
1365 A regular expression pattern that will be used in searching
1364 variable names in the users namespaces.
1366 variable names in the users namespaces.
1365 """
1367 """
1366 if regex is not None:
1368 if regex is not None:
1367 try:
1369 try:
1368 m = re.compile(regex)
1370 m = re.compile(regex)
1369 except TypeError:
1371 except TypeError:
1370 raise TypeError('regex must be a string or compiled pattern')
1372 raise TypeError('regex must be a string or compiled pattern')
1371 # Search for keys in each namespace that match the given regex
1373 # Search for keys in each namespace that match the given regex
1372 # If a match is found, delete the key/value pair.
1374 # If a match is found, delete the key/value pair.
1373 for ns in self.all_ns_refs:
1375 for ns in self.all_ns_refs:
1374 for var in ns:
1376 for var in ns:
1375 if m.search(var):
1377 if m.search(var):
1376 del ns[var]
1378 del ns[var]
1377
1379
1378 def push(self, variables, interactive=True):
1380 def push(self, variables, interactive=True):
1379 """Inject a group of variables into the IPython user namespace.
1381 """Inject a group of variables into the IPython user namespace.
1380
1382
1381 Parameters
1383 Parameters
1382 ----------
1384 ----------
1383 variables : dict, str or list/tuple of str
1385 variables : dict, str or list/tuple of str
1384 The variables to inject into the user's namespace. If a dict, a
1386 The variables to inject into the user's namespace. If a dict, a
1385 simple update is done. If a str, the string is assumed to have
1387 simple update is done. If a str, the string is assumed to have
1386 variable names separated by spaces. A list/tuple of str can also
1388 variable names separated by spaces. A list/tuple of str can also
1387 be used to give the variable names. If just the variable names are
1389 be used to give the variable names. If just the variable names are
1388 give (list/tuple/str) then the variable values looked up in the
1390 give (list/tuple/str) then the variable values looked up in the
1389 callers frame.
1391 callers frame.
1390 interactive : bool
1392 interactive : bool
1391 If True (default), the variables will be listed with the ``who``
1393 If True (default), the variables will be listed with the ``who``
1392 magic.
1394 magic.
1393 """
1395 """
1394 vdict = None
1396 vdict = None
1395
1397
1396 # We need a dict of name/value pairs to do namespace updates.
1398 # We need a dict of name/value pairs to do namespace updates.
1397 if isinstance(variables, dict):
1399 if isinstance(variables, dict):
1398 vdict = variables
1400 vdict = variables
1399 elif isinstance(variables, string_types+(list, tuple)):
1401 elif isinstance(variables, string_types+(list, tuple)):
1400 if isinstance(variables, string_types):
1402 if isinstance(variables, string_types):
1401 vlist = variables.split()
1403 vlist = variables.split()
1402 else:
1404 else:
1403 vlist = variables
1405 vlist = variables
1404 vdict = {}
1406 vdict = {}
1405 cf = sys._getframe(1)
1407 cf = sys._getframe(1)
1406 for name in vlist:
1408 for name in vlist:
1407 try:
1409 try:
1408 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1410 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1409 except:
1411 except:
1410 print('Could not get variable %s from %s' %
1412 print('Could not get variable %s from %s' %
1411 (name,cf.f_code.co_name))
1413 (name,cf.f_code.co_name))
1412 else:
1414 else:
1413 raise ValueError('variables must be a dict/str/list/tuple')
1415 raise ValueError('variables must be a dict/str/list/tuple')
1414
1416
1415 # Propagate variables to user namespace
1417 # Propagate variables to user namespace
1416 self.user_ns.update(vdict)
1418 self.user_ns.update(vdict)
1417
1419
1418 # And configure interactive visibility
1420 # And configure interactive visibility
1419 user_ns_hidden = self.user_ns_hidden
1421 user_ns_hidden = self.user_ns_hidden
1420 if interactive:
1422 if interactive:
1421 for name in vdict:
1423 for name in vdict:
1422 user_ns_hidden.pop(name, None)
1424 user_ns_hidden.pop(name, None)
1423 else:
1425 else:
1424 user_ns_hidden.update(vdict)
1426 user_ns_hidden.update(vdict)
1425
1427
1426 def drop_by_id(self, variables):
1428 def drop_by_id(self, variables):
1427 """Remove a dict of variables from the user namespace, if they are the
1429 """Remove a dict of variables from the user namespace, if they are the
1428 same as the values in the dictionary.
1430 same as the values in the dictionary.
1429
1431
1430 This is intended for use by extensions: variables that they've added can
1432 This is intended for use by extensions: variables that they've added can
1431 be taken back out if they are unloaded, without removing any that the
1433 be taken back out if they are unloaded, without removing any that the
1432 user has overwritten.
1434 user has overwritten.
1433
1435
1434 Parameters
1436 Parameters
1435 ----------
1437 ----------
1436 variables : dict
1438 variables : dict
1437 A dictionary mapping object names (as strings) to the objects.
1439 A dictionary mapping object names (as strings) to the objects.
1438 """
1440 """
1439 for name, obj in iteritems(variables):
1441 for name, obj in iteritems(variables):
1440 if name in self.user_ns and self.user_ns[name] is obj:
1442 if name in self.user_ns and self.user_ns[name] is obj:
1441 del self.user_ns[name]
1443 del self.user_ns[name]
1442 self.user_ns_hidden.pop(name, None)
1444 self.user_ns_hidden.pop(name, None)
1443
1445
1444 #-------------------------------------------------------------------------
1446 #-------------------------------------------------------------------------
1445 # Things related to object introspection
1447 # Things related to object introspection
1446 #-------------------------------------------------------------------------
1448 #-------------------------------------------------------------------------
1447
1449
1448 def _ofind(self, oname, namespaces=None):
1450 def _ofind(self, oname, namespaces=None):
1449 """Find an object in the available namespaces.
1451 """Find an object in the available namespaces.
1450
1452
1451 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1453 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1452
1454
1453 Has special code to detect magic functions.
1455 Has special code to detect magic functions.
1454 """
1456 """
1455 oname = oname.strip()
1457 oname = oname.strip()
1456 #print '1- oname: <%r>' % oname # dbg
1458 #print '1- oname: <%r>' % oname # dbg
1457 if not oname.startswith(ESC_MAGIC) and \
1459 if not oname.startswith(ESC_MAGIC) and \
1458 not oname.startswith(ESC_MAGIC2) and \
1460 not oname.startswith(ESC_MAGIC2) and \
1459 not py3compat.isidentifier(oname, dotted=True):
1461 not py3compat.isidentifier(oname, dotted=True):
1460 return dict(found=False)
1462 return dict(found=False)
1461
1463
1462 if namespaces is None:
1464 if namespaces is None:
1463 # Namespaces to search in:
1465 # Namespaces to search in:
1464 # Put them in a list. The order is important so that we
1466 # Put them in a list. The order is important so that we
1465 # find things in the same order that Python finds them.
1467 # find things in the same order that Python finds them.
1466 namespaces = [ ('Interactive', self.user_ns),
1468 namespaces = [ ('Interactive', self.user_ns),
1467 ('Interactive (global)', self.user_global_ns),
1469 ('Interactive (global)', self.user_global_ns),
1468 ('Python builtin', builtin_mod.__dict__),
1470 ('Python builtin', builtin_mod.__dict__),
1469 ]
1471 ]
1470
1472
1471 # initialize results to 'null'
1473 # initialize results to 'null'
1472 found = False; obj = None; ospace = None;
1474 found = False; obj = None; ospace = None;
1473 ismagic = False; isalias = False; parent = None
1475 ismagic = False; isalias = False; parent = None
1474
1476
1475 # We need to special-case 'print', which as of python2.6 registers as a
1477 # We need to special-case 'print', which as of python2.6 registers as a
1476 # function but should only be treated as one if print_function was
1478 # function but should only be treated as one if print_function was
1477 # loaded with a future import. In this case, just bail.
1479 # loaded with a future import. In this case, just bail.
1478 if (oname == 'print' and not py3compat.PY3 and not \
1480 if (oname == 'print' and not py3compat.PY3 and not \
1479 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1481 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1480 return {'found':found, 'obj':obj, 'namespace':ospace,
1482 return {'found':found, 'obj':obj, 'namespace':ospace,
1481 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1483 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1482
1484
1483 # Look for the given name by splitting it in parts. If the head is
1485 # Look for the given name by splitting it in parts. If the head is
1484 # found, then we look for all the remaining parts as members, and only
1486 # found, then we look for all the remaining parts as members, and only
1485 # declare success if we can find them all.
1487 # declare success if we can find them all.
1486 oname_parts = oname.split('.')
1488 oname_parts = oname.split('.')
1487 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1489 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1488 for nsname,ns in namespaces:
1490 for nsname,ns in namespaces:
1489 try:
1491 try:
1490 obj = ns[oname_head]
1492 obj = ns[oname_head]
1491 except KeyError:
1493 except KeyError:
1492 continue
1494 continue
1493 else:
1495 else:
1494 #print 'oname_rest:', oname_rest # dbg
1496 #print 'oname_rest:', oname_rest # dbg
1495 for idx, part in enumerate(oname_rest):
1497 for idx, part in enumerate(oname_rest):
1496 try:
1498 try:
1497 parent = obj
1499 parent = obj
1498 # The last part is looked up in a special way to avoid
1500 # The last part is looked up in a special way to avoid
1499 # descriptor invocation as it may raise or have side
1501 # descriptor invocation as it may raise or have side
1500 # effects.
1502 # effects.
1501 if idx == len(oname_rest) - 1:
1503 if idx == len(oname_rest) - 1:
1502 obj = self._getattr_property(obj, part)
1504 obj = self._getattr_property(obj, part)
1503 else:
1505 else:
1504 obj = getattr(obj, part)
1506 obj = getattr(obj, part)
1505 except:
1507 except:
1506 # Blanket except b/c some badly implemented objects
1508 # Blanket except b/c some badly implemented objects
1507 # allow __getattr__ to raise exceptions other than
1509 # allow __getattr__ to raise exceptions other than
1508 # AttributeError, which then crashes IPython.
1510 # AttributeError, which then crashes IPython.
1509 break
1511 break
1510 else:
1512 else:
1511 # If we finish the for loop (no break), we got all members
1513 # If we finish the for loop (no break), we got all members
1512 found = True
1514 found = True
1513 ospace = nsname
1515 ospace = nsname
1514 break # namespace loop
1516 break # namespace loop
1515
1517
1516 # Try to see if it's magic
1518 # Try to see if it's magic
1517 if not found:
1519 if not found:
1518 obj = None
1520 obj = None
1519 if oname.startswith(ESC_MAGIC2):
1521 if oname.startswith(ESC_MAGIC2):
1520 oname = oname.lstrip(ESC_MAGIC2)
1522 oname = oname.lstrip(ESC_MAGIC2)
1521 obj = self.find_cell_magic(oname)
1523 obj = self.find_cell_magic(oname)
1522 elif oname.startswith(ESC_MAGIC):
1524 elif oname.startswith(ESC_MAGIC):
1523 oname = oname.lstrip(ESC_MAGIC)
1525 oname = oname.lstrip(ESC_MAGIC)
1524 obj = self.find_line_magic(oname)
1526 obj = self.find_line_magic(oname)
1525 else:
1527 else:
1526 # search without prefix, so run? will find %run?
1528 # search without prefix, so run? will find %run?
1527 obj = self.find_line_magic(oname)
1529 obj = self.find_line_magic(oname)
1528 if obj is None:
1530 if obj is None:
1529 obj = self.find_cell_magic(oname)
1531 obj = self.find_cell_magic(oname)
1530 if obj is not None:
1532 if obj is not None:
1531 found = True
1533 found = True
1532 ospace = 'IPython internal'
1534 ospace = 'IPython internal'
1533 ismagic = True
1535 ismagic = True
1534 isalias = isinstance(obj, Alias)
1536 isalias = isinstance(obj, Alias)
1535
1537
1536 # Last try: special-case some literals like '', [], {}, etc:
1538 # Last try: special-case some literals like '', [], {}, etc:
1537 if not found and oname_head in ["''",'""','[]','{}','()']:
1539 if not found and oname_head in ["''",'""','[]','{}','()']:
1538 obj = eval(oname_head)
1540 obj = eval(oname_head)
1539 found = True
1541 found = True
1540 ospace = 'Interactive'
1542 ospace = 'Interactive'
1541
1543
1542 return {'found':found, 'obj':obj, 'namespace':ospace,
1544 return {'found':found, 'obj':obj, 'namespace':ospace,
1543 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1545 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1544
1546
1545 @staticmethod
1547 @staticmethod
1546 def _getattr_property(obj, attrname):
1548 def _getattr_property(obj, attrname):
1547 """Property-aware getattr to use in object finding.
1549 """Property-aware getattr to use in object finding.
1548
1550
1549 If attrname represents a property, return it unevaluated (in case it has
1551 If attrname represents a property, return it unevaluated (in case it has
1550 side effects or raises an error.
1552 side effects or raises an error.
1551
1553
1552 """
1554 """
1553 if not isinstance(obj, type):
1555 if not isinstance(obj, type):
1554 try:
1556 try:
1555 # `getattr(type(obj), attrname)` is not guaranteed to return
1557 # `getattr(type(obj), attrname)` is not guaranteed to return
1556 # `obj`, but does so for property:
1558 # `obj`, but does so for property:
1557 #
1559 #
1558 # property.__get__(self, None, cls) -> self
1560 # property.__get__(self, None, cls) -> self
1559 #
1561 #
1560 # The universal alternative is to traverse the mro manually
1562 # The universal alternative is to traverse the mro manually
1561 # searching for attrname in class dicts.
1563 # searching for attrname in class dicts.
1562 attr = getattr(type(obj), attrname)
1564 attr = getattr(type(obj), attrname)
1563 except AttributeError:
1565 except AttributeError:
1564 pass
1566 pass
1565 else:
1567 else:
1566 # This relies on the fact that data descriptors (with both
1568 # This relies on the fact that data descriptors (with both
1567 # __get__ & __set__ magic methods) take precedence over
1569 # __get__ & __set__ magic methods) take precedence over
1568 # instance-level attributes:
1570 # instance-level attributes:
1569 #
1571 #
1570 # class A(object):
1572 # class A(object):
1571 # @property
1573 # @property
1572 # def foobar(self): return 123
1574 # def foobar(self): return 123
1573 # a = A()
1575 # a = A()
1574 # a.__dict__['foobar'] = 345
1576 # a.__dict__['foobar'] = 345
1575 # a.foobar # == 123
1577 # a.foobar # == 123
1576 #
1578 #
1577 # So, a property may be returned right away.
1579 # So, a property may be returned right away.
1578 if isinstance(attr, property):
1580 if isinstance(attr, property):
1579 return attr
1581 return attr
1580
1582
1581 # Nothing helped, fall back.
1583 # Nothing helped, fall back.
1582 return getattr(obj, attrname)
1584 return getattr(obj, attrname)
1583
1585
1584 def _object_find(self, oname, namespaces=None):
1586 def _object_find(self, oname, namespaces=None):
1585 """Find an object and return a struct with info about it."""
1587 """Find an object and return a struct with info about it."""
1586 return Struct(self._ofind(oname, namespaces))
1588 return Struct(self._ofind(oname, namespaces))
1587
1589
1588 def _inspect(self, meth, oname, namespaces=None, **kw):
1590 def _inspect(self, meth, oname, namespaces=None, **kw):
1589 """Generic interface to the inspector system.
1591 """Generic interface to the inspector system.
1590
1592
1591 This function is meant to be called by pdef, pdoc & friends."""
1593 This function is meant to be called by pdef, pdoc & friends."""
1592 info = self._object_find(oname, namespaces)
1594 info = self._object_find(oname, namespaces)
1593 if info.found:
1595 if info.found:
1594 pmethod = getattr(self.inspector, meth)
1596 pmethod = getattr(self.inspector, meth)
1595 formatter = format_screen if info.ismagic else None
1597 formatter = format_screen if info.ismagic else None
1596 if meth == 'pdoc':
1598 if meth == 'pdoc':
1597 pmethod(info.obj, oname, formatter)
1599 pmethod(info.obj, oname, formatter)
1598 elif meth == 'pinfo':
1600 elif meth == 'pinfo':
1599 pmethod(info.obj, oname, formatter, info, **kw)
1601 pmethod(info.obj, oname, formatter, info, **kw)
1600 else:
1602 else:
1601 pmethod(info.obj, oname)
1603 pmethod(info.obj, oname)
1602 else:
1604 else:
1603 print('Object `%s` not found.' % oname)
1605 print('Object `%s` not found.' % oname)
1604 return 'not found' # so callers can take other action
1606 return 'not found' # so callers can take other action
1605
1607
1606 def object_inspect(self, oname, detail_level=0):
1608 def object_inspect(self, oname, detail_level=0):
1607 """Get object info about oname"""
1609 """Get object info about oname"""
1608 with self.builtin_trap:
1610 with self.builtin_trap:
1609 info = self._object_find(oname)
1611 info = self._object_find(oname)
1610 if info.found:
1612 if info.found:
1611 return self.inspector.info(info.obj, oname, info=info,
1613 return self.inspector.info(info.obj, oname, info=info,
1612 detail_level=detail_level
1614 detail_level=detail_level
1613 )
1615 )
1614 else:
1616 else:
1615 return oinspect.object_info(name=oname, found=False)
1617 return oinspect.object_info(name=oname, found=False)
1616
1618
1617 def object_inspect_text(self, oname, detail_level=0):
1619 def object_inspect_text(self, oname, detail_level=0):
1618 """Get object info as formatted text"""
1620 """Get object info as formatted text"""
1619 with self.builtin_trap:
1621 with self.builtin_trap:
1620 info = self._object_find(oname)
1622 info = self._object_find(oname)
1621 if info.found:
1623 if info.found:
1622 return self.inspector._format_info(info.obj, oname, info=info,
1624 return self.inspector._format_info(info.obj, oname, info=info,
1623 detail_level=detail_level
1625 detail_level=detail_level
1624 )
1626 )
1625 else:
1627 else:
1626 raise KeyError(oname)
1628 raise KeyError(oname)
1627
1629
1628 #-------------------------------------------------------------------------
1630 #-------------------------------------------------------------------------
1629 # Things related to history management
1631 # Things related to history management
1630 #-------------------------------------------------------------------------
1632 #-------------------------------------------------------------------------
1631
1633
1632 def init_history(self):
1634 def init_history(self):
1633 """Sets up the command history, and starts regular autosaves."""
1635 """Sets up the command history, and starts regular autosaves."""
1634 self.history_manager = HistoryManager(shell=self, parent=self)
1636 self.history_manager = HistoryManager(shell=self, parent=self)
1635 self.configurables.append(self.history_manager)
1637 self.configurables.append(self.history_manager)
1636
1638
1637 #-------------------------------------------------------------------------
1639 #-------------------------------------------------------------------------
1638 # Things related to exception handling and tracebacks (not debugging)
1640 # Things related to exception handling and tracebacks (not debugging)
1639 #-------------------------------------------------------------------------
1641 #-------------------------------------------------------------------------
1640
1642
1641 def init_traceback_handlers(self, custom_exceptions):
1643 def init_traceback_handlers(self, custom_exceptions):
1642 # Syntax error handler.
1644 # Syntax error handler.
1643 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1645 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1644
1646
1645 # The interactive one is initialized with an offset, meaning we always
1647 # The interactive one is initialized with an offset, meaning we always
1646 # want to remove the topmost item in the traceback, which is our own
1648 # want to remove the topmost item in the traceback, which is our own
1647 # internal code. Valid modes: ['Plain','Context','Verbose']
1649 # internal code. Valid modes: ['Plain','Context','Verbose']
1648 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1650 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1649 color_scheme='NoColor',
1651 color_scheme='NoColor',
1650 tb_offset = 1,
1652 tb_offset = 1,
1651 check_cache=check_linecache_ipython)
1653 check_cache=check_linecache_ipython)
1652
1654
1653 # The instance will store a pointer to the system-wide exception hook,
1655 # The instance will store a pointer to the system-wide exception hook,
1654 # so that runtime code (such as magics) can access it. This is because
1656 # so that runtime code (such as magics) can access it. This is because
1655 # during the read-eval loop, it may get temporarily overwritten.
1657 # during the read-eval loop, it may get temporarily overwritten.
1656 self.sys_excepthook = sys.excepthook
1658 self.sys_excepthook = sys.excepthook
1657
1659
1658 # and add any custom exception handlers the user may have specified
1660 # and add any custom exception handlers the user may have specified
1659 self.set_custom_exc(*custom_exceptions)
1661 self.set_custom_exc(*custom_exceptions)
1660
1662
1661 # Set the exception mode
1663 # Set the exception mode
1662 self.InteractiveTB.set_mode(mode=self.xmode)
1664 self.InteractiveTB.set_mode(mode=self.xmode)
1663
1665
1664 def set_custom_exc(self, exc_tuple, handler):
1666 def set_custom_exc(self, exc_tuple, handler):
1665 """set_custom_exc(exc_tuple,handler)
1667 """set_custom_exc(exc_tuple,handler)
1666
1668
1667 Set a custom exception handler, which will be called if any of the
1669 Set a custom exception handler, which will be called if any of the
1668 exceptions in exc_tuple occur in the mainloop (specifically, in the
1670 exceptions in exc_tuple occur in the mainloop (specifically, in the
1669 run_code() method).
1671 run_code() method).
1670
1672
1671 Parameters
1673 Parameters
1672 ----------
1674 ----------
1673
1675
1674 exc_tuple : tuple of exception classes
1676 exc_tuple : tuple of exception classes
1675 A *tuple* of exception classes, for which to call the defined
1677 A *tuple* of exception classes, for which to call the defined
1676 handler. It is very important that you use a tuple, and NOT A
1678 handler. It is very important that you use a tuple, and NOT A
1677 LIST here, because of the way Python's except statement works. If
1679 LIST here, because of the way Python's except statement works. If
1678 you only want to trap a single exception, use a singleton tuple::
1680 you only want to trap a single exception, use a singleton tuple::
1679
1681
1680 exc_tuple == (MyCustomException,)
1682 exc_tuple == (MyCustomException,)
1681
1683
1682 handler : callable
1684 handler : callable
1683 handler must have the following signature::
1685 handler must have the following signature::
1684
1686
1685 def my_handler(self, etype, value, tb, tb_offset=None):
1687 def my_handler(self, etype, value, tb, tb_offset=None):
1686 ...
1688 ...
1687 return structured_traceback
1689 return structured_traceback
1688
1690
1689 Your handler must return a structured traceback (a list of strings),
1691 Your handler must return a structured traceback (a list of strings),
1690 or None.
1692 or None.
1691
1693
1692 This will be made into an instance method (via types.MethodType)
1694 This will be made into an instance method (via types.MethodType)
1693 of IPython itself, and it will be called if any of the exceptions
1695 of IPython itself, and it will be called if any of the exceptions
1694 listed in the exc_tuple are caught. If the handler is None, an
1696 listed in the exc_tuple are caught. If the handler is None, an
1695 internal basic one is used, which just prints basic info.
1697 internal basic one is used, which just prints basic info.
1696
1698
1697 To protect IPython from crashes, if your handler ever raises an
1699 To protect IPython from crashes, if your handler ever raises an
1698 exception or returns an invalid result, it will be immediately
1700 exception or returns an invalid result, it will be immediately
1699 disabled.
1701 disabled.
1700
1702
1701 WARNING: by putting in your own exception handler into IPython's main
1703 WARNING: by putting in your own exception handler into IPython's main
1702 execution loop, you run a very good chance of nasty crashes. This
1704 execution loop, you run a very good chance of nasty crashes. This
1703 facility should only be used if you really know what you are doing."""
1705 facility should only be used if you really know what you are doing."""
1704
1706
1705 assert type(exc_tuple)==type(()) , \
1707 assert type(exc_tuple)==type(()) , \
1706 "The custom exceptions must be given AS A TUPLE."
1708 "The custom exceptions must be given AS A TUPLE."
1707
1709
1708 def dummy_handler(self,etype,value,tb,tb_offset=None):
1710 def dummy_handler(self,etype,value,tb,tb_offset=None):
1709 print('*** Simple custom exception handler ***')
1711 print('*** Simple custom exception handler ***')
1710 print('Exception type :',etype)
1712 print('Exception type :',etype)
1711 print('Exception value:',value)
1713 print('Exception value:',value)
1712 print('Traceback :',tb)
1714 print('Traceback :',tb)
1713 #print 'Source code :','\n'.join(self.buffer)
1715 #print 'Source code :','\n'.join(self.buffer)
1714
1716
1715 def validate_stb(stb):
1717 def validate_stb(stb):
1716 """validate structured traceback return type
1718 """validate structured traceback return type
1717
1719
1718 return type of CustomTB *should* be a list of strings, but allow
1720 return type of CustomTB *should* be a list of strings, but allow
1719 single strings or None, which are harmless.
1721 single strings or None, which are harmless.
1720
1722
1721 This function will *always* return a list of strings,
1723 This function will *always* return a list of strings,
1722 and will raise a TypeError if stb is inappropriate.
1724 and will raise a TypeError if stb is inappropriate.
1723 """
1725 """
1724 msg = "CustomTB must return list of strings, not %r" % stb
1726 msg = "CustomTB must return list of strings, not %r" % stb
1725 if stb is None:
1727 if stb is None:
1726 return []
1728 return []
1727 elif isinstance(stb, string_types):
1729 elif isinstance(stb, string_types):
1728 return [stb]
1730 return [stb]
1729 elif not isinstance(stb, list):
1731 elif not isinstance(stb, list):
1730 raise TypeError(msg)
1732 raise TypeError(msg)
1731 # it's a list
1733 # it's a list
1732 for line in stb:
1734 for line in stb:
1733 # check every element
1735 # check every element
1734 if not isinstance(line, string_types):
1736 if not isinstance(line, string_types):
1735 raise TypeError(msg)
1737 raise TypeError(msg)
1736 return stb
1738 return stb
1737
1739
1738 if handler is None:
1740 if handler is None:
1739 wrapped = dummy_handler
1741 wrapped = dummy_handler
1740 else:
1742 else:
1741 def wrapped(self,etype,value,tb,tb_offset=None):
1743 def wrapped(self,etype,value,tb,tb_offset=None):
1742 """wrap CustomTB handler, to protect IPython from user code
1744 """wrap CustomTB handler, to protect IPython from user code
1743
1745
1744 This makes it harder (but not impossible) for custom exception
1746 This makes it harder (but not impossible) for custom exception
1745 handlers to crash IPython.
1747 handlers to crash IPython.
1746 """
1748 """
1747 try:
1749 try:
1748 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1750 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1749 return validate_stb(stb)
1751 return validate_stb(stb)
1750 except:
1752 except:
1751 # clear custom handler immediately
1753 # clear custom handler immediately
1752 self.set_custom_exc((), None)
1754 self.set_custom_exc((), None)
1753 print("Custom TB Handler failed, unregistering", file=io.stderr)
1755 print("Custom TB Handler failed, unregistering", file=io.stderr)
1754 # show the exception in handler first
1756 # show the exception in handler first
1755 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1757 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1756 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1758 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1757 print("The original exception:", file=io.stdout)
1759 print("The original exception:", file=io.stdout)
1758 stb = self.InteractiveTB.structured_traceback(
1760 stb = self.InteractiveTB.structured_traceback(
1759 (etype,value,tb), tb_offset=tb_offset
1761 (etype,value,tb), tb_offset=tb_offset
1760 )
1762 )
1761 return stb
1763 return stb
1762
1764
1763 self.CustomTB = types.MethodType(wrapped,self)
1765 self.CustomTB = types.MethodType(wrapped,self)
1764 self.custom_exceptions = exc_tuple
1766 self.custom_exceptions = exc_tuple
1765
1767
1766 def excepthook(self, etype, value, tb):
1768 def excepthook(self, etype, value, tb):
1767 """One more defense for GUI apps that call sys.excepthook.
1769 """One more defense for GUI apps that call sys.excepthook.
1768
1770
1769 GUI frameworks like wxPython trap exceptions and call
1771 GUI frameworks like wxPython trap exceptions and call
1770 sys.excepthook themselves. I guess this is a feature that
1772 sys.excepthook themselves. I guess this is a feature that
1771 enables them to keep running after exceptions that would
1773 enables them to keep running after exceptions that would
1772 otherwise kill their mainloop. This is a bother for IPython
1774 otherwise kill their mainloop. This is a bother for IPython
1773 which excepts to catch all of the program exceptions with a try:
1775 which excepts to catch all of the program exceptions with a try:
1774 except: statement.
1776 except: statement.
1775
1777
1776 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1778 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1777 any app directly invokes sys.excepthook, it will look to the user like
1779 any app directly invokes sys.excepthook, it will look to the user like
1778 IPython crashed. In order to work around this, we can disable the
1780 IPython crashed. In order to work around this, we can disable the
1779 CrashHandler and replace it with this excepthook instead, which prints a
1781 CrashHandler and replace it with this excepthook instead, which prints a
1780 regular traceback using our InteractiveTB. In this fashion, apps which
1782 regular traceback using our InteractiveTB. In this fashion, apps which
1781 call sys.excepthook will generate a regular-looking exception from
1783 call sys.excepthook will generate a regular-looking exception from
1782 IPython, and the CrashHandler will only be triggered by real IPython
1784 IPython, and the CrashHandler will only be triggered by real IPython
1783 crashes.
1785 crashes.
1784
1786
1785 This hook should be used sparingly, only in places which are not likely
1787 This hook should be used sparingly, only in places which are not likely
1786 to be true IPython errors.
1788 to be true IPython errors.
1787 """
1789 """
1788 self.showtraceback((etype, value, tb), tb_offset=0)
1790 self.showtraceback((etype, value, tb), tb_offset=0)
1789
1791
1790 def _get_exc_info(self, exc_tuple=None):
1792 def _get_exc_info(self, exc_tuple=None):
1791 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1793 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1792
1794
1793 Ensures sys.last_type,value,traceback hold the exc_info we found,
1795 Ensures sys.last_type,value,traceback hold the exc_info we found,
1794 from whichever source.
1796 from whichever source.
1795
1797
1796 raises ValueError if none of these contain any information
1798 raises ValueError if none of these contain any information
1797 """
1799 """
1798 if exc_tuple is None:
1800 if exc_tuple is None:
1799 etype, value, tb = sys.exc_info()
1801 etype, value, tb = sys.exc_info()
1800 else:
1802 else:
1801 etype, value, tb = exc_tuple
1803 etype, value, tb = exc_tuple
1802
1804
1803 if etype is None:
1805 if etype is None:
1804 if hasattr(sys, 'last_type'):
1806 if hasattr(sys, 'last_type'):
1805 etype, value, tb = sys.last_type, sys.last_value, \
1807 etype, value, tb = sys.last_type, sys.last_value, \
1806 sys.last_traceback
1808 sys.last_traceback
1807
1809
1808 if etype is None:
1810 if etype is None:
1809 raise ValueError("No exception to find")
1811 raise ValueError("No exception to find")
1810
1812
1811 # Now store the exception info in sys.last_type etc.
1813 # Now store the exception info in sys.last_type etc.
1812 # WARNING: these variables are somewhat deprecated and not
1814 # WARNING: these variables are somewhat deprecated and not
1813 # necessarily safe to use in a threaded environment, but tools
1815 # necessarily safe to use in a threaded environment, but tools
1814 # like pdb depend on their existence, so let's set them. If we
1816 # like pdb depend on their existence, so let's set them. If we
1815 # find problems in the field, we'll need to revisit their use.
1817 # find problems in the field, we'll need to revisit their use.
1816 sys.last_type = etype
1818 sys.last_type = etype
1817 sys.last_value = value
1819 sys.last_value = value
1818 sys.last_traceback = tb
1820 sys.last_traceback = tb
1819
1821
1820 return etype, value, tb
1822 return etype, value, tb
1821
1823
1822 def show_usage_error(self, exc):
1824 def show_usage_error(self, exc):
1823 """Show a short message for UsageErrors
1825 """Show a short message for UsageErrors
1824
1826
1825 These are special exceptions that shouldn't show a traceback.
1827 These are special exceptions that shouldn't show a traceback.
1826 """
1828 """
1827 self.write_err("UsageError: %s" % exc)
1829 self.write_err("UsageError: %s" % exc)
1828
1830
1829 def get_exception_only(self, exc_tuple=None):
1831 def get_exception_only(self, exc_tuple=None):
1830 """
1832 """
1831 Return as a string (ending with a newline) the exception that
1833 Return as a string (ending with a newline) the exception that
1832 just occurred, without any traceback.
1834 just occurred, without any traceback.
1833 """
1835 """
1834 etype, value, tb = self._get_exc_info(exc_tuple)
1836 etype, value, tb = self._get_exc_info(exc_tuple)
1835 msg = traceback.format_exception_only(etype, value)
1837 msg = traceback.format_exception_only(etype, value)
1836 return ''.join(msg)
1838 return ''.join(msg)
1837
1839
1838 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1840 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1839 exception_only=False):
1841 exception_only=False):
1840 """Display the exception that just occurred.
1842 """Display the exception that just occurred.
1841
1843
1842 If nothing is known about the exception, this is the method which
1844 If nothing is known about the exception, this is the method which
1843 should be used throughout the code for presenting user tracebacks,
1845 should be used throughout the code for presenting user tracebacks,
1844 rather than directly invoking the InteractiveTB object.
1846 rather than directly invoking the InteractiveTB object.
1845
1847
1846 A specific showsyntaxerror() also exists, but this method can take
1848 A specific showsyntaxerror() also exists, but this method can take
1847 care of calling it if needed, so unless you are explicitly catching a
1849 care of calling it if needed, so unless you are explicitly catching a
1848 SyntaxError exception, don't try to analyze the stack manually and
1850 SyntaxError exception, don't try to analyze the stack manually and
1849 simply call this method."""
1851 simply call this method."""
1850
1852
1851 try:
1853 try:
1852 try:
1854 try:
1853 etype, value, tb = self._get_exc_info(exc_tuple)
1855 etype, value, tb = self._get_exc_info(exc_tuple)
1854 except ValueError:
1856 except ValueError:
1855 self.write_err('No traceback available to show.\n')
1857 self.write_err('No traceback available to show.\n')
1856 return
1858 return
1857
1859
1858 if issubclass(etype, SyntaxError):
1860 if issubclass(etype, SyntaxError):
1859 # Though this won't be called by syntax errors in the input
1861 # Though this won't be called by syntax errors in the input
1860 # line, there may be SyntaxError cases with imported code.
1862 # line, there may be SyntaxError cases with imported code.
1861 self.showsyntaxerror(filename)
1863 self.showsyntaxerror(filename)
1862 elif etype is UsageError:
1864 elif etype is UsageError:
1863 self.show_usage_error(value)
1865 self.show_usage_error(value)
1864 else:
1866 else:
1865 if exception_only:
1867 if exception_only:
1866 stb = ['An exception has occurred, use %tb to see '
1868 stb = ['An exception has occurred, use %tb to see '
1867 'the full traceback.\n']
1869 'the full traceback.\n']
1868 stb.extend(self.InteractiveTB.get_exception_only(etype,
1870 stb.extend(self.InteractiveTB.get_exception_only(etype,
1869 value))
1871 value))
1870 else:
1872 else:
1871 try:
1873 try:
1872 # Exception classes can customise their traceback - we
1874 # Exception classes can customise their traceback - we
1873 # use this in IPython.parallel for exceptions occurring
1875 # use this in IPython.parallel for exceptions occurring
1874 # in the engines. This should return a list of strings.
1876 # in the engines. This should return a list of strings.
1875 stb = value._render_traceback_()
1877 stb = value._render_traceback_()
1876 except Exception:
1878 except Exception:
1877 stb = self.InteractiveTB.structured_traceback(etype,
1879 stb = self.InteractiveTB.structured_traceback(etype,
1878 value, tb, tb_offset=tb_offset)
1880 value, tb, tb_offset=tb_offset)
1879
1881
1880 self._showtraceback(etype, value, stb)
1882 self._showtraceback(etype, value, stb)
1881 if self.call_pdb:
1883 if self.call_pdb:
1882 # drop into debugger
1884 # drop into debugger
1883 self.debugger(force=True)
1885 self.debugger(force=True)
1884 return
1886 return
1885
1887
1886 # Actually show the traceback
1888 # Actually show the traceback
1887 self._showtraceback(etype, value, stb)
1889 self._showtraceback(etype, value, stb)
1888
1890
1889 except KeyboardInterrupt:
1891 except KeyboardInterrupt:
1890 self.write_err('\n' + self.get_exception_only())
1892 self.write_err('\n' + self.get_exception_only())
1891
1893
1892 def _showtraceback(self, etype, evalue, stb):
1894 def _showtraceback(self, etype, evalue, stb):
1893 """Actually show a traceback.
1895 """Actually show a traceback.
1894
1896
1895 Subclasses may override this method to put the traceback on a different
1897 Subclasses may override this method to put the traceback on a different
1896 place, like a side channel.
1898 place, like a side channel.
1897 """
1899 """
1898 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1900 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1899
1901
1900 def showsyntaxerror(self, filename=None):
1902 def showsyntaxerror(self, filename=None):
1901 """Display the syntax error that just occurred.
1903 """Display the syntax error that just occurred.
1902
1904
1903 This doesn't display a stack trace because there isn't one.
1905 This doesn't display a stack trace because there isn't one.
1904
1906
1905 If a filename is given, it is stuffed in the exception instead
1907 If a filename is given, it is stuffed in the exception instead
1906 of what was there before (because Python's parser always uses
1908 of what was there before (because Python's parser always uses
1907 "<string>" when reading from a string).
1909 "<string>" when reading from a string).
1908 """
1910 """
1909 etype, value, last_traceback = self._get_exc_info()
1911 etype, value, last_traceback = self._get_exc_info()
1910
1912
1911 if filename and issubclass(etype, SyntaxError):
1913 if filename and issubclass(etype, SyntaxError):
1912 try:
1914 try:
1913 value.filename = filename
1915 value.filename = filename
1914 except:
1916 except:
1915 # Not the format we expect; leave it alone
1917 # Not the format we expect; leave it alone
1916 pass
1918 pass
1917
1919
1918 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1920 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1919 self._showtraceback(etype, value, stb)
1921 self._showtraceback(etype, value, stb)
1920
1922
1921 # This is overridden in TerminalInteractiveShell to show a message about
1923 # This is overridden in TerminalInteractiveShell to show a message about
1922 # the %paste magic.
1924 # the %paste magic.
1923 def showindentationerror(self):
1925 def showindentationerror(self):
1924 """Called by run_cell when there's an IndentationError in code entered
1926 """Called by run_cell when there's an IndentationError in code entered
1925 at the prompt.
1927 at the prompt.
1926
1928
1927 This is overridden in TerminalInteractiveShell to show a message about
1929 This is overridden in TerminalInteractiveShell to show a message about
1928 the %paste magic."""
1930 the %paste magic."""
1929 self.showsyntaxerror()
1931 self.showsyntaxerror()
1930
1932
1931 #-------------------------------------------------------------------------
1933 #-------------------------------------------------------------------------
1932 # Things related to readline
1934 # Things related to readline
1933 #-------------------------------------------------------------------------
1935 #-------------------------------------------------------------------------
1934
1936
1935 def init_readline(self):
1937 def init_readline(self):
1936 """Command history completion/saving/reloading."""
1938 """Command history completion/saving/reloading."""
1937
1939
1938 if self.readline_use:
1940 if self.readline_use:
1939 import IPython.utils.rlineimpl as readline
1941 import IPython.utils.rlineimpl as readline
1940
1942
1941 self.rl_next_input = None
1943 self.rl_next_input = None
1942 self.rl_do_indent = False
1944 self.rl_do_indent = False
1943
1945
1944 if not self.readline_use or not readline.have_readline:
1946 if not self.readline_use or not readline.have_readline:
1945 self.has_readline = False
1947 self.has_readline = False
1946 self.readline = None
1948 self.readline = None
1947 # Set a number of methods that depend on readline to be no-op
1949 # Set a number of methods that depend on readline to be no-op
1948 self.readline_no_record = no_op_context
1950 self.readline_no_record = no_op_context
1949 self.set_readline_completer = no_op
1951 self.set_readline_completer = no_op
1950 self.set_custom_completer = no_op
1952 self.set_custom_completer = no_op
1951 if self.readline_use:
1953 if self.readline_use:
1952 warn('Readline services not available or not loaded.')
1954 warn('Readline services not available or not loaded.')
1953 else:
1955 else:
1954 self.has_readline = True
1956 self.has_readline = True
1955 self.readline = readline
1957 self.readline = readline
1956 sys.modules['readline'] = readline
1958 sys.modules['readline'] = readline
1957
1959
1958 # Platform-specific configuration
1960 # Platform-specific configuration
1959 if os.name == 'nt':
1961 if os.name == 'nt':
1960 # FIXME - check with Frederick to see if we can harmonize
1962 # FIXME - check with Frederick to see if we can harmonize
1961 # naming conventions with pyreadline to avoid this
1963 # naming conventions with pyreadline to avoid this
1962 # platform-dependent check
1964 # platform-dependent check
1963 self.readline_startup_hook = readline.set_pre_input_hook
1965 self.readline_startup_hook = readline.set_pre_input_hook
1964 else:
1966 else:
1965 self.readline_startup_hook = readline.set_startup_hook
1967 self.readline_startup_hook = readline.set_startup_hook
1966
1968
1967 # Readline config order:
1969 # Readline config order:
1968 # - IPython config (default value)
1970 # - IPython config (default value)
1969 # - custom inputrc
1971 # - custom inputrc
1970 # - IPython config (user customized)
1972 # - IPython config (user customized)
1971
1973
1972 # load IPython config before inputrc if default
1974 # load IPython config before inputrc if default
1973 # skip if libedit because parse_and_bind syntax is different
1975 # skip if libedit because parse_and_bind syntax is different
1974 if not self._custom_readline_config and not readline.uses_libedit:
1976 if not self._custom_readline_config and not readline.uses_libedit:
1975 for rlcommand in self.readline_parse_and_bind:
1977 for rlcommand in self.readline_parse_and_bind:
1976 readline.parse_and_bind(rlcommand)
1978 readline.parse_and_bind(rlcommand)
1977
1979
1978 # Load user's initrc file (readline config)
1980 # Load user's initrc file (readline config)
1979 # Or if libedit is used, load editrc.
1981 # Or if libedit is used, load editrc.
1980 inputrc_name = os.environ.get('INPUTRC')
1982 inputrc_name = os.environ.get('INPUTRC')
1981 if inputrc_name is None:
1983 if inputrc_name is None:
1982 inputrc_name = '.inputrc'
1984 inputrc_name = '.inputrc'
1983 if readline.uses_libedit:
1985 if readline.uses_libedit:
1984 inputrc_name = '.editrc'
1986 inputrc_name = '.editrc'
1985 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1987 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1986 if os.path.isfile(inputrc_name):
1988 if os.path.isfile(inputrc_name):
1987 try:
1989 try:
1988 readline.read_init_file(inputrc_name)
1990 readline.read_init_file(inputrc_name)
1989 except:
1991 except:
1990 warn('Problems reading readline initialization file <%s>'
1992 warn('Problems reading readline initialization file <%s>'
1991 % inputrc_name)
1993 % inputrc_name)
1992
1994
1993 # load IPython config after inputrc if user has customized
1995 # load IPython config after inputrc if user has customized
1994 if self._custom_readline_config:
1996 if self._custom_readline_config:
1995 for rlcommand in self.readline_parse_and_bind:
1997 for rlcommand in self.readline_parse_and_bind:
1996 readline.parse_and_bind(rlcommand)
1998 readline.parse_and_bind(rlcommand)
1997
1999
1998 # Remove some chars from the delimiters list. If we encounter
2000 # Remove some chars from the delimiters list. If we encounter
1999 # unicode chars, discard them.
2001 # unicode chars, discard them.
2000 delims = readline.get_completer_delims()
2002 delims = readline.get_completer_delims()
2001 if not py3compat.PY3:
2003 if not py3compat.PY3:
2002 delims = delims.encode("ascii", "ignore")
2004 delims = delims.encode("ascii", "ignore")
2003 for d in self.readline_remove_delims:
2005 for d in self.readline_remove_delims:
2004 delims = delims.replace(d, "")
2006 delims = delims.replace(d, "")
2005 delims = delims.replace(ESC_MAGIC, '')
2007 delims = delims.replace(ESC_MAGIC, '')
2006 readline.set_completer_delims(delims)
2008 readline.set_completer_delims(delims)
2007 # Store these so we can restore them if something like rpy2 modifies
2009 # Store these so we can restore them if something like rpy2 modifies
2008 # them.
2010 # them.
2009 self.readline_delims = delims
2011 self.readline_delims = delims
2010 # otherwise we end up with a monster history after a while:
2012 # otherwise we end up with a monster history after a while:
2011 readline.set_history_length(self.history_length)
2013 readline.set_history_length(self.history_length)
2012
2014
2013 self.refill_readline_hist()
2015 self.refill_readline_hist()
2014 self.readline_no_record = ReadlineNoRecord(self)
2016 self.readline_no_record = ReadlineNoRecord(self)
2015
2017
2016 # Configure auto-indent for all platforms
2018 # Configure auto-indent for all platforms
2017 self.set_autoindent(self.autoindent)
2019 self.set_autoindent(self.autoindent)
2018
2020
2019 def refill_readline_hist(self):
2021 def refill_readline_hist(self):
2020 # Load the last 1000 lines from history
2022 # Load the last 1000 lines from history
2021 self.readline.clear_history()
2023 self.readline.clear_history()
2022 stdin_encoding = sys.stdin.encoding or "utf-8"
2024 stdin_encoding = sys.stdin.encoding or "utf-8"
2023 last_cell = u""
2025 last_cell = u""
2024 for _, _, cell in self.history_manager.get_tail(self.history_load_length,
2026 for _, _, cell in self.history_manager.get_tail(self.history_load_length,
2025 include_latest=True):
2027 include_latest=True):
2026 # Ignore blank lines and consecutive duplicates
2028 # Ignore blank lines and consecutive duplicates
2027 cell = cell.rstrip()
2029 cell = cell.rstrip()
2028 if cell and (cell != last_cell):
2030 if cell and (cell != last_cell):
2029 try:
2031 try:
2030 if self.multiline_history:
2032 if self.multiline_history:
2031 self.readline.add_history(py3compat.unicode_to_str(cell,
2033 self.readline.add_history(py3compat.unicode_to_str(cell,
2032 stdin_encoding))
2034 stdin_encoding))
2033 else:
2035 else:
2034 for line in cell.splitlines():
2036 for line in cell.splitlines():
2035 self.readline.add_history(py3compat.unicode_to_str(line,
2037 self.readline.add_history(py3compat.unicode_to_str(line,
2036 stdin_encoding))
2038 stdin_encoding))
2037 last_cell = cell
2039 last_cell = cell
2038
2040
2039 except TypeError:
2041 except TypeError:
2040 # The history DB can get corrupted so it returns strings
2042 # The history DB can get corrupted so it returns strings
2041 # containing null bytes, which readline objects to.
2043 # containing null bytes, which readline objects to.
2042 continue
2044 continue
2043
2045
2044 @skip_doctest
2046 @skip_doctest
2045 def set_next_input(self, s, replace=False):
2047 def set_next_input(self, s, replace=False):
2046 """ Sets the 'default' input string for the next command line.
2048 """ Sets the 'default' input string for the next command line.
2047
2049
2048 Requires readline.
2050 Requires readline.
2049
2051
2050 Example::
2052 Example::
2051
2053
2052 In [1]: _ip.set_next_input("Hello Word")
2054 In [1]: _ip.set_next_input("Hello Word")
2053 In [2]: Hello Word_ # cursor is here
2055 In [2]: Hello Word_ # cursor is here
2054 """
2056 """
2055 self.rl_next_input = py3compat.cast_bytes_py2(s)
2057 self.rl_next_input = py3compat.cast_bytes_py2(s)
2056
2058
2057 # Maybe move this to the terminal subclass?
2059 # Maybe move this to the terminal subclass?
2058 def pre_readline(self):
2060 def pre_readline(self):
2059 """readline hook to be used at the start of each line.
2061 """readline hook to be used at the start of each line.
2060
2062
2061 Currently it handles auto-indent only."""
2063 Currently it handles auto-indent only."""
2062
2064
2063 if self.rl_do_indent:
2065 if self.rl_do_indent:
2064 self.readline.insert_text(self._indent_current_str())
2066 self.readline.insert_text(self._indent_current_str())
2065 if self.rl_next_input is not None:
2067 if self.rl_next_input is not None:
2066 self.readline.insert_text(self.rl_next_input)
2068 self.readline.insert_text(self.rl_next_input)
2067 self.rl_next_input = None
2069 self.rl_next_input = None
2068
2070
2069 def _indent_current_str(self):
2071 def _indent_current_str(self):
2070 """return the current level of indentation as a string"""
2072 """return the current level of indentation as a string"""
2071 return self.input_splitter.indent_spaces * ' '
2073 return self.input_splitter.indent_spaces * ' '
2072
2074
2073 #-------------------------------------------------------------------------
2075 #-------------------------------------------------------------------------
2074 # Things related to text completion
2076 # Things related to text completion
2075 #-------------------------------------------------------------------------
2077 #-------------------------------------------------------------------------
2076
2078
2077 def init_completer(self):
2079 def init_completer(self):
2078 """Initialize the completion machinery.
2080 """Initialize the completion machinery.
2079
2081
2080 This creates completion machinery that can be used by client code,
2082 This creates completion machinery that can be used by client code,
2081 either interactively in-process (typically triggered by the readline
2083 either interactively in-process (typically triggered by the readline
2082 library), programmatically (such as in test suites) or out-of-process
2084 library), programmatically (such as in test suites) or out-of-process
2083 (typically over the network by remote frontends).
2085 (typically over the network by remote frontends).
2084 """
2086 """
2085 from IPython.core.completer import IPCompleter
2087 from IPython.core.completer import IPCompleter
2086 from IPython.core.completerlib import (module_completer,
2088 from IPython.core.completerlib import (module_completer,
2087 magic_run_completer, cd_completer, reset_completer)
2089 magic_run_completer, cd_completer, reset_completer)
2088
2090
2089 self.Completer = IPCompleter(shell=self,
2091 self.Completer = IPCompleter(shell=self,
2090 namespace=self.user_ns,
2092 namespace=self.user_ns,
2091 global_namespace=self.user_global_ns,
2093 global_namespace=self.user_global_ns,
2092 use_readline=self.has_readline,
2094 use_readline=self.has_readline,
2093 parent=self,
2095 parent=self,
2094 )
2096 )
2095 self.configurables.append(self.Completer)
2097 self.configurables.append(self.Completer)
2096
2098
2097 # Add custom completers to the basic ones built into IPCompleter
2099 # Add custom completers to the basic ones built into IPCompleter
2098 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2100 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2099 self.strdispatchers['complete_command'] = sdisp
2101 self.strdispatchers['complete_command'] = sdisp
2100 self.Completer.custom_completers = sdisp
2102 self.Completer.custom_completers = sdisp
2101
2103
2102 self.set_hook('complete_command', module_completer, str_key = 'import')
2104 self.set_hook('complete_command', module_completer, str_key = 'import')
2103 self.set_hook('complete_command', module_completer, str_key = 'from')
2105 self.set_hook('complete_command', module_completer, str_key = 'from')
2104 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2106 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2105 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2107 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2106 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2108 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2107 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2109 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2108
2110
2109 # Only configure readline if we truly are using readline. IPython can
2111 # Only configure readline if we truly are using readline. IPython can
2110 # do tab-completion over the network, in GUIs, etc, where readline
2112 # do tab-completion over the network, in GUIs, etc, where readline
2111 # itself may be absent
2113 # itself may be absent
2112 if self.has_readline:
2114 if self.has_readline:
2113 self.set_readline_completer()
2115 self.set_readline_completer()
2114
2116
2115 def complete(self, text, line=None, cursor_pos=None):
2117 def complete(self, text, line=None, cursor_pos=None):
2116 """Return the completed text and a list of completions.
2118 """Return the completed text and a list of completions.
2117
2119
2118 Parameters
2120 Parameters
2119 ----------
2121 ----------
2120
2122
2121 text : string
2123 text : string
2122 A string of text to be completed on. It can be given as empty and
2124 A string of text to be completed on. It can be given as empty and
2123 instead a line/position pair are given. In this case, the
2125 instead a line/position pair are given. In this case, the
2124 completer itself will split the line like readline does.
2126 completer itself will split the line like readline does.
2125
2127
2126 line : string, optional
2128 line : string, optional
2127 The complete line that text is part of.
2129 The complete line that text is part of.
2128
2130
2129 cursor_pos : int, optional
2131 cursor_pos : int, optional
2130 The position of the cursor on the input line.
2132 The position of the cursor on the input line.
2131
2133
2132 Returns
2134 Returns
2133 -------
2135 -------
2134 text : string
2136 text : string
2135 The actual text that was completed.
2137 The actual text that was completed.
2136
2138
2137 matches : list
2139 matches : list
2138 A sorted list with all possible completions.
2140 A sorted list with all possible completions.
2139
2141
2140 The optional arguments allow the completion to take more context into
2142 The optional arguments allow the completion to take more context into
2141 account, and are part of the low-level completion API.
2143 account, and are part of the low-level completion API.
2142
2144
2143 This is a wrapper around the completion mechanism, similar to what
2145 This is a wrapper around the completion mechanism, similar to what
2144 readline does at the command line when the TAB key is hit. By
2146 readline does at the command line when the TAB key is hit. By
2145 exposing it as a method, it can be used by other non-readline
2147 exposing it as a method, it can be used by other non-readline
2146 environments (such as GUIs) for text completion.
2148 environments (such as GUIs) for text completion.
2147
2149
2148 Simple usage example:
2150 Simple usage example:
2149
2151
2150 In [1]: x = 'hello'
2152 In [1]: x = 'hello'
2151
2153
2152 In [2]: _ip.complete('x.l')
2154 In [2]: _ip.complete('x.l')
2153 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2155 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2154 """
2156 """
2155
2157
2156 # Inject names into __builtin__ so we can complete on the added names.
2158 # Inject names into __builtin__ so we can complete on the added names.
2157 with self.builtin_trap:
2159 with self.builtin_trap:
2158 return self.Completer.complete(text, line, cursor_pos)
2160 return self.Completer.complete(text, line, cursor_pos)
2159
2161
2160 def set_custom_completer(self, completer, pos=0):
2162 def set_custom_completer(self, completer, pos=0):
2161 """Adds a new custom completer function.
2163 """Adds a new custom completer function.
2162
2164
2163 The position argument (defaults to 0) is the index in the completers
2165 The position argument (defaults to 0) is the index in the completers
2164 list where you want the completer to be inserted."""
2166 list where you want the completer to be inserted."""
2165
2167
2166 newcomp = types.MethodType(completer,self.Completer)
2168 newcomp = types.MethodType(completer,self.Completer)
2167 self.Completer.matchers.insert(pos,newcomp)
2169 self.Completer.matchers.insert(pos,newcomp)
2168
2170
2169 def set_readline_completer(self):
2171 def set_readline_completer(self):
2170 """Reset readline's completer to be our own."""
2172 """Reset readline's completer to be our own."""
2171 self.readline.set_completer(self.Completer.rlcomplete)
2173 self.readline.set_completer(self.Completer.rlcomplete)
2172
2174
2173 def set_completer_frame(self, frame=None):
2175 def set_completer_frame(self, frame=None):
2174 """Set the frame of the completer."""
2176 """Set the frame of the completer."""
2175 if frame:
2177 if frame:
2176 self.Completer.namespace = frame.f_locals
2178 self.Completer.namespace = frame.f_locals
2177 self.Completer.global_namespace = frame.f_globals
2179 self.Completer.global_namespace = frame.f_globals
2178 else:
2180 else:
2179 self.Completer.namespace = self.user_ns
2181 self.Completer.namespace = self.user_ns
2180 self.Completer.global_namespace = self.user_global_ns
2182 self.Completer.global_namespace = self.user_global_ns
2181
2183
2182 #-------------------------------------------------------------------------
2184 #-------------------------------------------------------------------------
2183 # Things related to magics
2185 # Things related to magics
2184 #-------------------------------------------------------------------------
2186 #-------------------------------------------------------------------------
2185
2187
2186 def init_magics(self):
2188 def init_magics(self):
2187 from IPython.core import magics as m
2189 from IPython.core import magics as m
2188 self.magics_manager = magic.MagicsManager(shell=self,
2190 self.magics_manager = magic.MagicsManager(shell=self,
2189 parent=self,
2191 parent=self,
2190 user_magics=m.UserMagics(self))
2192 user_magics=m.UserMagics(self))
2191 self.configurables.append(self.magics_manager)
2193 self.configurables.append(self.magics_manager)
2192
2194
2193 # Expose as public API from the magics manager
2195 # Expose as public API from the magics manager
2194 self.register_magics = self.magics_manager.register
2196 self.register_magics = self.magics_manager.register
2195 self.define_magic = self.magics_manager.define_magic
2197 self.define_magic = self.magics_manager.define_magic
2196
2198
2197 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2199 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2198 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2200 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2199 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2201 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2200 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2202 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2201 )
2203 )
2202
2204
2203 # Register Magic Aliases
2205 # Register Magic Aliases
2204 mman = self.magics_manager
2206 mman = self.magics_manager
2205 # FIXME: magic aliases should be defined by the Magics classes
2207 # FIXME: magic aliases should be defined by the Magics classes
2206 # or in MagicsManager, not here
2208 # or in MagicsManager, not here
2207 mman.register_alias('ed', 'edit')
2209 mman.register_alias('ed', 'edit')
2208 mman.register_alias('hist', 'history')
2210 mman.register_alias('hist', 'history')
2209 mman.register_alias('rep', 'recall')
2211 mman.register_alias('rep', 'recall')
2210 mman.register_alias('SVG', 'svg', 'cell')
2212 mman.register_alias('SVG', 'svg', 'cell')
2211 mman.register_alias('HTML', 'html', 'cell')
2213 mman.register_alias('HTML', 'html', 'cell')
2212 mman.register_alias('file', 'writefile', 'cell')
2214 mman.register_alias('file', 'writefile', 'cell')
2213
2215
2214 # FIXME: Move the color initialization to the DisplayHook, which
2216 # FIXME: Move the color initialization to the DisplayHook, which
2215 # should be split into a prompt manager and displayhook. We probably
2217 # should be split into a prompt manager and displayhook. We probably
2216 # even need a centralize colors management object.
2218 # even need a centralize colors management object.
2217 self.magic('colors %s' % self.colors)
2219 self.magic('colors %s' % self.colors)
2218
2220
2219 # Defined here so that it's included in the documentation
2221 # Defined here so that it's included in the documentation
2220 @functools.wraps(magic.MagicsManager.register_function)
2222 @functools.wraps(magic.MagicsManager.register_function)
2221 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2223 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2222 self.magics_manager.register_function(func,
2224 self.magics_manager.register_function(func,
2223 magic_kind=magic_kind, magic_name=magic_name)
2225 magic_kind=magic_kind, magic_name=magic_name)
2224
2226
2225 def run_line_magic(self, magic_name, line):
2227 def run_line_magic(self, magic_name, line):
2226 """Execute the given line magic.
2228 """Execute the given line magic.
2227
2229
2228 Parameters
2230 Parameters
2229 ----------
2231 ----------
2230 magic_name : str
2232 magic_name : str
2231 Name of the desired magic function, without '%' prefix.
2233 Name of the desired magic function, without '%' prefix.
2232
2234
2233 line : str
2235 line : str
2234 The rest of the input line as a single string.
2236 The rest of the input line as a single string.
2235 """
2237 """
2236 fn = self.find_line_magic(magic_name)
2238 fn = self.find_line_magic(magic_name)
2237 if fn is None:
2239 if fn is None:
2238 cm = self.find_cell_magic(magic_name)
2240 cm = self.find_cell_magic(magic_name)
2239 etpl = "Line magic function `%%%s` not found%s."
2241 etpl = "Line magic function `%%%s` not found%s."
2240 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2242 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2241 'did you mean that instead?)' % magic_name )
2243 'did you mean that instead?)' % magic_name )
2242 error(etpl % (magic_name, extra))
2244 error(etpl % (magic_name, extra))
2243 else:
2245 else:
2244 # Note: this is the distance in the stack to the user's frame.
2246 # Note: this is the distance in the stack to the user's frame.
2245 # This will need to be updated if the internal calling logic gets
2247 # This will need to be updated if the internal calling logic gets
2246 # refactored, or else we'll be expanding the wrong variables.
2248 # refactored, or else we'll be expanding the wrong variables.
2247 stack_depth = 2
2249 stack_depth = 2
2248 magic_arg_s = self.var_expand(line, stack_depth)
2250 magic_arg_s = self.var_expand(line, stack_depth)
2249 # Put magic args in a list so we can call with f(*a) syntax
2251 # Put magic args in a list so we can call with f(*a) syntax
2250 args = [magic_arg_s]
2252 args = [magic_arg_s]
2251 kwargs = {}
2253 kwargs = {}
2252 # Grab local namespace if we need it:
2254 # Grab local namespace if we need it:
2253 if getattr(fn, "needs_local_scope", False):
2255 if getattr(fn, "needs_local_scope", False):
2254 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2256 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2255 with self.builtin_trap:
2257 with self.builtin_trap:
2256 result = fn(*args,**kwargs)
2258 result = fn(*args,**kwargs)
2257 return result
2259 return result
2258
2260
2259 def run_cell_magic(self, magic_name, line, cell):
2261 def run_cell_magic(self, magic_name, line, cell):
2260 """Execute the given cell magic.
2262 """Execute the given cell magic.
2261
2263
2262 Parameters
2264 Parameters
2263 ----------
2265 ----------
2264 magic_name : str
2266 magic_name : str
2265 Name of the desired magic function, without '%' prefix.
2267 Name of the desired magic function, without '%' prefix.
2266
2268
2267 line : str
2269 line : str
2268 The rest of the first input line as a single string.
2270 The rest of the first input line as a single string.
2269
2271
2270 cell : str
2272 cell : str
2271 The body of the cell as a (possibly multiline) string.
2273 The body of the cell as a (possibly multiline) string.
2272 """
2274 """
2273 fn = self.find_cell_magic(magic_name)
2275 fn = self.find_cell_magic(magic_name)
2274 if fn is None:
2276 if fn is None:
2275 lm = self.find_line_magic(magic_name)
2277 lm = self.find_line_magic(magic_name)
2276 etpl = "Cell magic `%%{0}` not found{1}."
2278 etpl = "Cell magic `%%{0}` not found{1}."
2277 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2279 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2278 'did you mean that instead?)'.format(magic_name))
2280 'did you mean that instead?)'.format(magic_name))
2279 error(etpl.format(magic_name, extra))
2281 error(etpl.format(magic_name, extra))
2280 elif cell == '':
2282 elif cell == '':
2281 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2283 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2282 if self.find_line_magic(magic_name) is not None:
2284 if self.find_line_magic(magic_name) is not None:
2283 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2285 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2284 raise UsageError(message)
2286 raise UsageError(message)
2285 else:
2287 else:
2286 # Note: this is the distance in the stack to the user's frame.
2288 # Note: this is the distance in the stack to the user's frame.
2287 # This will need to be updated if the internal calling logic gets
2289 # This will need to be updated if the internal calling logic gets
2288 # refactored, or else we'll be expanding the wrong variables.
2290 # refactored, or else we'll be expanding the wrong variables.
2289 stack_depth = 2
2291 stack_depth = 2
2290 magic_arg_s = self.var_expand(line, stack_depth)
2292 magic_arg_s = self.var_expand(line, stack_depth)
2291 with self.builtin_trap:
2293 with self.builtin_trap:
2292 result = fn(magic_arg_s, cell)
2294 result = fn(magic_arg_s, cell)
2293 return result
2295 return result
2294
2296
2295 def find_line_magic(self, magic_name):
2297 def find_line_magic(self, magic_name):
2296 """Find and return a line magic by name.
2298 """Find and return a line magic by name.
2297
2299
2298 Returns None if the magic isn't found."""
2300 Returns None if the magic isn't found."""
2299 return self.magics_manager.magics['line'].get(magic_name)
2301 return self.magics_manager.magics['line'].get(magic_name)
2300
2302
2301 def find_cell_magic(self, magic_name):
2303 def find_cell_magic(self, magic_name):
2302 """Find and return a cell magic by name.
2304 """Find and return a cell magic by name.
2303
2305
2304 Returns None if the magic isn't found."""
2306 Returns None if the magic isn't found."""
2305 return self.magics_manager.magics['cell'].get(magic_name)
2307 return self.magics_manager.magics['cell'].get(magic_name)
2306
2308
2307 def find_magic(self, magic_name, magic_kind='line'):
2309 def find_magic(self, magic_name, magic_kind='line'):
2308 """Find and return a magic of the given type by name.
2310 """Find and return a magic of the given type by name.
2309
2311
2310 Returns None if the magic isn't found."""
2312 Returns None if the magic isn't found."""
2311 return self.magics_manager.magics[magic_kind].get(magic_name)
2313 return self.magics_manager.magics[magic_kind].get(magic_name)
2312
2314
2313 def magic(self, arg_s):
2315 def magic(self, arg_s):
2314 """DEPRECATED. Use run_line_magic() instead.
2316 """DEPRECATED. Use run_line_magic() instead.
2315
2317
2316 Call a magic function by name.
2318 Call a magic function by name.
2317
2319
2318 Input: a string containing the name of the magic function to call and
2320 Input: a string containing the name of the magic function to call and
2319 any additional arguments to be passed to the magic.
2321 any additional arguments to be passed to the magic.
2320
2322
2321 magic('name -opt foo bar') is equivalent to typing at the ipython
2323 magic('name -opt foo bar') is equivalent to typing at the ipython
2322 prompt:
2324 prompt:
2323
2325
2324 In[1]: %name -opt foo bar
2326 In[1]: %name -opt foo bar
2325
2327
2326 To call a magic without arguments, simply use magic('name').
2328 To call a magic without arguments, simply use magic('name').
2327
2329
2328 This provides a proper Python function to call IPython's magics in any
2330 This provides a proper Python function to call IPython's magics in any
2329 valid Python code you can type at the interpreter, including loops and
2331 valid Python code you can type at the interpreter, including loops and
2330 compound statements.
2332 compound statements.
2331 """
2333 """
2332 # TODO: should we issue a loud deprecation warning here?
2334 # TODO: should we issue a loud deprecation warning here?
2333 magic_name, _, magic_arg_s = arg_s.partition(' ')
2335 magic_name, _, magic_arg_s = arg_s.partition(' ')
2334 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2336 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2335 return self.run_line_magic(magic_name, magic_arg_s)
2337 return self.run_line_magic(magic_name, magic_arg_s)
2336
2338
2337 #-------------------------------------------------------------------------
2339 #-------------------------------------------------------------------------
2338 # Things related to macros
2340 # Things related to macros
2339 #-------------------------------------------------------------------------
2341 #-------------------------------------------------------------------------
2340
2342
2341 def define_macro(self, name, themacro):
2343 def define_macro(self, name, themacro):
2342 """Define a new macro
2344 """Define a new macro
2343
2345
2344 Parameters
2346 Parameters
2345 ----------
2347 ----------
2346 name : str
2348 name : str
2347 The name of the macro.
2349 The name of the macro.
2348 themacro : str or Macro
2350 themacro : str or Macro
2349 The action to do upon invoking the macro. If a string, a new
2351 The action to do upon invoking the macro. If a string, a new
2350 Macro object is created by passing the string to it.
2352 Macro object is created by passing the string to it.
2351 """
2353 """
2352
2354
2353 from IPython.core import macro
2355 from IPython.core import macro
2354
2356
2355 if isinstance(themacro, string_types):
2357 if isinstance(themacro, string_types):
2356 themacro = macro.Macro(themacro)
2358 themacro = macro.Macro(themacro)
2357 if not isinstance(themacro, macro.Macro):
2359 if not isinstance(themacro, macro.Macro):
2358 raise ValueError('A macro must be a string or a Macro instance.')
2360 raise ValueError('A macro must be a string or a Macro instance.')
2359 self.user_ns[name] = themacro
2361 self.user_ns[name] = themacro
2360
2362
2361 #-------------------------------------------------------------------------
2363 #-------------------------------------------------------------------------
2362 # Things related to the running of system commands
2364 # Things related to the running of system commands
2363 #-------------------------------------------------------------------------
2365 #-------------------------------------------------------------------------
2364
2366
2365 def system_piped(self, cmd):
2367 def system_piped(self, cmd):
2366 """Call the given cmd in a subprocess, piping stdout/err
2368 """Call the given cmd in a subprocess, piping stdout/err
2367
2369
2368 Parameters
2370 Parameters
2369 ----------
2371 ----------
2370 cmd : str
2372 cmd : str
2371 Command to execute (can not end in '&', as background processes are
2373 Command to execute (can not end in '&', as background processes are
2372 not supported. Should not be a command that expects input
2374 not supported. Should not be a command that expects input
2373 other than simple text.
2375 other than simple text.
2374 """
2376 """
2375 if cmd.rstrip().endswith('&'):
2377 if cmd.rstrip().endswith('&'):
2376 # this is *far* from a rigorous test
2378 # this is *far* from a rigorous test
2377 # We do not support backgrounding processes because we either use
2379 # We do not support backgrounding processes because we either use
2378 # pexpect or pipes to read from. Users can always just call
2380 # pexpect or pipes to read from. Users can always just call
2379 # os.system() or use ip.system=ip.system_raw
2381 # os.system() or use ip.system=ip.system_raw
2380 # if they really want a background process.
2382 # if they really want a background process.
2381 raise OSError("Background processes not supported.")
2383 raise OSError("Background processes not supported.")
2382
2384
2383 # we explicitly do NOT return the subprocess status code, because
2385 # we explicitly do NOT return the subprocess status code, because
2384 # a non-None value would trigger :func:`sys.displayhook` calls.
2386 # a non-None value would trigger :func:`sys.displayhook` calls.
2385 # Instead, we store the exit_code in user_ns.
2387 # Instead, we store the exit_code in user_ns.
2386 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2388 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2387
2389
2388 def system_raw(self, cmd):
2390 def system_raw(self, cmd):
2389 """Call the given cmd in a subprocess using os.system on Windows or
2391 """Call the given cmd in a subprocess using os.system on Windows or
2390 subprocess.call using the system shell on other platforms.
2392 subprocess.call using the system shell on other platforms.
2391
2393
2392 Parameters
2394 Parameters
2393 ----------
2395 ----------
2394 cmd : str
2396 cmd : str
2395 Command to execute.
2397 Command to execute.
2396 """
2398 """
2397 cmd = self.var_expand(cmd, depth=1)
2399 cmd = self.var_expand(cmd, depth=1)
2398 # protect os.system from UNC paths on Windows, which it can't handle:
2400 # protect os.system from UNC paths on Windows, which it can't handle:
2399 if sys.platform == 'win32':
2401 if sys.platform == 'win32':
2400 from IPython.utils._process_win32 import AvoidUNCPath
2402 from IPython.utils._process_win32 import AvoidUNCPath
2401 with AvoidUNCPath() as path:
2403 with AvoidUNCPath() as path:
2402 if path is not None:
2404 if path is not None:
2403 cmd = '"pushd %s &&"%s' % (path, cmd)
2405 cmd = '"pushd %s &&"%s' % (path, cmd)
2404 cmd = py3compat.unicode_to_str(cmd)
2406 cmd = py3compat.unicode_to_str(cmd)
2405 try:
2407 try:
2406 ec = os.system(cmd)
2408 ec = os.system(cmd)
2407 except KeyboardInterrupt:
2409 except KeyboardInterrupt:
2408 self.write_err('\n' + self.get_exception_only())
2410 self.write_err('\n' + self.get_exception_only())
2409 ec = -2
2411 ec = -2
2410 else:
2412 else:
2411 cmd = py3compat.unicode_to_str(cmd)
2413 cmd = py3compat.unicode_to_str(cmd)
2412 # For posix the result of the subprocess.call() below is an exit
2414 # For posix the result of the subprocess.call() below is an exit
2413 # code, which by convention is zero for success, positive for
2415 # code, which by convention is zero for success, positive for
2414 # program failure. Exit codes above 128 are reserved for signals,
2416 # program failure. Exit codes above 128 are reserved for signals,
2415 # and the formula for converting a signal to an exit code is usually
2417 # and the formula for converting a signal to an exit code is usually
2416 # signal_number+128. To more easily differentiate between exit
2418 # signal_number+128. To more easily differentiate between exit
2417 # codes and signals, ipython uses negative numbers. For instance
2419 # codes and signals, ipython uses negative numbers. For instance
2418 # since control-c is signal 2 but exit code 130, ipython's
2420 # since control-c is signal 2 but exit code 130, ipython's
2419 # _exit_code variable will read -2. Note that some shells like
2421 # _exit_code variable will read -2. Note that some shells like
2420 # csh and fish don't follow sh/bash conventions for exit codes.
2422 # csh and fish don't follow sh/bash conventions for exit codes.
2421 executable = os.environ.get('SHELL', None)
2423 executable = os.environ.get('SHELL', None)
2422 try:
2424 try:
2423 # Use env shell instead of default /bin/sh
2425 # Use env shell instead of default /bin/sh
2424 ec = subprocess.call(cmd, shell=True, executable=executable)
2426 ec = subprocess.call(cmd, shell=True, executable=executable)
2425 except KeyboardInterrupt:
2427 except KeyboardInterrupt:
2426 # intercept control-C; a long traceback is not useful here
2428 # intercept control-C; a long traceback is not useful here
2427 self.write_err('\n' + self.get_exception_only())
2429 self.write_err('\n' + self.get_exception_only())
2428 ec = 130
2430 ec = 130
2429 if ec > 128:
2431 if ec > 128:
2430 ec = -(ec - 128)
2432 ec = -(ec - 128)
2431
2433
2432 # We explicitly do NOT return the subprocess status code, because
2434 # We explicitly do NOT return the subprocess status code, because
2433 # a non-None value would trigger :func:`sys.displayhook` calls.
2435 # a non-None value would trigger :func:`sys.displayhook` calls.
2434 # Instead, we store the exit_code in user_ns. Note the semantics
2436 # Instead, we store the exit_code in user_ns. Note the semantics
2435 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2437 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2436 # but raising SystemExit(_exit_code) will give status 254!
2438 # but raising SystemExit(_exit_code) will give status 254!
2437 self.user_ns['_exit_code'] = ec
2439 self.user_ns['_exit_code'] = ec
2438
2440
2439 # use piped system by default, because it is better behaved
2441 # use piped system by default, because it is better behaved
2440 system = system_piped
2442 system = system_piped
2441
2443
2442 def getoutput(self, cmd, split=True, depth=0):
2444 def getoutput(self, cmd, split=True, depth=0):
2443 """Get output (possibly including stderr) from a subprocess.
2445 """Get output (possibly including stderr) from a subprocess.
2444
2446
2445 Parameters
2447 Parameters
2446 ----------
2448 ----------
2447 cmd : str
2449 cmd : str
2448 Command to execute (can not end in '&', as background processes are
2450 Command to execute (can not end in '&', as background processes are
2449 not supported.
2451 not supported.
2450 split : bool, optional
2452 split : bool, optional
2451 If True, split the output into an IPython SList. Otherwise, an
2453 If True, split the output into an IPython SList. Otherwise, an
2452 IPython LSString is returned. These are objects similar to normal
2454 IPython LSString is returned. These are objects similar to normal
2453 lists and strings, with a few convenience attributes for easier
2455 lists and strings, with a few convenience attributes for easier
2454 manipulation of line-based output. You can use '?' on them for
2456 manipulation of line-based output. You can use '?' on them for
2455 details.
2457 details.
2456 depth : int, optional
2458 depth : int, optional
2457 How many frames above the caller are the local variables which should
2459 How many frames above the caller are the local variables which should
2458 be expanded in the command string? The default (0) assumes that the
2460 be expanded in the command string? The default (0) assumes that the
2459 expansion variables are in the stack frame calling this function.
2461 expansion variables are in the stack frame calling this function.
2460 """
2462 """
2461 if cmd.rstrip().endswith('&'):
2463 if cmd.rstrip().endswith('&'):
2462 # this is *far* from a rigorous test
2464 # this is *far* from a rigorous test
2463 raise OSError("Background processes not supported.")
2465 raise OSError("Background processes not supported.")
2464 out = getoutput(self.var_expand(cmd, depth=depth+1))
2466 out = getoutput(self.var_expand(cmd, depth=depth+1))
2465 if split:
2467 if split:
2466 out = SList(out.splitlines())
2468 out = SList(out.splitlines())
2467 else:
2469 else:
2468 out = LSString(out)
2470 out = LSString(out)
2469 return out
2471 return out
2470
2472
2471 #-------------------------------------------------------------------------
2473 #-------------------------------------------------------------------------
2472 # Things related to aliases
2474 # Things related to aliases
2473 #-------------------------------------------------------------------------
2475 #-------------------------------------------------------------------------
2474
2476
2475 def init_alias(self):
2477 def init_alias(self):
2476 self.alias_manager = AliasManager(shell=self, parent=self)
2478 self.alias_manager = AliasManager(shell=self, parent=self)
2477 self.configurables.append(self.alias_manager)
2479 self.configurables.append(self.alias_manager)
2478
2480
2479 #-------------------------------------------------------------------------
2481 #-------------------------------------------------------------------------
2480 # Things related to extensions
2482 # Things related to extensions
2481 #-------------------------------------------------------------------------
2483 #-------------------------------------------------------------------------
2482
2484
2483 def init_extension_manager(self):
2485 def init_extension_manager(self):
2484 self.extension_manager = ExtensionManager(shell=self, parent=self)
2486 self.extension_manager = ExtensionManager(shell=self, parent=self)
2485 self.configurables.append(self.extension_manager)
2487 self.configurables.append(self.extension_manager)
2486
2488
2487 #-------------------------------------------------------------------------
2489 #-------------------------------------------------------------------------
2488 # Things related to payloads
2490 # Things related to payloads
2489 #-------------------------------------------------------------------------
2491 #-------------------------------------------------------------------------
2490
2492
2491 def init_payload(self):
2493 def init_payload(self):
2492 self.payload_manager = PayloadManager(parent=self)
2494 self.payload_manager = PayloadManager(parent=self)
2493 self.configurables.append(self.payload_manager)
2495 self.configurables.append(self.payload_manager)
2494
2496
2495 #-------------------------------------------------------------------------
2497 #-------------------------------------------------------------------------
2496 # Things related to the prefilter
2498 # Things related to the prefilter
2497 #-------------------------------------------------------------------------
2499 #-------------------------------------------------------------------------
2498
2500
2499 def init_prefilter(self):
2501 def init_prefilter(self):
2500 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2502 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2501 self.configurables.append(self.prefilter_manager)
2503 self.configurables.append(self.prefilter_manager)
2502 # Ultimately this will be refactored in the new interpreter code, but
2504 # Ultimately this will be refactored in the new interpreter code, but
2503 # for now, we should expose the main prefilter method (there's legacy
2505 # for now, we should expose the main prefilter method (there's legacy
2504 # code out there that may rely on this).
2506 # code out there that may rely on this).
2505 self.prefilter = self.prefilter_manager.prefilter_lines
2507 self.prefilter = self.prefilter_manager.prefilter_lines
2506
2508
2507 def auto_rewrite_input(self, cmd):
2509 def auto_rewrite_input(self, cmd):
2508 """Print to the screen the rewritten form of the user's command.
2510 """Print to the screen the rewritten form of the user's command.
2509
2511
2510 This shows visual feedback by rewriting input lines that cause
2512 This shows visual feedback by rewriting input lines that cause
2511 automatic calling to kick in, like::
2513 automatic calling to kick in, like::
2512
2514
2513 /f x
2515 /f x
2514
2516
2515 into::
2517 into::
2516
2518
2517 ------> f(x)
2519 ------> f(x)
2518
2520
2519 after the user's input prompt. This helps the user understand that the
2521 after the user's input prompt. This helps the user understand that the
2520 input line was transformed automatically by IPython.
2522 input line was transformed automatically by IPython.
2521 """
2523 """
2522 if not self.show_rewritten_input:
2524 if not self.show_rewritten_input:
2523 return
2525 return
2524
2526
2525 rw = self.prompt_manager.render('rewrite') + cmd
2527 rw = self.prompt_manager.render('rewrite') + cmd
2526
2528
2527 try:
2529 try:
2528 # plain ascii works better w/ pyreadline, on some machines, so
2530 # plain ascii works better w/ pyreadline, on some machines, so
2529 # we use it and only print uncolored rewrite if we have unicode
2531 # we use it and only print uncolored rewrite if we have unicode
2530 rw = str(rw)
2532 rw = str(rw)
2531 print(rw, file=io.stdout)
2533 print(rw, file=io.stdout)
2532 except UnicodeEncodeError:
2534 except UnicodeEncodeError:
2533 print("------> " + cmd)
2535 print("------> " + cmd)
2534
2536
2535 #-------------------------------------------------------------------------
2537 #-------------------------------------------------------------------------
2536 # Things related to extracting values/expressions from kernel and user_ns
2538 # Things related to extracting values/expressions from kernel and user_ns
2537 #-------------------------------------------------------------------------
2539 #-------------------------------------------------------------------------
2538
2540
2539 def _user_obj_error(self):
2541 def _user_obj_error(self):
2540 """return simple exception dict
2542 """return simple exception dict
2541
2543
2542 for use in user_expressions
2544 for use in user_expressions
2543 """
2545 """
2544
2546
2545 etype, evalue, tb = self._get_exc_info()
2547 etype, evalue, tb = self._get_exc_info()
2546 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2548 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2547
2549
2548 exc_info = {
2550 exc_info = {
2549 u'status' : 'error',
2551 u'status' : 'error',
2550 u'traceback' : stb,
2552 u'traceback' : stb,
2551 u'ename' : unicode_type(etype.__name__),
2553 u'ename' : unicode_type(etype.__name__),
2552 u'evalue' : py3compat.safe_unicode(evalue),
2554 u'evalue' : py3compat.safe_unicode(evalue),
2553 }
2555 }
2554
2556
2555 return exc_info
2557 return exc_info
2556
2558
2557 def _format_user_obj(self, obj):
2559 def _format_user_obj(self, obj):
2558 """format a user object to display dict
2560 """format a user object to display dict
2559
2561
2560 for use in user_expressions
2562 for use in user_expressions
2561 """
2563 """
2562
2564
2563 data, md = self.display_formatter.format(obj)
2565 data, md = self.display_formatter.format(obj)
2564 value = {
2566 value = {
2565 'status' : 'ok',
2567 'status' : 'ok',
2566 'data' : data,
2568 'data' : data,
2567 'metadata' : md,
2569 'metadata' : md,
2568 }
2570 }
2569 return value
2571 return value
2570
2572
2571 def user_expressions(self, expressions):
2573 def user_expressions(self, expressions):
2572 """Evaluate a dict of expressions in the user's namespace.
2574 """Evaluate a dict of expressions in the user's namespace.
2573
2575
2574 Parameters
2576 Parameters
2575 ----------
2577 ----------
2576 expressions : dict
2578 expressions : dict
2577 A dict with string keys and string values. The expression values
2579 A dict with string keys and string values. The expression values
2578 should be valid Python expressions, each of which will be evaluated
2580 should be valid Python expressions, each of which will be evaluated
2579 in the user namespace.
2581 in the user namespace.
2580
2582
2581 Returns
2583 Returns
2582 -------
2584 -------
2583 A dict, keyed like the input expressions dict, with the rich mime-typed
2585 A dict, keyed like the input expressions dict, with the rich mime-typed
2584 display_data of each value.
2586 display_data of each value.
2585 """
2587 """
2586 out = {}
2588 out = {}
2587 user_ns = self.user_ns
2589 user_ns = self.user_ns
2588 global_ns = self.user_global_ns
2590 global_ns = self.user_global_ns
2589
2591
2590 for key, expr in iteritems(expressions):
2592 for key, expr in iteritems(expressions):
2591 try:
2593 try:
2592 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2594 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2593 except:
2595 except:
2594 value = self._user_obj_error()
2596 value = self._user_obj_error()
2595 out[key] = value
2597 out[key] = value
2596 return out
2598 return out
2597
2599
2598 #-------------------------------------------------------------------------
2600 #-------------------------------------------------------------------------
2599 # Things related to the running of code
2601 # Things related to the running of code
2600 #-------------------------------------------------------------------------
2602 #-------------------------------------------------------------------------
2601
2603
2602 def ex(self, cmd):
2604 def ex(self, cmd):
2603 """Execute a normal python statement in user namespace."""
2605 """Execute a normal python statement in user namespace."""
2604 with self.builtin_trap:
2606 with self.builtin_trap:
2605 exec(cmd, self.user_global_ns, self.user_ns)
2607 exec(cmd, self.user_global_ns, self.user_ns)
2606
2608
2607 def ev(self, expr):
2609 def ev(self, expr):
2608 """Evaluate python expression expr in user namespace.
2610 """Evaluate python expression expr in user namespace.
2609
2611
2610 Returns the result of evaluation
2612 Returns the result of evaluation
2611 """
2613 """
2612 with self.builtin_trap:
2614 with self.builtin_trap:
2613 return eval(expr, self.user_global_ns, self.user_ns)
2615 return eval(expr, self.user_global_ns, self.user_ns)
2614
2616
2615 def safe_execfile(self, fname, *where, **kw):
2617 def safe_execfile(self, fname, *where, **kw):
2616 """A safe version of the builtin execfile().
2618 """A safe version of the builtin execfile().
2617
2619
2618 This version will never throw an exception, but instead print
2620 This version will never throw an exception, but instead print
2619 helpful error messages to the screen. This only works on pure
2621 helpful error messages to the screen. This only works on pure
2620 Python files with the .py extension.
2622 Python files with the .py extension.
2621
2623
2622 Parameters
2624 Parameters
2623 ----------
2625 ----------
2624 fname : string
2626 fname : string
2625 The name of the file to be executed.
2627 The name of the file to be executed.
2626 where : tuple
2628 where : tuple
2627 One or two namespaces, passed to execfile() as (globals,locals).
2629 One or two namespaces, passed to execfile() as (globals,locals).
2628 If only one is given, it is passed as both.
2630 If only one is given, it is passed as both.
2629 exit_ignore : bool (False)
2631 exit_ignore : bool (False)
2630 If True, then silence SystemExit for non-zero status (it is always
2632 If True, then silence SystemExit for non-zero status (it is always
2631 silenced for zero status, as it is so common).
2633 silenced for zero status, as it is so common).
2632 raise_exceptions : bool (False)
2634 raise_exceptions : bool (False)
2633 If True raise exceptions everywhere. Meant for testing.
2635 If True raise exceptions everywhere. Meant for testing.
2634 shell_futures : bool (False)
2636 shell_futures : bool (False)
2635 If True, the code will share future statements with the interactive
2637 If True, the code will share future statements with the interactive
2636 shell. It will both be affected by previous __future__ imports, and
2638 shell. It will both be affected by previous __future__ imports, and
2637 any __future__ imports in the code will affect the shell. If False,
2639 any __future__ imports in the code will affect the shell. If False,
2638 __future__ imports are not shared in either direction.
2640 __future__ imports are not shared in either direction.
2639
2641
2640 """
2642 """
2641 kw.setdefault('exit_ignore', False)
2643 kw.setdefault('exit_ignore', False)
2642 kw.setdefault('raise_exceptions', False)
2644 kw.setdefault('raise_exceptions', False)
2643 kw.setdefault('shell_futures', False)
2645 kw.setdefault('shell_futures', False)
2644
2646
2645 fname = os.path.abspath(os.path.expanduser(fname))
2647 fname = os.path.abspath(os.path.expanduser(fname))
2646
2648
2647 # Make sure we can open the file
2649 # Make sure we can open the file
2648 try:
2650 try:
2649 with open(fname):
2651 with open(fname):
2650 pass
2652 pass
2651 except:
2653 except:
2652 warn('Could not open file <%s> for safe execution.' % fname)
2654 warn('Could not open file <%s> for safe execution.' % fname)
2653 return
2655 return
2654
2656
2655 # Find things also in current directory. This is needed to mimic the
2657 # Find things also in current directory. This is needed to mimic the
2656 # behavior of running a script from the system command line, where
2658 # behavior of running a script from the system command line, where
2657 # Python inserts the script's directory into sys.path
2659 # Python inserts the script's directory into sys.path
2658 dname = os.path.dirname(fname)
2660 dname = os.path.dirname(fname)
2659
2661
2660 with prepended_to_syspath(dname):
2662 with prepended_to_syspath(dname):
2661 try:
2663 try:
2662 glob, loc = (where + (None, ))[:2]
2664 glob, loc = (where + (None, ))[:2]
2663 py3compat.execfile(
2665 py3compat.execfile(
2664 fname, glob, loc,
2666 fname, glob, loc,
2665 self.compile if kw['shell_futures'] else None)
2667 self.compile if kw['shell_futures'] else None)
2666 except SystemExit as status:
2668 except SystemExit as status:
2667 # If the call was made with 0 or None exit status (sys.exit(0)
2669 # If the call was made with 0 or None exit status (sys.exit(0)
2668 # or sys.exit() ), don't bother showing a traceback, as both of
2670 # or sys.exit() ), don't bother showing a traceback, as both of
2669 # these are considered normal by the OS:
2671 # these are considered normal by the OS:
2670 # > python -c'import sys;sys.exit(0)'; echo $?
2672 # > python -c'import sys;sys.exit(0)'; echo $?
2671 # 0
2673 # 0
2672 # > python -c'import sys;sys.exit()'; echo $?
2674 # > python -c'import sys;sys.exit()'; echo $?
2673 # 0
2675 # 0
2674 # For other exit status, we show the exception unless
2676 # For other exit status, we show the exception unless
2675 # explicitly silenced, but only in short form.
2677 # explicitly silenced, but only in short form.
2676 if status.code:
2678 if status.code:
2677 if kw['raise_exceptions']:
2679 if kw['raise_exceptions']:
2678 raise
2680 raise
2679 if not kw['exit_ignore']:
2681 if not kw['exit_ignore']:
2680 self.showtraceback(exception_only=True)
2682 self.showtraceback(exception_only=True)
2681 except:
2683 except:
2682 if kw['raise_exceptions']:
2684 if kw['raise_exceptions']:
2683 raise
2685 raise
2684 # tb offset is 2 because we wrap execfile
2686 # tb offset is 2 because we wrap execfile
2685 self.showtraceback(tb_offset=2)
2687 self.showtraceback(tb_offset=2)
2686
2688
2687 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2689 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2688 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2690 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2689
2691
2690 Parameters
2692 Parameters
2691 ----------
2693 ----------
2692 fname : str
2694 fname : str
2693 The name of the file to execute. The filename must have a
2695 The name of the file to execute. The filename must have a
2694 .ipy or .ipynb extension.
2696 .ipy or .ipynb extension.
2695 shell_futures : bool (False)
2697 shell_futures : bool (False)
2696 If True, the code will share future statements with the interactive
2698 If True, the code will share future statements with the interactive
2697 shell. It will both be affected by previous __future__ imports, and
2699 shell. It will both be affected by previous __future__ imports, and
2698 any __future__ imports in the code will affect the shell. If False,
2700 any __future__ imports in the code will affect the shell. If False,
2699 __future__ imports are not shared in either direction.
2701 __future__ imports are not shared in either direction.
2700 raise_exceptions : bool (False)
2702 raise_exceptions : bool (False)
2701 If True raise exceptions everywhere. Meant for testing.
2703 If True raise exceptions everywhere. Meant for testing.
2702 """
2704 """
2703 fname = os.path.abspath(os.path.expanduser(fname))
2705 fname = os.path.abspath(os.path.expanduser(fname))
2704
2706
2705 # Make sure we can open the file
2707 # Make sure we can open the file
2706 try:
2708 try:
2707 with open(fname):
2709 with open(fname):
2708 pass
2710 pass
2709 except:
2711 except:
2710 warn('Could not open file <%s> for safe execution.' % fname)
2712 warn('Could not open file <%s> for safe execution.' % fname)
2711 return
2713 return
2712
2714
2713 # Find things also in current directory. This is needed to mimic the
2715 # Find things also in current directory. This is needed to mimic the
2714 # behavior of running a script from the system command line, where
2716 # behavior of running a script from the system command line, where
2715 # Python inserts the script's directory into sys.path
2717 # Python inserts the script's directory into sys.path
2716 dname = os.path.dirname(fname)
2718 dname = os.path.dirname(fname)
2717
2719
2718 def get_cells():
2720 def get_cells():
2719 """generator for sequence of code blocks to run"""
2721 """generator for sequence of code blocks to run"""
2720 if fname.endswith('.ipynb'):
2722 if fname.endswith('.ipynb'):
2721 from nbformat import read
2723 from nbformat import read
2722 with io_open(fname) as f:
2724 with io_open(fname) as f:
2723 nb = read(f, as_version=4)
2725 nb = read(f, as_version=4)
2724 if not nb.cells:
2726 if not nb.cells:
2725 return
2727 return
2726 for cell in nb.cells:
2728 for cell in nb.cells:
2727 if cell.cell_type == 'code':
2729 if cell.cell_type == 'code':
2728 yield cell.source
2730 yield cell.source
2729 else:
2731 else:
2730 with open(fname) as f:
2732 with open(fname) as f:
2731 yield f.read()
2733 yield f.read()
2732
2734
2733 with prepended_to_syspath(dname):
2735 with prepended_to_syspath(dname):
2734 try:
2736 try:
2735 for cell in get_cells():
2737 for cell in get_cells():
2736 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2738 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2737 if raise_exceptions:
2739 if raise_exceptions:
2738 result.raise_error()
2740 result.raise_error()
2739 elif not result.success:
2741 elif not result.success:
2740 break
2742 break
2741 except:
2743 except:
2742 if raise_exceptions:
2744 if raise_exceptions:
2743 raise
2745 raise
2744 self.showtraceback()
2746 self.showtraceback()
2745 warn('Unknown failure executing file: <%s>' % fname)
2747 warn('Unknown failure executing file: <%s>' % fname)
2746
2748
2747 def safe_run_module(self, mod_name, where):
2749 def safe_run_module(self, mod_name, where):
2748 """A safe version of runpy.run_module().
2750 """A safe version of runpy.run_module().
2749
2751
2750 This version will never throw an exception, but instead print
2752 This version will never throw an exception, but instead print
2751 helpful error messages to the screen.
2753 helpful error messages to the screen.
2752
2754
2753 `SystemExit` exceptions with status code 0 or None are ignored.
2755 `SystemExit` exceptions with status code 0 or None are ignored.
2754
2756
2755 Parameters
2757 Parameters
2756 ----------
2758 ----------
2757 mod_name : string
2759 mod_name : string
2758 The name of the module to be executed.
2760 The name of the module to be executed.
2759 where : dict
2761 where : dict
2760 The globals namespace.
2762 The globals namespace.
2761 """
2763 """
2762 try:
2764 try:
2763 try:
2765 try:
2764 where.update(
2766 where.update(
2765 runpy.run_module(str(mod_name), run_name="__main__",
2767 runpy.run_module(str(mod_name), run_name="__main__",
2766 alter_sys=True)
2768 alter_sys=True)
2767 )
2769 )
2768 except SystemExit as status:
2770 except SystemExit as status:
2769 if status.code:
2771 if status.code:
2770 raise
2772 raise
2771 except:
2773 except:
2772 self.showtraceback()
2774 self.showtraceback()
2773 warn('Unknown failure executing module: <%s>' % mod_name)
2775 warn('Unknown failure executing module: <%s>' % mod_name)
2774
2776
2775 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2777 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2776 """Run a complete IPython cell.
2778 """Run a complete IPython cell.
2777
2779
2778 Parameters
2780 Parameters
2779 ----------
2781 ----------
2780 raw_cell : str
2782 raw_cell : str
2781 The code (including IPython code such as %magic functions) to run.
2783 The code (including IPython code such as %magic functions) to run.
2782 store_history : bool
2784 store_history : bool
2783 If True, the raw and translated cell will be stored in IPython's
2785 If True, the raw and translated cell will be stored in IPython's
2784 history. For user code calling back into IPython's machinery, this
2786 history. For user code calling back into IPython's machinery, this
2785 should be set to False.
2787 should be set to False.
2786 silent : bool
2788 silent : bool
2787 If True, avoid side-effects, such as implicit displayhooks and
2789 If True, avoid side-effects, such as implicit displayhooks and
2788 and logging. silent=True forces store_history=False.
2790 and logging. silent=True forces store_history=False.
2789 shell_futures : bool
2791 shell_futures : bool
2790 If True, the code will share future statements with the interactive
2792 If True, the code will share future statements with the interactive
2791 shell. It will both be affected by previous __future__ imports, and
2793 shell. It will both be affected by previous __future__ imports, and
2792 any __future__ imports in the code will affect the shell. If False,
2794 any __future__ imports in the code will affect the shell. If False,
2793 __future__ imports are not shared in either direction.
2795 __future__ imports are not shared in either direction.
2794
2796
2795 Returns
2797 Returns
2796 -------
2798 -------
2797 result : :class:`ExecutionResult`
2799 result : :class:`ExecutionResult`
2798 """
2800 """
2799 result = ExecutionResult()
2801 result = ExecutionResult()
2800
2802
2801 if (not raw_cell) or raw_cell.isspace():
2803 if (not raw_cell) or raw_cell.isspace():
2802 return result
2804 return result
2803
2805
2804 if silent:
2806 if silent:
2805 store_history = False
2807 store_history = False
2806
2808
2807 if store_history:
2809 if store_history:
2808 result.execution_count = self.execution_count
2810 result.execution_count = self.execution_count
2809
2811
2810 def error_before_exec(value):
2812 def error_before_exec(value):
2811 result.error_before_exec = value
2813 result.error_before_exec = value
2812 return result
2814 return result
2813
2815
2814 self.events.trigger('pre_execute')
2816 self.events.trigger('pre_execute')
2815 if not silent:
2817 if not silent:
2816 self.events.trigger('pre_run_cell')
2818 self.events.trigger('pre_run_cell')
2817
2819
2818 # If any of our input transformation (input_transformer_manager or
2820 # If any of our input transformation (input_transformer_manager or
2819 # prefilter_manager) raises an exception, we store it in this variable
2821 # prefilter_manager) raises an exception, we store it in this variable
2820 # so that we can display the error after logging the input and storing
2822 # so that we can display the error after logging the input and storing
2821 # it in the history.
2823 # it in the history.
2822 preprocessing_exc_tuple = None
2824 preprocessing_exc_tuple = None
2823 try:
2825 try:
2824 # Static input transformations
2826 # Static input transformations
2825 cell = self.input_transformer_manager.transform_cell(raw_cell)
2827 cell = self.input_transformer_manager.transform_cell(raw_cell)
2826 except SyntaxError:
2828 except SyntaxError:
2827 preprocessing_exc_tuple = sys.exc_info()
2829 preprocessing_exc_tuple = sys.exc_info()
2828 cell = raw_cell # cell has to exist so it can be stored/logged
2830 cell = raw_cell # cell has to exist so it can be stored/logged
2829 else:
2831 else:
2830 if len(cell.splitlines()) == 1:
2832 if len(cell.splitlines()) == 1:
2831 # Dynamic transformations - only applied for single line commands
2833 # Dynamic transformations - only applied for single line commands
2832 with self.builtin_trap:
2834 with self.builtin_trap:
2833 try:
2835 try:
2834 # use prefilter_lines to handle trailing newlines
2836 # use prefilter_lines to handle trailing newlines
2835 # restore trailing newline for ast.parse
2837 # restore trailing newline for ast.parse
2836 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2838 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2837 except Exception:
2839 except Exception:
2838 # don't allow prefilter errors to crash IPython
2840 # don't allow prefilter errors to crash IPython
2839 preprocessing_exc_tuple = sys.exc_info()
2841 preprocessing_exc_tuple = sys.exc_info()
2840
2842
2841 # Store raw and processed history
2843 # Store raw and processed history
2842 if store_history:
2844 if store_history:
2843 self.history_manager.store_inputs(self.execution_count,
2845 self.history_manager.store_inputs(self.execution_count,
2844 cell, raw_cell)
2846 cell, raw_cell)
2845 if not silent:
2847 if not silent:
2846 self.logger.log(cell, raw_cell)
2848 self.logger.log(cell, raw_cell)
2847
2849
2848 # Display the exception if input processing failed.
2850 # Display the exception if input processing failed.
2849 if preprocessing_exc_tuple is not None:
2851 if preprocessing_exc_tuple is not None:
2850 self.showtraceback(preprocessing_exc_tuple)
2852 self.showtraceback(preprocessing_exc_tuple)
2851 if store_history:
2853 if store_history:
2852 self.execution_count += 1
2854 self.execution_count += 1
2853 return error_before_exec(preprocessing_exc_tuple[2])
2855 return error_before_exec(preprocessing_exc_tuple[2])
2854
2856
2855 # Our own compiler remembers the __future__ environment. If we want to
2857 # Our own compiler remembers the __future__ environment. If we want to
2856 # run code with a separate __future__ environment, use the default
2858 # run code with a separate __future__ environment, use the default
2857 # compiler
2859 # compiler
2858 compiler = self.compile if shell_futures else CachingCompiler()
2860 compiler = self.compile if shell_futures else CachingCompiler()
2859
2861
2860 with self.builtin_trap:
2862 with self.builtin_trap:
2861 cell_name = self.compile.cache(cell, self.execution_count)
2863 cell_name = self.compile.cache(cell, self.execution_count)
2862
2864
2863 with self.display_trap:
2865 with self.display_trap:
2864 # Compile to bytecode
2866 # Compile to bytecode
2865 try:
2867 try:
2866 code_ast = compiler.ast_parse(cell, filename=cell_name)
2868 code_ast = compiler.ast_parse(cell, filename=cell_name)
2867 except IndentationError as e:
2869 except IndentationError as e:
2868 self.showindentationerror()
2870 self.showindentationerror()
2869 if store_history:
2871 if store_history:
2870 self.execution_count += 1
2872 self.execution_count += 1
2871 return error_before_exec(e)
2873 return error_before_exec(e)
2872 except (OverflowError, SyntaxError, ValueError, TypeError,
2874 except (OverflowError, SyntaxError, ValueError, TypeError,
2873 MemoryError) as e:
2875 MemoryError) as e:
2874 self.showsyntaxerror()
2876 self.showsyntaxerror()
2875 if store_history:
2877 if store_history:
2876 self.execution_count += 1
2878 self.execution_count += 1
2877 return error_before_exec(e)
2879 return error_before_exec(e)
2878
2880
2879 # Apply AST transformations
2881 # Apply AST transformations
2880 try:
2882 try:
2881 code_ast = self.transform_ast(code_ast)
2883 code_ast = self.transform_ast(code_ast)
2882 except InputRejected as e:
2884 except InputRejected as e:
2883 self.showtraceback()
2885 self.showtraceback()
2884 if store_history:
2886 if store_history:
2885 self.execution_count += 1
2887 self.execution_count += 1
2886 return error_before_exec(e)
2888 return error_before_exec(e)
2887
2889
2888 # Give the displayhook a reference to our ExecutionResult so it
2890 # Give the displayhook a reference to our ExecutionResult so it
2889 # can fill in the output value.
2891 # can fill in the output value.
2890 self.displayhook.exec_result = result
2892 self.displayhook.exec_result = result
2891
2893
2892 # Execute the user code
2894 # Execute the user code
2893 interactivity = "none" if silent else self.ast_node_interactivity
2895 interactivity = "none" if silent else self.ast_node_interactivity
2894 self.run_ast_nodes(code_ast.body, cell_name,
2896 self.run_ast_nodes(code_ast.body, cell_name,
2895 interactivity=interactivity, compiler=compiler, result=result)
2897 interactivity=interactivity, compiler=compiler, result=result)
2896
2898
2897 # Reset this so later displayed values do not modify the
2899 # Reset this so later displayed values do not modify the
2898 # ExecutionResult
2900 # ExecutionResult
2899 self.displayhook.exec_result = None
2901 self.displayhook.exec_result = None
2900
2902
2901 self.events.trigger('post_execute')
2903 self.events.trigger('post_execute')
2902 if not silent:
2904 if not silent:
2903 self.events.trigger('post_run_cell')
2905 self.events.trigger('post_run_cell')
2904
2906
2905 if store_history:
2907 if store_history:
2906 # Write output to the database. Does nothing unless
2908 # Write output to the database. Does nothing unless
2907 # history output logging is enabled.
2909 # history output logging is enabled.
2908 self.history_manager.store_output(self.execution_count)
2910 self.history_manager.store_output(self.execution_count)
2909 # Each cell is a *single* input, regardless of how many lines it has
2911 # Each cell is a *single* input, regardless of how many lines it has
2910 self.execution_count += 1
2912 self.execution_count += 1
2911
2913
2912 return result
2914 return result
2913
2915
2914 def transform_ast(self, node):
2916 def transform_ast(self, node):
2915 """Apply the AST transformations from self.ast_transformers
2917 """Apply the AST transformations from self.ast_transformers
2916
2918
2917 Parameters
2919 Parameters
2918 ----------
2920 ----------
2919 node : ast.Node
2921 node : ast.Node
2920 The root node to be transformed. Typically called with the ast.Module
2922 The root node to be transformed. Typically called with the ast.Module
2921 produced by parsing user input.
2923 produced by parsing user input.
2922
2924
2923 Returns
2925 Returns
2924 -------
2926 -------
2925 An ast.Node corresponding to the node it was called with. Note that it
2927 An ast.Node corresponding to the node it was called with. Note that it
2926 may also modify the passed object, so don't rely on references to the
2928 may also modify the passed object, so don't rely on references to the
2927 original AST.
2929 original AST.
2928 """
2930 """
2929 for transformer in self.ast_transformers:
2931 for transformer in self.ast_transformers:
2930 try:
2932 try:
2931 node = transformer.visit(node)
2933 node = transformer.visit(node)
2932 except InputRejected:
2934 except InputRejected:
2933 # User-supplied AST transformers can reject an input by raising
2935 # User-supplied AST transformers can reject an input by raising
2934 # an InputRejected. Short-circuit in this case so that we
2936 # an InputRejected. Short-circuit in this case so that we
2935 # don't unregister the transform.
2937 # don't unregister the transform.
2936 raise
2938 raise
2937 except Exception:
2939 except Exception:
2938 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2940 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2939 self.ast_transformers.remove(transformer)
2941 self.ast_transformers.remove(transformer)
2940
2942
2941 if self.ast_transformers:
2943 if self.ast_transformers:
2942 ast.fix_missing_locations(node)
2944 ast.fix_missing_locations(node)
2943 return node
2945 return node
2944
2946
2945
2947
2946 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2948 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2947 compiler=compile, result=None):
2949 compiler=compile, result=None):
2948 """Run a sequence of AST nodes. The execution mode depends on the
2950 """Run a sequence of AST nodes. The execution mode depends on the
2949 interactivity parameter.
2951 interactivity parameter.
2950
2952
2951 Parameters
2953 Parameters
2952 ----------
2954 ----------
2953 nodelist : list
2955 nodelist : list
2954 A sequence of AST nodes to run.
2956 A sequence of AST nodes to run.
2955 cell_name : str
2957 cell_name : str
2956 Will be passed to the compiler as the filename of the cell. Typically
2958 Will be passed to the compiler as the filename of the cell. Typically
2957 the value returned by ip.compile.cache(cell).
2959 the value returned by ip.compile.cache(cell).
2958 interactivity : str
2960 interactivity : str
2959 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2961 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2960 run interactively (displaying output from expressions). 'last_expr'
2962 run interactively (displaying output from expressions). 'last_expr'
2961 will run the last node interactively only if it is an expression (i.e.
2963 will run the last node interactively only if it is an expression (i.e.
2962 expressions in loops or other blocks are not displayed. Other values
2964 expressions in loops or other blocks are not displayed. Other values
2963 for this parameter will raise a ValueError.
2965 for this parameter will raise a ValueError.
2964 compiler : callable
2966 compiler : callable
2965 A function with the same interface as the built-in compile(), to turn
2967 A function with the same interface as the built-in compile(), to turn
2966 the AST nodes into code objects. Default is the built-in compile().
2968 the AST nodes into code objects. Default is the built-in compile().
2967 result : ExecutionResult, optional
2969 result : ExecutionResult, optional
2968 An object to store exceptions that occur during execution.
2970 An object to store exceptions that occur during execution.
2969
2971
2970 Returns
2972 Returns
2971 -------
2973 -------
2972 True if an exception occurred while running code, False if it finished
2974 True if an exception occurred while running code, False if it finished
2973 running.
2975 running.
2974 """
2976 """
2975 if not nodelist:
2977 if not nodelist:
2976 return
2978 return
2977
2979
2978 if interactivity == 'last_expr':
2980 if interactivity == 'last_expr':
2979 if isinstance(nodelist[-1], ast.Expr):
2981 if isinstance(nodelist[-1], ast.Expr):
2980 interactivity = "last"
2982 interactivity = "last"
2981 else:
2983 else:
2982 interactivity = "none"
2984 interactivity = "none"
2983
2985
2984 if interactivity == 'none':
2986 if interactivity == 'none':
2985 to_run_exec, to_run_interactive = nodelist, []
2987 to_run_exec, to_run_interactive = nodelist, []
2986 elif interactivity == 'last':
2988 elif interactivity == 'last':
2987 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2989 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2988 elif interactivity == 'all':
2990 elif interactivity == 'all':
2989 to_run_exec, to_run_interactive = [], nodelist
2991 to_run_exec, to_run_interactive = [], nodelist
2990 else:
2992 else:
2991 raise ValueError("Interactivity was %r" % interactivity)
2993 raise ValueError("Interactivity was %r" % interactivity)
2992
2994
2993 try:
2995 try:
2994 for i, node in enumerate(to_run_exec):
2996 for i, node in enumerate(to_run_exec):
2995 mod = ast.Module([node])
2997 mod = ast.Module([node])
2996 code = compiler(mod, cell_name, "exec")
2998 code = compiler(mod, cell_name, "exec")
2997 if self.run_code(code, result):
2999 if self.run_code(code, result):
2998 return True
3000 return True
2999
3001
3000 for i, node in enumerate(to_run_interactive):
3002 for i, node in enumerate(to_run_interactive):
3001 mod = ast.Interactive([node])
3003 mod = ast.Interactive([node])
3002 code = compiler(mod, cell_name, "single")
3004 code = compiler(mod, cell_name, "single")
3003 if self.run_code(code, result):
3005 if self.run_code(code, result):
3004 return True
3006 return True
3005
3007
3006 # Flush softspace
3008 # Flush softspace
3007 if softspace(sys.stdout, 0):
3009 if softspace(sys.stdout, 0):
3008 print()
3010 print()
3009
3011
3010 except:
3012 except:
3011 # It's possible to have exceptions raised here, typically by
3013 # It's possible to have exceptions raised here, typically by
3012 # compilation of odd code (such as a naked 'return' outside a
3014 # compilation of odd code (such as a naked 'return' outside a
3013 # function) that did parse but isn't valid. Typically the exception
3015 # function) that did parse but isn't valid. Typically the exception
3014 # is a SyntaxError, but it's safest just to catch anything and show
3016 # is a SyntaxError, but it's safest just to catch anything and show
3015 # the user a traceback.
3017 # the user a traceback.
3016
3018
3017 # We do only one try/except outside the loop to minimize the impact
3019 # We do only one try/except outside the loop to minimize the impact
3018 # on runtime, and also because if any node in the node list is
3020 # on runtime, and also because if any node in the node list is
3019 # broken, we should stop execution completely.
3021 # broken, we should stop execution completely.
3020 if result:
3022 if result:
3021 result.error_before_exec = sys.exc_info()[1]
3023 result.error_before_exec = sys.exc_info()[1]
3022 self.showtraceback()
3024 self.showtraceback()
3023 return True
3025 return True
3024
3026
3025 return False
3027 return False
3026
3028
3027 def run_code(self, code_obj, result=None):
3029 def run_code(self, code_obj, result=None):
3028 """Execute a code object.
3030 """Execute a code object.
3029
3031
3030 When an exception occurs, self.showtraceback() is called to display a
3032 When an exception occurs, self.showtraceback() is called to display a
3031 traceback.
3033 traceback.
3032
3034
3033 Parameters
3035 Parameters
3034 ----------
3036 ----------
3035 code_obj : code object
3037 code_obj : code object
3036 A compiled code object, to be executed
3038 A compiled code object, to be executed
3037 result : ExecutionResult, optional
3039 result : ExecutionResult, optional
3038 An object to store exceptions that occur during execution.
3040 An object to store exceptions that occur during execution.
3039
3041
3040 Returns
3042 Returns
3041 -------
3043 -------
3042 False : successful execution.
3044 False : successful execution.
3043 True : an error occurred.
3045 True : an error occurred.
3044 """
3046 """
3045 # Set our own excepthook in case the user code tries to call it
3047 # Set our own excepthook in case the user code tries to call it
3046 # directly, so that the IPython crash handler doesn't get triggered
3048 # directly, so that the IPython crash handler doesn't get triggered
3047 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3049 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3048
3050
3049 # we save the original sys.excepthook in the instance, in case config
3051 # we save the original sys.excepthook in the instance, in case config
3050 # code (such as magics) needs access to it.
3052 # code (such as magics) needs access to it.
3051 self.sys_excepthook = old_excepthook
3053 self.sys_excepthook = old_excepthook
3052 outflag = 1 # happens in more places, so it's easier as default
3054 outflag = 1 # happens in more places, so it's easier as default
3053 try:
3055 try:
3054 try:
3056 try:
3055 self.hooks.pre_run_code_hook()
3057 self.hooks.pre_run_code_hook()
3056 #rprint('Running code', repr(code_obj)) # dbg
3058 #rprint('Running code', repr(code_obj)) # dbg
3057 exec(code_obj, self.user_global_ns, self.user_ns)
3059 exec(code_obj, self.user_global_ns, self.user_ns)
3058 finally:
3060 finally:
3059 # Reset our crash handler in place
3061 # Reset our crash handler in place
3060 sys.excepthook = old_excepthook
3062 sys.excepthook = old_excepthook
3061 except SystemExit as e:
3063 except SystemExit as e:
3062 if result is not None:
3064 if result is not None:
3063 result.error_in_exec = e
3065 result.error_in_exec = e
3064 self.showtraceback(exception_only=True)
3066 self.showtraceback(exception_only=True)
3065 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
3067 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
3066 except self.custom_exceptions:
3068 except self.custom_exceptions:
3067 etype, value, tb = sys.exc_info()
3069 etype, value, tb = sys.exc_info()
3068 if result is not None:
3070 if result is not None:
3069 result.error_in_exec = value
3071 result.error_in_exec = value
3070 self.CustomTB(etype, value, tb)
3072 self.CustomTB(etype, value, tb)
3071 except:
3073 except:
3072 if result is not None:
3074 if result is not None:
3073 result.error_in_exec = sys.exc_info()[1]
3075 result.error_in_exec = sys.exc_info()[1]
3074 self.showtraceback()
3076 self.showtraceback()
3075 else:
3077 else:
3076 outflag = 0
3078 outflag = 0
3077 return outflag
3079 return outflag
3078
3080
3079 # For backwards compatibility
3081 # For backwards compatibility
3080 runcode = run_code
3082 runcode = run_code
3081
3083
3082 #-------------------------------------------------------------------------
3084 #-------------------------------------------------------------------------
3083 # Things related to GUI support and pylab
3085 # Things related to GUI support and pylab
3084 #-------------------------------------------------------------------------
3086 #-------------------------------------------------------------------------
3085
3087
3086 def enable_gui(self, gui=None):
3088 def enable_gui(self, gui=None):
3087 raise NotImplementedError('Implement enable_gui in a subclass')
3089 raise NotImplementedError('Implement enable_gui in a subclass')
3088
3090
3089 def enable_matplotlib(self, gui=None):
3091 def enable_matplotlib(self, gui=None):
3090 """Enable interactive matplotlib and inline figure support.
3092 """Enable interactive matplotlib and inline figure support.
3091
3093
3092 This takes the following steps:
3094 This takes the following steps:
3093
3095
3094 1. select the appropriate eventloop and matplotlib backend
3096 1. select the appropriate eventloop and matplotlib backend
3095 2. set up matplotlib for interactive use with that backend
3097 2. set up matplotlib for interactive use with that backend
3096 3. configure formatters for inline figure display
3098 3. configure formatters for inline figure display
3097 4. enable the selected gui eventloop
3099 4. enable the selected gui eventloop
3098
3100
3099 Parameters
3101 Parameters
3100 ----------
3102 ----------
3101 gui : optional, string
3103 gui : optional, string
3102 If given, dictates the choice of matplotlib GUI backend to use
3104 If given, dictates the choice of matplotlib GUI backend to use
3103 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3105 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3104 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3106 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3105 matplotlib (as dictated by the matplotlib build-time options plus the
3107 matplotlib (as dictated by the matplotlib build-time options plus the
3106 user's matplotlibrc configuration file). Note that not all backends
3108 user's matplotlibrc configuration file). Note that not all backends
3107 make sense in all contexts, for example a terminal ipython can't
3109 make sense in all contexts, for example a terminal ipython can't
3108 display figures inline.
3110 display figures inline.
3109 """
3111 """
3110 from IPython.core import pylabtools as pt
3112 from IPython.core import pylabtools as pt
3111 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3113 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3112
3114
3113 if gui != 'inline':
3115 if gui != 'inline':
3114 # If we have our first gui selection, store it
3116 # If we have our first gui selection, store it
3115 if self.pylab_gui_select is None:
3117 if self.pylab_gui_select is None:
3116 self.pylab_gui_select = gui
3118 self.pylab_gui_select = gui
3117 # Otherwise if they are different
3119 # Otherwise if they are different
3118 elif gui != self.pylab_gui_select:
3120 elif gui != self.pylab_gui_select:
3119 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3121 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3120 ' Using %s instead.' % (gui, self.pylab_gui_select))
3122 ' Using %s instead.' % (gui, self.pylab_gui_select))
3121 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3123 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3122
3124
3123 pt.activate_matplotlib(backend)
3125 pt.activate_matplotlib(backend)
3124 pt.configure_inline_support(self, backend)
3126 pt.configure_inline_support(self, backend)
3125
3127
3126 # Now we must activate the gui pylab wants to use, and fix %run to take
3128 # Now we must activate the gui pylab wants to use, and fix %run to take
3127 # plot updates into account
3129 # plot updates into account
3128 self.enable_gui(gui)
3130 self.enable_gui(gui)
3129 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3131 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3130 pt.mpl_runner(self.safe_execfile)
3132 pt.mpl_runner(self.safe_execfile)
3131
3133
3132 return gui, backend
3134 return gui, backend
3133
3135
3134 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3136 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3135 """Activate pylab support at runtime.
3137 """Activate pylab support at runtime.
3136
3138
3137 This turns on support for matplotlib, preloads into the interactive
3139 This turns on support for matplotlib, preloads into the interactive
3138 namespace all of numpy and pylab, and configures IPython to correctly
3140 namespace all of numpy and pylab, and configures IPython to correctly
3139 interact with the GUI event loop. The GUI backend to be used can be
3141 interact with the GUI event loop. The GUI backend to be used can be
3140 optionally selected with the optional ``gui`` argument.
3142 optionally selected with the optional ``gui`` argument.
3141
3143
3142 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3144 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3143
3145
3144 Parameters
3146 Parameters
3145 ----------
3147 ----------
3146 gui : optional, string
3148 gui : optional, string
3147 If given, dictates the choice of matplotlib GUI backend to use
3149 If given, dictates the choice of matplotlib GUI backend to use
3148 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3150 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3149 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3151 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3150 matplotlib (as dictated by the matplotlib build-time options plus the
3152 matplotlib (as dictated by the matplotlib build-time options plus the
3151 user's matplotlibrc configuration file). Note that not all backends
3153 user's matplotlibrc configuration file). Note that not all backends
3152 make sense in all contexts, for example a terminal ipython can't
3154 make sense in all contexts, for example a terminal ipython can't
3153 display figures inline.
3155 display figures inline.
3154 import_all : optional, bool, default: True
3156 import_all : optional, bool, default: True
3155 Whether to do `from numpy import *` and `from pylab import *`
3157 Whether to do `from numpy import *` and `from pylab import *`
3156 in addition to module imports.
3158 in addition to module imports.
3157 welcome_message : deprecated
3159 welcome_message : deprecated
3158 This argument is ignored, no welcome message will be displayed.
3160 This argument is ignored, no welcome message will be displayed.
3159 """
3161 """
3160 from IPython.core.pylabtools import import_pylab
3162 from IPython.core.pylabtools import import_pylab
3161
3163
3162 gui, backend = self.enable_matplotlib(gui)
3164 gui, backend = self.enable_matplotlib(gui)
3163
3165
3164 # We want to prevent the loading of pylab to pollute the user's
3166 # We want to prevent the loading of pylab to pollute the user's
3165 # namespace as shown by the %who* magics, so we execute the activation
3167 # namespace as shown by the %who* magics, so we execute the activation
3166 # code in an empty namespace, and we update *both* user_ns and
3168 # code in an empty namespace, and we update *both* user_ns and
3167 # user_ns_hidden with this information.
3169 # user_ns_hidden with this information.
3168 ns = {}
3170 ns = {}
3169 import_pylab(ns, import_all)
3171 import_pylab(ns, import_all)
3170 # warn about clobbered names
3172 # warn about clobbered names
3171 ignored = {"__builtins__"}
3173 ignored = {"__builtins__"}
3172 both = set(ns).intersection(self.user_ns).difference(ignored)
3174 both = set(ns).intersection(self.user_ns).difference(ignored)
3173 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3175 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3174 self.user_ns.update(ns)
3176 self.user_ns.update(ns)
3175 self.user_ns_hidden.update(ns)
3177 self.user_ns_hidden.update(ns)
3176 return gui, backend, clobbered
3178 return gui, backend, clobbered
3177
3179
3178 #-------------------------------------------------------------------------
3180 #-------------------------------------------------------------------------
3179 # Utilities
3181 # Utilities
3180 #-------------------------------------------------------------------------
3182 #-------------------------------------------------------------------------
3181
3183
3182 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3184 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3183 """Expand python variables in a string.
3185 """Expand python variables in a string.
3184
3186
3185 The depth argument indicates how many frames above the caller should
3187 The depth argument indicates how many frames above the caller should
3186 be walked to look for the local namespace where to expand variables.
3188 be walked to look for the local namespace where to expand variables.
3187
3189
3188 The global namespace for expansion is always the user's interactive
3190 The global namespace for expansion is always the user's interactive
3189 namespace.
3191 namespace.
3190 """
3192 """
3191 ns = self.user_ns.copy()
3193 ns = self.user_ns.copy()
3192 try:
3194 try:
3193 frame = sys._getframe(depth+1)
3195 frame = sys._getframe(depth+1)
3194 except ValueError:
3196 except ValueError:
3195 # This is thrown if there aren't that many frames on the stack,
3197 # This is thrown if there aren't that many frames on the stack,
3196 # e.g. if a script called run_line_magic() directly.
3198 # e.g. if a script called run_line_magic() directly.
3197 pass
3199 pass
3198 else:
3200 else:
3199 ns.update(frame.f_locals)
3201 ns.update(frame.f_locals)
3200
3202
3201 try:
3203 try:
3202 # We have to use .vformat() here, because 'self' is a valid and common
3204 # We have to use .vformat() here, because 'self' is a valid and common
3203 # name, and expanding **ns for .format() would make it collide with
3205 # name, and expanding **ns for .format() would make it collide with
3204 # the 'self' argument of the method.
3206 # the 'self' argument of the method.
3205 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3207 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3206 except Exception:
3208 except Exception:
3207 # if formatter couldn't format, just let it go untransformed
3209 # if formatter couldn't format, just let it go untransformed
3208 pass
3210 pass
3209 return cmd
3211 return cmd
3210
3212
3211 def mktempfile(self, data=None, prefix='ipython_edit_'):
3213 def mktempfile(self, data=None, prefix='ipython_edit_'):
3212 """Make a new tempfile and return its filename.
3214 """Make a new tempfile and return its filename.
3213
3215
3214 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3216 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3215 but it registers the created filename internally so ipython cleans it up
3217 but it registers the created filename internally so ipython cleans it up
3216 at exit time.
3218 at exit time.
3217
3219
3218 Optional inputs:
3220 Optional inputs:
3219
3221
3220 - data(None): if data is given, it gets written out to the temp file
3222 - data(None): if data is given, it gets written out to the temp file
3221 immediately, and the file is closed again."""
3223 immediately, and the file is closed again."""
3222
3224
3223 dirname = tempfile.mkdtemp(prefix=prefix)
3225 dirname = tempfile.mkdtemp(prefix=prefix)
3224 self.tempdirs.append(dirname)
3226 self.tempdirs.append(dirname)
3225
3227
3226 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3228 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3227 os.close(handle) # On Windows, there can only be one open handle on a file
3229 os.close(handle) # On Windows, there can only be one open handle on a file
3228 self.tempfiles.append(filename)
3230 self.tempfiles.append(filename)
3229
3231
3230 if data:
3232 if data:
3231 tmp_file = open(filename,'w')
3233 tmp_file = open(filename,'w')
3232 tmp_file.write(data)
3234 tmp_file.write(data)
3233 tmp_file.close()
3235 tmp_file.close()
3234 return filename
3236 return filename
3235
3237
3236 # TODO: This should be removed when Term is refactored.
3238 # TODO: This should be removed when Term is refactored.
3237 def write(self,data):
3239 def write(self,data):
3238 """Write a string to the default output"""
3240 """Write a string to the default output"""
3239 io.stdout.write(data)
3241 io.stdout.write(data)
3240
3242
3241 # TODO: This should be removed when Term is refactored.
3243 # TODO: This should be removed when Term is refactored.
3242 def write_err(self,data):
3244 def write_err(self,data):
3243 """Write a string to the default error output"""
3245 """Write a string to the default error output"""
3244 io.stderr.write(data)
3246 io.stderr.write(data)
3245
3247
3246 def ask_yes_no(self, prompt, default=None, interrupt=None):
3248 def ask_yes_no(self, prompt, default=None, interrupt=None):
3247 if self.quiet:
3249 if self.quiet:
3248 return True
3250 return True
3249 return ask_yes_no(prompt,default,interrupt)
3251 return ask_yes_no(prompt,default,interrupt)
3250
3252
3251 def show_usage(self):
3253 def show_usage(self):
3252 """Show a usage message"""
3254 """Show a usage message"""
3253 page.page(IPython.core.usage.interactive_usage)
3255 page.page(IPython.core.usage.interactive_usage)
3254
3256
3255 def extract_input_lines(self, range_str, raw=False):
3257 def extract_input_lines(self, range_str, raw=False):
3256 """Return as a string a set of input history slices.
3258 """Return as a string a set of input history slices.
3257
3259
3258 Parameters
3260 Parameters
3259 ----------
3261 ----------
3260 range_str : string
3262 range_str : string
3261 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3263 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3262 since this function is for use by magic functions which get their
3264 since this function is for use by magic functions which get their
3263 arguments as strings. The number before the / is the session
3265 arguments as strings. The number before the / is the session
3264 number: ~n goes n back from the current session.
3266 number: ~n goes n back from the current session.
3265
3267
3266 raw : bool, optional
3268 raw : bool, optional
3267 By default, the processed input is used. If this is true, the raw
3269 By default, the processed input is used. If this is true, the raw
3268 input history is used instead.
3270 input history is used instead.
3269
3271
3270 Notes
3272 Notes
3271 -----
3273 -----
3272
3274
3273 Slices can be described with two notations:
3275 Slices can be described with two notations:
3274
3276
3275 * ``N:M`` -> standard python form, means including items N...(M-1).
3277 * ``N:M`` -> standard python form, means including items N...(M-1).
3276 * ``N-M`` -> include items N..M (closed endpoint).
3278 * ``N-M`` -> include items N..M (closed endpoint).
3277 """
3279 """
3278 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3280 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3279 return "\n".join(x for _, _, x in lines)
3281 return "\n".join(x for _, _, x in lines)
3280
3282
3281 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3283 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3282 """Get a code string from history, file, url, or a string or macro.
3284 """Get a code string from history, file, url, or a string or macro.
3283
3285
3284 This is mainly used by magic functions.
3286 This is mainly used by magic functions.
3285
3287
3286 Parameters
3288 Parameters
3287 ----------
3289 ----------
3288
3290
3289 target : str
3291 target : str
3290
3292
3291 A string specifying code to retrieve. This will be tried respectively
3293 A string specifying code to retrieve. This will be tried respectively
3292 as: ranges of input history (see %history for syntax), url,
3294 as: ranges of input history (see %history for syntax), url,
3293 corresponding .py file, filename, or an expression evaluating to a
3295 corresponding .py file, filename, or an expression evaluating to a
3294 string or Macro in the user namespace.
3296 string or Macro in the user namespace.
3295
3297
3296 raw : bool
3298 raw : bool
3297 If true (default), retrieve raw history. Has no effect on the other
3299 If true (default), retrieve raw history. Has no effect on the other
3298 retrieval mechanisms.
3300 retrieval mechanisms.
3299
3301
3300 py_only : bool (default False)
3302 py_only : bool (default False)
3301 Only try to fetch python code, do not try alternative methods to decode file
3303 Only try to fetch python code, do not try alternative methods to decode file
3302 if unicode fails.
3304 if unicode fails.
3303
3305
3304 Returns
3306 Returns
3305 -------
3307 -------
3306 A string of code.
3308 A string of code.
3307
3309
3308 ValueError is raised if nothing is found, and TypeError if it evaluates
3310 ValueError is raised if nothing is found, and TypeError if it evaluates
3309 to an object of another type. In each case, .args[0] is a printable
3311 to an object of another type. In each case, .args[0] is a printable
3310 message.
3312 message.
3311 """
3313 """
3312 code = self.extract_input_lines(target, raw=raw) # Grab history
3314 code = self.extract_input_lines(target, raw=raw) # Grab history
3313 if code:
3315 if code:
3314 return code
3316 return code
3315 utarget = unquote_filename(target)
3317 utarget = unquote_filename(target)
3316 try:
3318 try:
3317 if utarget.startswith(('http://', 'https://')):
3319 if utarget.startswith(('http://', 'https://')):
3318 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3320 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3319 except UnicodeDecodeError:
3321 except UnicodeDecodeError:
3320 if not py_only :
3322 if not py_only :
3321 # Deferred import
3323 # Deferred import
3322 try:
3324 try:
3323 from urllib.request import urlopen # Py3
3325 from urllib.request import urlopen # Py3
3324 except ImportError:
3326 except ImportError:
3325 from urllib import urlopen
3327 from urllib import urlopen
3326 response = urlopen(target)
3328 response = urlopen(target)
3327 return response.read().decode('latin1')
3329 return response.read().decode('latin1')
3328 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3330 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3329
3331
3330 potential_target = [target]
3332 potential_target = [target]
3331 try :
3333 try :
3332 potential_target.insert(0,get_py_filename(target))
3334 potential_target.insert(0,get_py_filename(target))
3333 except IOError:
3335 except IOError:
3334 pass
3336 pass
3335
3337
3336 for tgt in potential_target :
3338 for tgt in potential_target :
3337 if os.path.isfile(tgt): # Read file
3339 if os.path.isfile(tgt): # Read file
3338 try :
3340 try :
3339 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3341 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3340 except UnicodeDecodeError :
3342 except UnicodeDecodeError :
3341 if not py_only :
3343 if not py_only :
3342 with io_open(tgt,'r', encoding='latin1') as f :
3344 with io_open(tgt,'r', encoding='latin1') as f :
3343 return f.read()
3345 return f.read()
3344 raise ValueError(("'%s' seem to be unreadable.") % target)
3346 raise ValueError(("'%s' seem to be unreadable.") % target)
3345 elif os.path.isdir(os.path.expanduser(tgt)):
3347 elif os.path.isdir(os.path.expanduser(tgt)):
3346 raise ValueError("'%s' is a directory, not a regular file." % target)
3348 raise ValueError("'%s' is a directory, not a regular file." % target)
3347
3349
3348 if search_ns:
3350 if search_ns:
3349 # Inspect namespace to load object source
3351 # Inspect namespace to load object source
3350 object_info = self.object_inspect(target, detail_level=1)
3352 object_info = self.object_inspect(target, detail_level=1)
3351 if object_info['found'] and object_info['source']:
3353 if object_info['found'] and object_info['source']:
3352 return object_info['source']
3354 return object_info['source']
3353
3355
3354 try: # User namespace
3356 try: # User namespace
3355 codeobj = eval(target, self.user_ns)
3357 codeobj = eval(target, self.user_ns)
3356 except Exception:
3358 except Exception:
3357 raise ValueError(("'%s' was not found in history, as a file, url, "
3359 raise ValueError(("'%s' was not found in history, as a file, url, "
3358 "nor in the user namespace.") % target)
3360 "nor in the user namespace.") % target)
3359
3361
3360 if isinstance(codeobj, string_types):
3362 if isinstance(codeobj, string_types):
3361 return codeobj
3363 return codeobj
3362 elif isinstance(codeobj, Macro):
3364 elif isinstance(codeobj, Macro):
3363 return codeobj.value
3365 return codeobj.value
3364
3366
3365 raise TypeError("%s is neither a string nor a macro." % target,
3367 raise TypeError("%s is neither a string nor a macro." % target,
3366 codeobj)
3368 codeobj)
3367
3369
3368 #-------------------------------------------------------------------------
3370 #-------------------------------------------------------------------------
3369 # Things related to IPython exiting
3371 # Things related to IPython exiting
3370 #-------------------------------------------------------------------------
3372 #-------------------------------------------------------------------------
3371 def atexit_operations(self):
3373 def atexit_operations(self):
3372 """This will be executed at the time of exit.
3374 """This will be executed at the time of exit.
3373
3375
3374 Cleanup operations and saving of persistent data that is done
3376 Cleanup operations and saving of persistent data that is done
3375 unconditionally by IPython should be performed here.
3377 unconditionally by IPython should be performed here.
3376
3378
3377 For things that may depend on startup flags or platform specifics (such
3379 For things that may depend on startup flags or platform specifics (such
3378 as having readline or not), register a separate atexit function in the
3380 as having readline or not), register a separate atexit function in the
3379 code that has the appropriate information, rather than trying to
3381 code that has the appropriate information, rather than trying to
3380 clutter
3382 clutter
3381 """
3383 """
3382 # Close the history session (this stores the end time and line count)
3384 # Close the history session (this stores the end time and line count)
3383 # this must be *before* the tempfile cleanup, in case of temporary
3385 # this must be *before* the tempfile cleanup, in case of temporary
3384 # history db
3386 # history db
3385 self.history_manager.end_session()
3387 self.history_manager.end_session()
3386
3388
3387 # Cleanup all tempfiles and folders left around
3389 # Cleanup all tempfiles and folders left around
3388 for tfile in self.tempfiles:
3390 for tfile in self.tempfiles:
3389 try:
3391 try:
3390 os.unlink(tfile)
3392 os.unlink(tfile)
3391 except OSError:
3393 except OSError:
3392 pass
3394 pass
3393
3395
3394 for tdir in self.tempdirs:
3396 for tdir in self.tempdirs:
3395 try:
3397 try:
3396 os.rmdir(tdir)
3398 os.rmdir(tdir)
3397 except OSError:
3399 except OSError:
3398 pass
3400 pass
3399
3401
3400 # Clear all user namespaces to release all references cleanly.
3402 # Clear all user namespaces to release all references cleanly.
3401 self.reset(new_session=False)
3403 self.reset(new_session=False)
3402
3404
3403 # Run user hooks
3405 # Run user hooks
3404 self.hooks.shutdown_hook()
3406 self.hooks.shutdown_hook()
3405
3407
3406 def cleanup(self):
3408 def cleanup(self):
3407 self.restore_sys_module_state()
3409 self.restore_sys_module_state()
3408
3410
3409
3411
3410 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3412 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3411 """An abstract base class for InteractiveShell."""
3413 """An abstract base class for InteractiveShell."""
3412
3414
3413 InteractiveShellABC.register(InteractiveShell)
3415 InteractiveShellABC.register(InteractiveShell)
@@ -1,702 +1,704 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4 from __future__ import print_function
4 from __future__ import print_function
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
9 # Copyright (C) 2008 The IPython Development Team
9 # Copyright (C) 2008 The IPython Development Team
10
10
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Stdlib
18 # Stdlib
19 import os
19 import os
20 import re
20 import re
21 import sys
21 import sys
22 import types
22 import types
23 from getopt import getopt, GetoptError
23 from getopt import getopt, GetoptError
24
24
25 # Our own
25 # Our own
26 from traitlets.config.configurable import Configurable
26 from traitlets.config.configurable import Configurable
27 from IPython.core import oinspect
27 from IPython.core import oinspect
28 from IPython.core.error import UsageError
28 from IPython.core.error import UsageError
29 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
29 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
30 from decorator import decorator
30 from decorator import decorator
31 from IPython.utils.ipstruct import Struct
31 from IPython.utils.ipstruct import Struct
32 from IPython.utils.process import arg_split
32 from IPython.utils.process import arg_split
33 from IPython.utils.py3compat import string_types, iteritems
33 from IPython.utils.py3compat import string_types, iteritems
34 from IPython.utils.text import dedent
34 from IPython.utils.text import dedent
35 from traitlets import Bool, Dict, Instance
35 from traitlets import Bool, Dict, Instance
36 from IPython.utils.warn import error
36 from IPython.utils.warn import error
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39 # Globals
39 # Globals
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41
41
42 # A dict we'll use for each class that has magics, used as temporary storage to
42 # A dict we'll use for each class that has magics, used as temporary storage to
43 # pass information between the @line/cell_magic method decorators and the
43 # pass information between the @line/cell_magic method decorators and the
44 # @magics_class class decorator, because the method decorators have no
44 # @magics_class class decorator, because the method decorators have no
45 # access to the class when they run. See for more details:
45 # access to the class when they run. See for more details:
46 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
46 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
47
47
48 magics = dict(line={}, cell={})
48 magics = dict(line={}, cell={})
49
49
50 magic_kinds = ('line', 'cell')
50 magic_kinds = ('line', 'cell')
51 magic_spec = ('line', 'cell', 'line_cell')
51 magic_spec = ('line', 'cell', 'line_cell')
52 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
52 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
53
53
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55 # Utility classes and functions
55 # Utility classes and functions
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57
57
58 class Bunch: pass
58 class Bunch: pass
59
59
60
60
61 def on_off(tag):
61 def on_off(tag):
62 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
62 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 return ['OFF','ON'][tag]
63 return ['OFF','ON'][tag]
64
64
65
65
66 def compress_dhist(dh):
66 def compress_dhist(dh):
67 """Compress a directory history into a new one with at most 20 entries.
67 """Compress a directory history into a new one with at most 20 entries.
68
68
69 Return a new list made from the first and last 10 elements of dhist after
69 Return a new list made from the first and last 10 elements of dhist after
70 removal of duplicates.
70 removal of duplicates.
71 """
71 """
72 head, tail = dh[:-10], dh[-10:]
72 head, tail = dh[:-10], dh[-10:]
73
73
74 newhead = []
74 newhead = []
75 done = set()
75 done = set()
76 for h in head:
76 for h in head:
77 if h in done:
77 if h in done:
78 continue
78 continue
79 newhead.append(h)
79 newhead.append(h)
80 done.add(h)
80 done.add(h)
81
81
82 return newhead + tail
82 return newhead + tail
83
83
84
84
85 def needs_local_scope(func):
85 def needs_local_scope(func):
86 """Decorator to mark magic functions which need to local scope to run."""
86 """Decorator to mark magic functions which need to local scope to run."""
87 func.needs_local_scope = True
87 func.needs_local_scope = True
88 return func
88 return func
89
89
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91 # Class and method decorators for registering magics
91 # Class and method decorators for registering magics
92 #-----------------------------------------------------------------------------
92 #-----------------------------------------------------------------------------
93
93
94 def magics_class(cls):
94 def magics_class(cls):
95 """Class decorator for all subclasses of the main Magics class.
95 """Class decorator for all subclasses of the main Magics class.
96
96
97 Any class that subclasses Magics *must* also apply this decorator, to
97 Any class that subclasses Magics *must* also apply this decorator, to
98 ensure that all the methods that have been decorated as line/cell magics
98 ensure that all the methods that have been decorated as line/cell magics
99 get correctly registered in the class instance. This is necessary because
99 get correctly registered in the class instance. This is necessary because
100 when method decorators run, the class does not exist yet, so they
100 when method decorators run, the class does not exist yet, so they
101 temporarily store their information into a module global. Application of
101 temporarily store their information into a module global. Application of
102 this class decorator copies that global data to the class instance and
102 this class decorator copies that global data to the class instance and
103 clears the global.
103 clears the global.
104
104
105 Obviously, this mechanism is not thread-safe, which means that the
105 Obviously, this mechanism is not thread-safe, which means that the
106 *creation* of subclasses of Magic should only be done in a single-thread
106 *creation* of subclasses of Magic should only be done in a single-thread
107 context. Instantiation of the classes has no restrictions. Given that
107 context. Instantiation of the classes has no restrictions. Given that
108 these classes are typically created at IPython startup time and before user
108 these classes are typically created at IPython startup time and before user
109 application code becomes active, in practice this should not pose any
109 application code becomes active, in practice this should not pose any
110 problems.
110 problems.
111 """
111 """
112 cls.registered = True
112 cls.registered = True
113 cls.magics = dict(line = magics['line'],
113 cls.magics = dict(line = magics['line'],
114 cell = magics['cell'])
114 cell = magics['cell'])
115 magics['line'] = {}
115 magics['line'] = {}
116 magics['cell'] = {}
116 magics['cell'] = {}
117 return cls
117 return cls
118
118
119
119
120 def record_magic(dct, magic_kind, magic_name, func):
120 def record_magic(dct, magic_kind, magic_name, func):
121 """Utility function to store a function as a magic of a specific kind.
121 """Utility function to store a function as a magic of a specific kind.
122
122
123 Parameters
123 Parameters
124 ----------
124 ----------
125 dct : dict
125 dct : dict
126 A dictionary with 'line' and 'cell' subdicts.
126 A dictionary with 'line' and 'cell' subdicts.
127
127
128 magic_kind : str
128 magic_kind : str
129 Kind of magic to be stored.
129 Kind of magic to be stored.
130
130
131 magic_name : str
131 magic_name : str
132 Key to store the magic as.
132 Key to store the magic as.
133
133
134 func : function
134 func : function
135 Callable object to store.
135 Callable object to store.
136 """
136 """
137 if magic_kind == 'line_cell':
137 if magic_kind == 'line_cell':
138 dct['line'][magic_name] = dct['cell'][magic_name] = func
138 dct['line'][magic_name] = dct['cell'][magic_name] = func
139 else:
139 else:
140 dct[magic_kind][magic_name] = func
140 dct[magic_kind][magic_name] = func
141
141
142
142
143 def validate_type(magic_kind):
143 def validate_type(magic_kind):
144 """Ensure that the given magic_kind is valid.
144 """Ensure that the given magic_kind is valid.
145
145
146 Check that the given magic_kind is one of the accepted spec types (stored
146 Check that the given magic_kind is one of the accepted spec types (stored
147 in the global `magic_spec`), raise ValueError otherwise.
147 in the global `magic_spec`), raise ValueError otherwise.
148 """
148 """
149 if magic_kind not in magic_spec:
149 if magic_kind not in magic_spec:
150 raise ValueError('magic_kind must be one of %s, %s given' %
150 raise ValueError('magic_kind must be one of %s, %s given' %
151 magic_kinds, magic_kind)
151 magic_kinds, magic_kind)
152
152
153
153
154 # The docstrings for the decorator below will be fairly similar for the two
154 # The docstrings for the decorator below will be fairly similar for the two
155 # types (method and function), so we generate them here once and reuse the
155 # types (method and function), so we generate them here once and reuse the
156 # templates below.
156 # templates below.
157 _docstring_template = \
157 _docstring_template = \
158 """Decorate the given {0} as {1} magic.
158 """Decorate the given {0} as {1} magic.
159
159
160 The decorator can be used with or without arguments, as follows.
160 The decorator can be used with or without arguments, as follows.
161
161
162 i) without arguments: it will create a {1} magic named as the {0} being
162 i) without arguments: it will create a {1} magic named as the {0} being
163 decorated::
163 decorated::
164
164
165 @deco
165 @deco
166 def foo(...)
166 def foo(...)
167
167
168 will create a {1} magic named `foo`.
168 will create a {1} magic named `foo`.
169
169
170 ii) with one string argument: which will be used as the actual name of the
170 ii) with one string argument: which will be used as the actual name of the
171 resulting magic::
171 resulting magic::
172
172
173 @deco('bar')
173 @deco('bar')
174 def foo(...)
174 def foo(...)
175
175
176 will create a {1} magic named `bar`.
176 will create a {1} magic named `bar`.
177 """
177 """
178
178
179 # These two are decorator factories. While they are conceptually very similar,
179 # These two are decorator factories. While they are conceptually very similar,
180 # there are enough differences in the details that it's simpler to have them
180 # there are enough differences in the details that it's simpler to have them
181 # written as completely standalone functions rather than trying to share code
181 # written as completely standalone functions rather than trying to share code
182 # and make a single one with convoluted logic.
182 # and make a single one with convoluted logic.
183
183
184 def _method_magic_marker(magic_kind):
184 def _method_magic_marker(magic_kind):
185 """Decorator factory for methods in Magics subclasses.
185 """Decorator factory for methods in Magics subclasses.
186 """
186 """
187
187
188 validate_type(magic_kind)
188 validate_type(magic_kind)
189
189
190 # This is a closure to capture the magic_kind. We could also use a class,
190 # This is a closure to capture the magic_kind. We could also use a class,
191 # but it's overkill for just that one bit of state.
191 # but it's overkill for just that one bit of state.
192 def magic_deco(arg):
192 def magic_deco(arg):
193 call = lambda f, *a, **k: f(*a, **k)
193 call = lambda f, *a, **k: f(*a, **k)
194
194
195 if callable(arg):
195 if callable(arg):
196 # "Naked" decorator call (just @foo, no args)
196 # "Naked" decorator call (just @foo, no args)
197 func = arg
197 func = arg
198 name = func.__name__
198 name = func.__name__
199 retval = decorator(call, func)
199 retval = decorator(call, func)
200 record_magic(magics, magic_kind, name, name)
200 record_magic(magics, magic_kind, name, name)
201 elif isinstance(arg, string_types):
201 elif isinstance(arg, string_types):
202 # Decorator called with arguments (@foo('bar'))
202 # Decorator called with arguments (@foo('bar'))
203 name = arg
203 name = arg
204 def mark(func, *a, **kw):
204 def mark(func, *a, **kw):
205 record_magic(magics, magic_kind, name, func.__name__)
205 record_magic(magics, magic_kind, name, func.__name__)
206 return decorator(call, func)
206 return decorator(call, func)
207 retval = mark
207 retval = mark
208 else:
208 else:
209 raise TypeError("Decorator can only be called with "
209 raise TypeError("Decorator can only be called with "
210 "string or function")
210 "string or function")
211 return retval
211 return retval
212
212
213 # Ensure the resulting decorator has a usable docstring
213 # Ensure the resulting decorator has a usable docstring
214 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
214 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
215 return magic_deco
215 return magic_deco
216
216
217
217
218 def _function_magic_marker(magic_kind):
218 def _function_magic_marker(magic_kind):
219 """Decorator factory for standalone functions.
219 """Decorator factory for standalone functions.
220 """
220 """
221 validate_type(magic_kind)
221 validate_type(magic_kind)
222
222
223 # This is a closure to capture the magic_kind. We could also use a class,
223 # This is a closure to capture the magic_kind. We could also use a class,
224 # but it's overkill for just that one bit of state.
224 # but it's overkill for just that one bit of state.
225 def magic_deco(arg):
225 def magic_deco(arg):
226 call = lambda f, *a, **k: f(*a, **k)
226 call = lambda f, *a, **k: f(*a, **k)
227
227
228 # Find get_ipython() in the caller's namespace
228 # Find get_ipython() in the caller's namespace
229 caller = sys._getframe(1)
229 caller = sys._getframe(1)
230 for ns in ['f_locals', 'f_globals', 'f_builtins']:
230 for ns in ['f_locals', 'f_globals', 'f_builtins']:
231 get_ipython = getattr(caller, ns).get('get_ipython')
231 get_ipython = getattr(caller, ns).get('get_ipython')
232 if get_ipython is not None:
232 if get_ipython is not None:
233 break
233 break
234 else:
234 else:
235 raise NameError('Decorator can only run in context where '
235 raise NameError('Decorator can only run in context where '
236 '`get_ipython` exists')
236 '`get_ipython` exists')
237
237
238 ip = get_ipython()
238 ip = get_ipython()
239
239
240 if callable(arg):
240 if callable(arg):
241 # "Naked" decorator call (just @foo, no args)
241 # "Naked" decorator call (just @foo, no args)
242 func = arg
242 func = arg
243 name = func.__name__
243 name = func.__name__
244 ip.register_magic_function(func, magic_kind, name)
244 ip.register_magic_function(func, magic_kind, name)
245 retval = decorator(call, func)
245 retval = decorator(call, func)
246 elif isinstance(arg, string_types):
246 elif isinstance(arg, string_types):
247 # Decorator called with arguments (@foo('bar'))
247 # Decorator called with arguments (@foo('bar'))
248 name = arg
248 name = arg
249 def mark(func, *a, **kw):
249 def mark(func, *a, **kw):
250 ip.register_magic_function(func, magic_kind, name)
250 ip.register_magic_function(func, magic_kind, name)
251 return decorator(call, func)
251 return decorator(call, func)
252 retval = mark
252 retval = mark
253 else:
253 else:
254 raise TypeError("Decorator can only be called with "
254 raise TypeError("Decorator can only be called with "
255 "string or function")
255 "string or function")
256 return retval
256 return retval
257
257
258 # Ensure the resulting decorator has a usable docstring
258 # Ensure the resulting decorator has a usable docstring
259 ds = _docstring_template.format('function', magic_kind)
259 ds = _docstring_template.format('function', magic_kind)
260
260
261 ds += dedent("""
261 ds += dedent("""
262 Note: this decorator can only be used in a context where IPython is already
262 Note: this decorator can only be used in a context where IPython is already
263 active, so that the `get_ipython()` call succeeds. You can therefore use
263 active, so that the `get_ipython()` call succeeds. You can therefore use
264 it in your startup files loaded after IPython initializes, but *not* in the
264 it in your startup files loaded after IPython initializes, but *not* in the
265 IPython configuration file itself, which is executed before IPython is
265 IPython configuration file itself, which is executed before IPython is
266 fully up and running. Any file located in the `startup` subdirectory of
266 fully up and running. Any file located in the `startup` subdirectory of
267 your configuration profile will be OK in this sense.
267 your configuration profile will be OK in this sense.
268 """)
268 """)
269
269
270 magic_deco.__doc__ = ds
270 magic_deco.__doc__ = ds
271 return magic_deco
271 return magic_deco
272
272
273
273
274 # Create the actual decorators for public use
274 # Create the actual decorators for public use
275
275
276 # These three are used to decorate methods in class definitions
276 # These three are used to decorate methods in class definitions
277 line_magic = _method_magic_marker('line')
277 line_magic = _method_magic_marker('line')
278 cell_magic = _method_magic_marker('cell')
278 cell_magic = _method_magic_marker('cell')
279 line_cell_magic = _method_magic_marker('line_cell')
279 line_cell_magic = _method_magic_marker('line_cell')
280
280
281 # These three decorate standalone functions and perform the decoration
281 # These three decorate standalone functions and perform the decoration
282 # immediately. They can only run where get_ipython() works
282 # immediately. They can only run where get_ipython() works
283 register_line_magic = _function_magic_marker('line')
283 register_line_magic = _function_magic_marker('line')
284 register_cell_magic = _function_magic_marker('cell')
284 register_cell_magic = _function_magic_marker('cell')
285 register_line_cell_magic = _function_magic_marker('line_cell')
285 register_line_cell_magic = _function_magic_marker('line_cell')
286
286
287 #-----------------------------------------------------------------------------
287 #-----------------------------------------------------------------------------
288 # Core Magic classes
288 # Core Magic classes
289 #-----------------------------------------------------------------------------
289 #-----------------------------------------------------------------------------
290
290
291 class MagicsManager(Configurable):
291 class MagicsManager(Configurable):
292 """Object that handles all magic-related functionality for IPython.
292 """Object that handles all magic-related functionality for IPython.
293 """
293 """
294 # Non-configurable class attributes
294 # Non-configurable class attributes
295
295
296 # A two-level dict, first keyed by magic type, then by magic function, and
296 # A two-level dict, first keyed by magic type, then by magic function, and
297 # holding the actual callable object as value. This is the dict used for
297 # holding the actual callable object as value. This is the dict used for
298 # magic function dispatch
298 # magic function dispatch
299 magics = Dict()
299 magics = Dict()
300
300
301 # A registry of the original objects that we've been given holding magics.
301 # A registry of the original objects that we've been given holding magics.
302 registry = Dict()
302 registry = Dict()
303
303
304 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
304 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
305
305
306 auto_magic = Bool(True, config=True, help=
306 auto_magic = Bool(True, config=True, help=
307 "Automatically call line magics without requiring explicit % prefix")
307 "Automatically call line magics without requiring explicit % prefix")
308
308
309 def _auto_magic_changed(self, name, value):
309 def _auto_magic_changed(self, name, value):
310 self.shell.automagic = value
310 self.shell.automagic = value
311
311
312 _auto_status = [
312 _auto_status = [
313 'Automagic is OFF, % prefix IS needed for line magics.',
313 'Automagic is OFF, % prefix IS needed for line magics.',
314 'Automagic is ON, % prefix IS NOT needed for line magics.']
314 'Automagic is ON, % prefix IS NOT needed for line magics.']
315
315
316 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
316 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
317
317
318 def __init__(self, shell=None, config=None, user_magics=None, **traits):
318 def __init__(self, shell=None, config=None, user_magics=None, **traits):
319
319
320 super(MagicsManager, self).__init__(shell=shell, config=config,
320 super(MagicsManager, self).__init__(shell=shell, config=config,
321 user_magics=user_magics, **traits)
321 user_magics=user_magics, **traits)
322 self.magics = dict(line={}, cell={})
322 self.magics = dict(line={}, cell={})
323 # Let's add the user_magics to the registry for uniformity, so *all*
323 # Let's add the user_magics to the registry for uniformity, so *all*
324 # registered magic containers can be found there.
324 # registered magic containers can be found there.
325 self.registry[user_magics.__class__.__name__] = user_magics
325 self.registry[user_magics.__class__.__name__] = user_magics
326
326
327 def auto_status(self):
327 def auto_status(self):
328 """Return descriptive string with automagic status."""
328 """Return descriptive string with automagic status."""
329 return self._auto_status[self.auto_magic]
329 return self._auto_status[self.auto_magic]
330
330
331 def lsmagic(self):
331 def lsmagic(self):
332 """Return a dict of currently available magic functions.
332 """Return a dict of currently available magic functions.
333
333
334 The return dict has the keys 'line' and 'cell', corresponding to the
334 The return dict has the keys 'line' and 'cell', corresponding to the
335 two types of magics we support. Each value is a list of names.
335 two types of magics we support. Each value is a list of names.
336 """
336 """
337 return self.magics
337 return self.magics
338
338
339 def lsmagic_docs(self, brief=False, missing=''):
339 def lsmagic_docs(self, brief=False, missing=''):
340 """Return dict of documentation of magic functions.
340 """Return dict of documentation of magic functions.
341
341
342 The return dict has the keys 'line' and 'cell', corresponding to the
342 The return dict has the keys 'line' and 'cell', corresponding to the
343 two types of magics we support. Each value is a dict keyed by magic
343 two types of magics we support. Each value is a dict keyed by magic
344 name whose value is the function docstring. If a docstring is
344 name whose value is the function docstring. If a docstring is
345 unavailable, the value of `missing` is used instead.
345 unavailable, the value of `missing` is used instead.
346
346
347 If brief is True, only the first line of each docstring will be returned.
347 If brief is True, only the first line of each docstring will be returned.
348 """
348 """
349 docs = {}
349 docs = {}
350 for m_type in self.magics:
350 for m_type in self.magics:
351 m_docs = {}
351 m_docs = {}
352 for m_name, m_func in iteritems(self.magics[m_type]):
352 for m_name, m_func in iteritems(self.magics[m_type]):
353 if m_func.__doc__:
353 if m_func.__doc__:
354 if brief:
354 if brief:
355 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
355 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
356 else:
356 else:
357 m_docs[m_name] = m_func.__doc__.rstrip()
357 m_docs[m_name] = m_func.__doc__.rstrip()
358 else:
358 else:
359 m_docs[m_name] = missing
359 m_docs[m_name] = missing
360 docs[m_type] = m_docs
360 docs[m_type] = m_docs
361 return docs
361 return docs
362
362
363 def register(self, *magic_objects):
363 def register(self, *magic_objects):
364 """Register one or more instances of Magics.
364 """Register one or more instances of Magics.
365
365
366 Take one or more classes or instances of classes that subclass the main
366 Take one or more classes or instances of classes that subclass the main
367 `core.Magic` class, and register them with IPython to use the magic
367 `core.Magic` class, and register them with IPython to use the magic
368 functions they provide. The registration process will then ensure that
368 functions they provide. The registration process will then ensure that
369 any methods that have decorated to provide line and/or cell magics will
369 any methods that have decorated to provide line and/or cell magics will
370 be recognized with the `%x`/`%%x` syntax as a line/cell magic
370 be recognized with the `%x`/`%%x` syntax as a line/cell magic
371 respectively.
371 respectively.
372
372
373 If classes are given, they will be instantiated with the default
373 If classes are given, they will be instantiated with the default
374 constructor. If your classes need a custom constructor, you should
374 constructor. If your classes need a custom constructor, you should
375 instanitate them first and pass the instance.
375 instanitate them first and pass the instance.
376
376
377 The provided arguments can be an arbitrary mix of classes and instances.
377 The provided arguments can be an arbitrary mix of classes and instances.
378
378
379 Parameters
379 Parameters
380 ----------
380 ----------
381 magic_objects : one or more classes or instances
381 magic_objects : one or more classes or instances
382 """
382 """
383 # Start by validating them to ensure they have all had their magic
383 # Start by validating them to ensure they have all had their magic
384 # methods registered at the instance level
384 # methods registered at the instance level
385 for m in magic_objects:
385 for m in magic_objects:
386 if not m.registered:
386 if not m.registered:
387 raise ValueError("Class of magics %r was constructed without "
387 raise ValueError("Class of magics %r was constructed without "
388 "the @register_magics class decorator")
388 "the @register_magics class decorator")
389 if isinstance(m, type):
389 if isinstance(m, type):
390 # If we're given an uninstantiated class
390 # If we're given an uninstantiated class
391 m = m(shell=self.shell)
391 m = m(shell=self.shell)
392
392
393 # Now that we have an instance, we can register it and update the
393 # Now that we have an instance, we can register it and update the
394 # table of callables
394 # table of callables
395 self.registry[m.__class__.__name__] = m
395 self.registry[m.__class__.__name__] = m
396 for mtype in magic_kinds:
396 for mtype in magic_kinds:
397 self.magics[mtype].update(m.magics[mtype])
397 self.magics[mtype].update(m.magics[mtype])
398
398
399 def register_function(self, func, magic_kind='line', magic_name=None):
399 def register_function(self, func, magic_kind='line', magic_name=None):
400 """Expose a standalone function as magic function for IPython.
400 """Expose a standalone function as magic function for IPython.
401
401
402 This will create an IPython magic (line, cell or both) from a
402 This will create an IPython magic (line, cell or both) from a
403 standalone function. The functions should have the following
403 standalone function. The functions should have the following
404 signatures:
404 signatures:
405
405
406 * For line magics: `def f(line)`
406 * For line magics: `def f(line)`
407 * For cell magics: `def f(line, cell)`
407 * For cell magics: `def f(line, cell)`
408 * For a function that does both: `def f(line, cell=None)`
408 * For a function that does both: `def f(line, cell=None)`
409
409
410 In the latter case, the function will be called with `cell==None` when
410 In the latter case, the function will be called with `cell==None` when
411 invoked as `%f`, and with cell as a string when invoked as `%%f`.
411 invoked as `%f`, and with cell as a string when invoked as `%%f`.
412
412
413 Parameters
413 Parameters
414 ----------
414 ----------
415 func : callable
415 func : callable
416 Function to be registered as a magic.
416 Function to be registered as a magic.
417
417
418 magic_kind : str
418 magic_kind : str
419 Kind of magic, one of 'line', 'cell' or 'line_cell'
419 Kind of magic, one of 'line', 'cell' or 'line_cell'
420
420
421 magic_name : optional str
421 magic_name : optional str
422 If given, the name the magic will have in the IPython namespace. By
422 If given, the name the magic will have in the IPython namespace. By
423 default, the name of the function itself is used.
423 default, the name of the function itself is used.
424 """
424 """
425
425
426 # Create the new method in the user_magics and register it in the
426 # Create the new method in the user_magics and register it in the
427 # global table
427 # global table
428 validate_type(magic_kind)
428 validate_type(magic_kind)
429 magic_name = func.__name__ if magic_name is None else magic_name
429 magic_name = func.__name__ if magic_name is None else magic_name
430 setattr(self.user_magics, magic_name, func)
430 setattr(self.user_magics, magic_name, func)
431 record_magic(self.magics, magic_kind, magic_name, func)
431 record_magic(self.magics, magic_kind, magic_name, func)
432
432
433 def define_magic(self, name, func):
433 def define_magic(self, name, func):
434 """[Deprecated] Expose own function as magic function for IPython.
434 """[Deprecated] Expose own function as magic function for IPython.
435
435
436 Will be removed in IPython 5.0
437
436 Example::
438 Example::
437
439
438 def foo_impl(self, parameter_s=''):
440 def foo_impl(self, parameter_s=''):
439 'My very own magic!. (Use docstrings, IPython reads them).'
441 'My very own magic!. (Use docstrings, IPython reads them).'
440 print 'Magic function. Passed parameter is between < >:'
442 print 'Magic function. Passed parameter is between < >:'
441 print '<%s>' % parameter_s
443 print '<%s>' % parameter_s
442 print 'The self object is:', self
444 print 'The self object is:', self
443
445
444 ip.define_magic('foo',foo_impl)
446 ip.define_magic('foo',foo_impl)
445 """
447 """
446 meth = types.MethodType(func, self.user_magics)
448 meth = types.MethodType(func, self.user_magics)
447 setattr(self.user_magics, name, meth)
449 setattr(self.user_magics, name, meth)
448 record_magic(self.magics, 'line', name, meth)
450 record_magic(self.magics, 'line', name, meth)
449
451
450 def register_alias(self, alias_name, magic_name, magic_kind='line'):
452 def register_alias(self, alias_name, magic_name, magic_kind='line'):
451 """Register an alias to a magic function.
453 """Register an alias to a magic function.
452
454
453 The alias is an instance of :class:`MagicAlias`, which holds the
455 The alias is an instance of :class:`MagicAlias`, which holds the
454 name and kind of the magic it should call. Binding is done at
456 name and kind of the magic it should call. Binding is done at
455 call time, so if the underlying magic function is changed the alias
457 call time, so if the underlying magic function is changed the alias
456 will call the new function.
458 will call the new function.
457
459
458 Parameters
460 Parameters
459 ----------
461 ----------
460 alias_name : str
462 alias_name : str
461 The name of the magic to be registered.
463 The name of the magic to be registered.
462
464
463 magic_name : str
465 magic_name : str
464 The name of an existing magic.
466 The name of an existing magic.
465
467
466 magic_kind : str
468 magic_kind : str
467 Kind of magic, one of 'line' or 'cell'
469 Kind of magic, one of 'line' or 'cell'
468 """
470 """
469
471
470 # `validate_type` is too permissive, as it allows 'line_cell'
472 # `validate_type` is too permissive, as it allows 'line_cell'
471 # which we do not handle.
473 # which we do not handle.
472 if magic_kind not in magic_kinds:
474 if magic_kind not in magic_kinds:
473 raise ValueError('magic_kind must be one of %s, %s given' %
475 raise ValueError('magic_kind must be one of %s, %s given' %
474 magic_kinds, magic_kind)
476 magic_kinds, magic_kind)
475
477
476 alias = MagicAlias(self.shell, magic_name, magic_kind)
478 alias = MagicAlias(self.shell, magic_name, magic_kind)
477 setattr(self.user_magics, alias_name, alias)
479 setattr(self.user_magics, alias_name, alias)
478 record_magic(self.magics, magic_kind, alias_name, alias)
480 record_magic(self.magics, magic_kind, alias_name, alias)
479
481
480 # Key base class that provides the central functionality for magics.
482 # Key base class that provides the central functionality for magics.
481
483
482
484
483 class Magics(Configurable):
485 class Magics(Configurable):
484 """Base class for implementing magic functions.
486 """Base class for implementing magic functions.
485
487
486 Shell functions which can be reached as %function_name. All magic
488 Shell functions which can be reached as %function_name. All magic
487 functions should accept a string, which they can parse for their own
489 functions should accept a string, which they can parse for their own
488 needs. This can make some functions easier to type, eg `%cd ../`
490 needs. This can make some functions easier to type, eg `%cd ../`
489 vs. `%cd("../")`
491 vs. `%cd("../")`
490
492
491 Classes providing magic functions need to subclass this class, and they
493 Classes providing magic functions need to subclass this class, and they
492 MUST:
494 MUST:
493
495
494 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
496 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
495 individual methods as magic functions, AND
497 individual methods as magic functions, AND
496
498
497 - Use the class decorator `@magics_class` to ensure that the magic
499 - Use the class decorator `@magics_class` to ensure that the magic
498 methods are properly registered at the instance level upon instance
500 methods are properly registered at the instance level upon instance
499 initialization.
501 initialization.
500
502
501 See :mod:`magic_functions` for examples of actual implementation classes.
503 See :mod:`magic_functions` for examples of actual implementation classes.
502 """
504 """
503 # Dict holding all command-line options for each magic.
505 # Dict holding all command-line options for each magic.
504 options_table = None
506 options_table = None
505 # Dict for the mapping of magic names to methods, set by class decorator
507 # Dict for the mapping of magic names to methods, set by class decorator
506 magics = None
508 magics = None
507 # Flag to check that the class decorator was properly applied
509 # Flag to check that the class decorator was properly applied
508 registered = False
510 registered = False
509 # Instance of IPython shell
511 # Instance of IPython shell
510 shell = None
512 shell = None
511
513
512 def __init__(self, shell=None, **kwargs):
514 def __init__(self, shell=None, **kwargs):
513 if not(self.__class__.registered):
515 if not(self.__class__.registered):
514 raise ValueError('Magics subclass without registration - '
516 raise ValueError('Magics subclass without registration - '
515 'did you forget to apply @magics_class?')
517 'did you forget to apply @magics_class?')
516 if shell is not None:
518 if shell is not None:
517 if hasattr(shell, 'configurables'):
519 if hasattr(shell, 'configurables'):
518 shell.configurables.append(self)
520 shell.configurables.append(self)
519 if hasattr(shell, 'config'):
521 if hasattr(shell, 'config'):
520 kwargs.setdefault('parent', shell)
522 kwargs.setdefault('parent', shell)
521 kwargs['shell'] = shell
523 kwargs['shell'] = shell
522
524
523 self.shell = shell
525 self.shell = shell
524 self.options_table = {}
526 self.options_table = {}
525 # The method decorators are run when the instance doesn't exist yet, so
527 # The method decorators are run when the instance doesn't exist yet, so
526 # they can only record the names of the methods they are supposed to
528 # they can only record the names of the methods they are supposed to
527 # grab. Only now, that the instance exists, can we create the proper
529 # grab. Only now, that the instance exists, can we create the proper
528 # mapping to bound methods. So we read the info off the original names
530 # mapping to bound methods. So we read the info off the original names
529 # table and replace each method name by the actual bound method.
531 # table and replace each method name by the actual bound method.
530 # But we mustn't clobber the *class* mapping, in case of multiple instances.
532 # But we mustn't clobber the *class* mapping, in case of multiple instances.
531 class_magics = self.magics
533 class_magics = self.magics
532 self.magics = {}
534 self.magics = {}
533 for mtype in magic_kinds:
535 for mtype in magic_kinds:
534 tab = self.magics[mtype] = {}
536 tab = self.magics[mtype] = {}
535 cls_tab = class_magics[mtype]
537 cls_tab = class_magics[mtype]
536 for magic_name, meth_name in iteritems(cls_tab):
538 for magic_name, meth_name in iteritems(cls_tab):
537 if isinstance(meth_name, string_types):
539 if isinstance(meth_name, string_types):
538 # it's a method name, grab it
540 # it's a method name, grab it
539 tab[magic_name] = getattr(self, meth_name)
541 tab[magic_name] = getattr(self, meth_name)
540 else:
542 else:
541 # it's the real thing
543 # it's the real thing
542 tab[magic_name] = meth_name
544 tab[magic_name] = meth_name
543 # Configurable **needs** to be initiated at the end or the config
545 # Configurable **needs** to be initiated at the end or the config
544 # magics get screwed up.
546 # magics get screwed up.
545 super(Magics, self).__init__(**kwargs)
547 super(Magics, self).__init__(**kwargs)
546
548
547 def arg_err(self,func):
549 def arg_err(self,func):
548 """Print docstring if incorrect arguments were passed"""
550 """Print docstring if incorrect arguments were passed"""
549 print('Error in arguments:')
551 print('Error in arguments:')
550 print(oinspect.getdoc(func))
552 print(oinspect.getdoc(func))
551
553
552 def format_latex(self, strng):
554 def format_latex(self, strng):
553 """Format a string for latex inclusion."""
555 """Format a string for latex inclusion."""
554
556
555 # Characters that need to be escaped for latex:
557 # Characters that need to be escaped for latex:
556 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
558 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
557 # Magic command names as headers:
559 # Magic command names as headers:
558 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
560 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
559 re.MULTILINE)
561 re.MULTILINE)
560 # Magic commands
562 # Magic commands
561 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
563 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
562 re.MULTILINE)
564 re.MULTILINE)
563 # Paragraph continue
565 # Paragraph continue
564 par_re = re.compile(r'\\$',re.MULTILINE)
566 par_re = re.compile(r'\\$',re.MULTILINE)
565
567
566 # The "\n" symbol
568 # The "\n" symbol
567 newline_re = re.compile(r'\\n')
569 newline_re = re.compile(r'\\n')
568
570
569 # Now build the string for output:
571 # Now build the string for output:
570 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
572 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
571 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
573 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
572 strng)
574 strng)
573 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
575 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
574 strng = par_re.sub(r'\\\\',strng)
576 strng = par_re.sub(r'\\\\',strng)
575 strng = escape_re.sub(r'\\\1',strng)
577 strng = escape_re.sub(r'\\\1',strng)
576 strng = newline_re.sub(r'\\textbackslash{}n',strng)
578 strng = newline_re.sub(r'\\textbackslash{}n',strng)
577 return strng
579 return strng
578
580
579 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
581 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
580 """Parse options passed to an argument string.
582 """Parse options passed to an argument string.
581
583
582 The interface is similar to that of :func:`getopt.getopt`, but it
584 The interface is similar to that of :func:`getopt.getopt`, but it
583 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
585 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
584 and the stripped argument string still as a string.
586 and the stripped argument string still as a string.
585
587
586 arg_str is quoted as a true sys.argv vector by using shlex.split.
588 arg_str is quoted as a true sys.argv vector by using shlex.split.
587 This allows us to easily expand variables, glob files, quote
589 This allows us to easily expand variables, glob files, quote
588 arguments, etc.
590 arguments, etc.
589
591
590 Parameters
592 Parameters
591 ----------
593 ----------
592
594
593 arg_str : str
595 arg_str : str
594 The arguments to parse.
596 The arguments to parse.
595
597
596 opt_str : str
598 opt_str : str
597 The options specification.
599 The options specification.
598
600
599 mode : str, default 'string'
601 mode : str, default 'string'
600 If given as 'list', the argument string is returned as a list (split
602 If given as 'list', the argument string is returned as a list (split
601 on whitespace) instead of a string.
603 on whitespace) instead of a string.
602
604
603 list_all : bool, default False
605 list_all : bool, default False
604 Put all option values in lists. Normally only options
606 Put all option values in lists. Normally only options
605 appearing more than once are put in a list.
607 appearing more than once are put in a list.
606
608
607 posix : bool, default True
609 posix : bool, default True
608 Whether to split the input line in POSIX mode or not, as per the
610 Whether to split the input line in POSIX mode or not, as per the
609 conventions outlined in the :mod:`shlex` module from the standard
611 conventions outlined in the :mod:`shlex` module from the standard
610 library.
612 library.
611 """
613 """
612
614
613 # inject default options at the beginning of the input line
615 # inject default options at the beginning of the input line
614 caller = sys._getframe(1).f_code.co_name
616 caller = sys._getframe(1).f_code.co_name
615 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
617 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
616
618
617 mode = kw.get('mode','string')
619 mode = kw.get('mode','string')
618 if mode not in ['string','list']:
620 if mode not in ['string','list']:
619 raise ValueError('incorrect mode given: %s' % mode)
621 raise ValueError('incorrect mode given: %s' % mode)
620 # Get options
622 # Get options
621 list_all = kw.get('list_all',0)
623 list_all = kw.get('list_all',0)
622 posix = kw.get('posix', os.name == 'posix')
624 posix = kw.get('posix', os.name == 'posix')
623 strict = kw.get('strict', True)
625 strict = kw.get('strict', True)
624
626
625 # Check if we have more than one argument to warrant extra processing:
627 # Check if we have more than one argument to warrant extra processing:
626 odict = {} # Dictionary with options
628 odict = {} # Dictionary with options
627 args = arg_str.split()
629 args = arg_str.split()
628 if len(args) >= 1:
630 if len(args) >= 1:
629 # If the list of inputs only has 0 or 1 thing in it, there's no
631 # If the list of inputs only has 0 or 1 thing in it, there's no
630 # need to look for options
632 # need to look for options
631 argv = arg_split(arg_str, posix, strict)
633 argv = arg_split(arg_str, posix, strict)
632 # Do regular option processing
634 # Do regular option processing
633 try:
635 try:
634 opts,args = getopt(argv, opt_str, long_opts)
636 opts,args = getopt(argv, opt_str, long_opts)
635 except GetoptError as e:
637 except GetoptError as e:
636 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
638 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
637 " ".join(long_opts)))
639 " ".join(long_opts)))
638 for o,a in opts:
640 for o,a in opts:
639 if o.startswith('--'):
641 if o.startswith('--'):
640 o = o[2:]
642 o = o[2:]
641 else:
643 else:
642 o = o[1:]
644 o = o[1:]
643 try:
645 try:
644 odict[o].append(a)
646 odict[o].append(a)
645 except AttributeError:
647 except AttributeError:
646 odict[o] = [odict[o],a]
648 odict[o] = [odict[o],a]
647 except KeyError:
649 except KeyError:
648 if list_all:
650 if list_all:
649 odict[o] = [a]
651 odict[o] = [a]
650 else:
652 else:
651 odict[o] = a
653 odict[o] = a
652
654
653 # Prepare opts,args for return
655 # Prepare opts,args for return
654 opts = Struct(odict)
656 opts = Struct(odict)
655 if mode == 'string':
657 if mode == 'string':
656 args = ' '.join(args)
658 args = ' '.join(args)
657
659
658 return opts,args
660 return opts,args
659
661
660 def default_option(self, fn, optstr):
662 def default_option(self, fn, optstr):
661 """Make an entry in the options_table for fn, with value optstr"""
663 """Make an entry in the options_table for fn, with value optstr"""
662
664
663 if fn not in self.lsmagic():
665 if fn not in self.lsmagic():
664 error("%s is not a magic function" % fn)
666 error("%s is not a magic function" % fn)
665 self.options_table[fn] = optstr
667 self.options_table[fn] = optstr
666
668
667
669
668 class MagicAlias(object):
670 class MagicAlias(object):
669 """An alias to another magic function.
671 """An alias to another magic function.
670
672
671 An alias is determined by its magic name and magic kind. Lookup
673 An alias is determined by its magic name and magic kind. Lookup
672 is done at call time, so if the underlying magic changes the alias
674 is done at call time, so if the underlying magic changes the alias
673 will call the new function.
675 will call the new function.
674
676
675 Use the :meth:`MagicsManager.register_alias` method or the
677 Use the :meth:`MagicsManager.register_alias` method or the
676 `%alias_magic` magic function to create and register a new alias.
678 `%alias_magic` magic function to create and register a new alias.
677 """
679 """
678 def __init__(self, shell, magic_name, magic_kind):
680 def __init__(self, shell, magic_name, magic_kind):
679 self.shell = shell
681 self.shell = shell
680 self.magic_name = magic_name
682 self.magic_name = magic_name
681 self.magic_kind = magic_kind
683 self.magic_kind = magic_kind
682
684
683 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
685 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
684 self.__doc__ = "Alias for `%s`." % self.pretty_target
686 self.__doc__ = "Alias for `%s`." % self.pretty_target
685
687
686 self._in_call = False
688 self._in_call = False
687
689
688 def __call__(self, *args, **kwargs):
690 def __call__(self, *args, **kwargs):
689 """Call the magic alias."""
691 """Call the magic alias."""
690 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
692 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
691 if fn is None:
693 if fn is None:
692 raise UsageError("Magic `%s` not found." % self.pretty_target)
694 raise UsageError("Magic `%s` not found." % self.pretty_target)
693
695
694 # Protect against infinite recursion.
696 # Protect against infinite recursion.
695 if self._in_call:
697 if self._in_call:
696 raise UsageError("Infinite recursion detected; "
698 raise UsageError("Infinite recursion detected; "
697 "magic aliases cannot call themselves.")
699 "magic aliases cannot call themselves.")
698 self._in_call = True
700 self._in_call = True
699 try:
701 try:
700 return fn(*args, **kwargs)
702 return fn(*args, **kwargs)
701 finally:
703 finally:
702 self._in_call = False
704 self._in_call = False
@@ -1,46 +1,47 b''
1 """Deprecated Magic functions.
1 """Deprecated Magic functions.
2 """
2 """
3 from __future__ import print_function
3 from __future__ import print_function
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 # Our own packages
16 # Our own packages
17 from IPython.core.magic import Magics, magics_class, line_magic
17 from IPython.core.magic import Magics, magics_class, line_magic
18 import warnings
18
19
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20 # Magic implementation classes
21 # Magic implementation classes
21 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
22
23
23 @magics_class
24 @magics_class
24 class DeprecatedMagics(Magics):
25 class DeprecatedMagics(Magics):
25 """Magics slated for later removal."""
26 """Magics slated for later removal."""
26
27
27 @line_magic
28 @line_magic
28 def install_profiles(self, parameter_s=''):
29 def install_profiles(self, parameter_s=''):
29 """%install_profiles has been deprecated."""
30 """%install_profiles has been deprecated."""
30 print('\n'.join([
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 "Use `ipython profile list` to view available profiles.",
33 "Use `ipython profile list` to view available profiles.",
33 "Requesting a profile with `ipython profile create <name>`",
34 "Requesting a profile with `ipython profile create <name>`",
34 "or `ipython --profile=<name>` will start with the bundled",
35 "or `ipython --profile=<name>` will start with the bundled",
35 "profile of that name if it exists."
36 "profile of that name if it exists."
36 ]))
37 ]))
37
38
38 @line_magic
39 @line_magic
39 def install_default_config(self, parameter_s=''):
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 print('\n'.join([
42 print('\n'.join([
42 "%install_default_config has been deprecated.",
43 "%install_default_config has been deprecated.",
43 "Use `ipython profile create <name>` to initialize a profile",
44 "Use `ipython profile create <name>` to initialize a profile",
44 "with the default config files.",
45 "with the default config files.",
45 "Add `--reset` to overwrite already existing config files with defaults."
46 "Add `--reset` to overwrite already existing config files with defaults."
46 ]))
47 ]))
@@ -1,433 +1,435 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 A mixin for :class:`~IPython.core.application.Application` classes that
3 A mixin for :class:`~IPython.core.application.Application` classes that
4 launch InteractiveShell instances, load extensions, etc.
4 launch InteractiveShell instances, load extensions, etc.
5 """
5 """
6
6
7 # Copyright (c) IPython Development Team.
7 # Copyright (c) IPython Development Team.
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9
9
10 from __future__ import absolute_import
10 from __future__ import absolute_import
11 from __future__ import print_function
11 from __future__ import print_function
12
12
13 import glob
13 import glob
14 import os
14 import os
15 import sys
15 import sys
16
16
17 from traitlets.config.application import boolean_flag
17 from traitlets.config.application import boolean_flag
18 from traitlets.config.configurable import Configurable
18 from traitlets.config.configurable import Configurable
19 from traitlets.config.loader import Config
19 from traitlets.config.loader import Config
20 from IPython.core import pylabtools
20 from IPython.core import pylabtools
21 from IPython.utils import py3compat
21 from IPython.utils import py3compat
22 from IPython.utils.contexts import preserve_keys
22 from IPython.utils.contexts import preserve_keys
23 from IPython.utils.path import filefind
23 from IPython.utils.path import filefind
24 from traitlets import (
24 from traitlets import (
25 Unicode, Instance, List, Bool, CaselessStrEnum
25 Unicode, Instance, List, Bool, CaselessStrEnum
26 )
26 )
27 from IPython.lib.inputhook import guis
27 from IPython.lib.inputhook import guis
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Aliases and Flags
30 # Aliases and Flags
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 gui_keys = tuple(sorted([ key for key in guis if key is not None ]))
33 gui_keys = tuple(sorted([ key for key in guis if key is not None ]))
34
34
35 backend_keys = sorted(pylabtools.backends.keys())
35 backend_keys = sorted(pylabtools.backends.keys())
36 backend_keys.insert(0, 'auto')
36 backend_keys.insert(0, 'auto')
37
37
38 shell_flags = {}
38 shell_flags = {}
39
39
40 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
40 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
41 addflag('autoindent', 'InteractiveShell.autoindent',
41 addflag('autoindent', 'InteractiveShell.autoindent',
42 'Turn on autoindenting.', 'Turn off autoindenting.'
42 'Turn on autoindenting.', 'Turn off autoindenting.'
43 )
43 )
44 addflag('automagic', 'InteractiveShell.automagic',
44 addflag('automagic', 'InteractiveShell.automagic',
45 """Turn on the auto calling of magic commands. Type %%magic at the
45 """Turn on the auto calling of magic commands. Type %%magic at the
46 IPython prompt for more information.""",
46 IPython prompt for more information.""",
47 'Turn off the auto calling of magic commands.'
47 'Turn off the auto calling of magic commands.'
48 )
48 )
49 addflag('pdb', 'InteractiveShell.pdb',
49 addflag('pdb', 'InteractiveShell.pdb',
50 "Enable auto calling the pdb debugger after every exception.",
50 "Enable auto calling the pdb debugger after every exception.",
51 "Disable auto calling the pdb debugger after every exception."
51 "Disable auto calling the pdb debugger after every exception."
52 )
52 )
53 # pydb flag doesn't do any config, as core.debugger switches on import,
53 # pydb flag doesn't do any config, as core.debugger switches on import,
54 # which is before parsing. This just allows the flag to be passed.
54 # which is before parsing. This just allows the flag to be passed.
55 shell_flags.update(dict(
55 shell_flags.update(dict(
56 pydb = ({},
56 pydb = ({},
57 """Use the third party 'pydb' package as debugger, instead of pdb.
57 """Use the third party 'pydb' package as debugger, instead of pdb.
58 Requires that pydb is installed."""
58 Requires that pydb is installed."""
59 )
59 )
60 ))
60 ))
61 addflag('pprint', 'PlainTextFormatter.pprint',
61 addflag('pprint', 'PlainTextFormatter.pprint',
62 "Enable auto pretty printing of results.",
62 "Enable auto pretty printing of results.",
63 "Disable auto pretty printing of results."
63 "Disable auto pretty printing of results."
64 )
64 )
65 addflag('color-info', 'InteractiveShell.color_info',
65 addflag('color-info', 'InteractiveShell.color_info',
66 """IPython can display information about objects via a set of functions,
66 """IPython can display information about objects via a set of functions,
67 and optionally can use colors for this, syntax highlighting
67 and optionally can use colors for this, syntax highlighting
68 source code and various other elements. This is on by default, but can cause
68 source code and various other elements. This is on by default, but can cause
69 problems with some pagers. If you see such problems, you can disable the
69 problems with some pagers. If you see such problems, you can disable the
70 colours.""",
70 colours.""",
71 "Disable using colors for info related things."
71 "Disable using colors for info related things."
72 )
72 )
73 addflag('deep-reload', 'InteractiveShell.deep_reload',
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 deep_reload module which reloads changes in modules recursively (it
77 deep_reload module which reloads changes in modules recursively (it
76 replaces the reload() function, so you don't need to change anything to
78 replaces the reload() function, so you don't need to change anything to
77 use it). deep_reload() forces a full reload of modules whose code may
79 use it). deep_reload() forces a full reload of modules whose code may
78 have changed, which the default reload() function does not. When
80 have changed, which the default reload() function does not. When
79 deep_reload is off, IPython will use the normal reload(), but
81 deep_reload is off, IPython will use the normal reload(), but
80 deep_reload will still be available as dreload(). This feature is off
82 deep_reload will still be available as dreload(). This feature is off
81 by default [which means that you have both normal reload() and
83 by default [which means that you have both normal reload() and
82 dreload()].""",
84 dreload()].""",
83 "Disable deep (recursive) reloading by default."
85 "Disable deep (recursive) reloading by default."
84 )
86 )
85 nosep_config = Config()
87 nosep_config = Config()
86 nosep_config.InteractiveShell.separate_in = ''
88 nosep_config.InteractiveShell.separate_in = ''
87 nosep_config.InteractiveShell.separate_out = ''
89 nosep_config.InteractiveShell.separate_out = ''
88 nosep_config.InteractiveShell.separate_out2 = ''
90 nosep_config.InteractiveShell.separate_out2 = ''
89
91
90 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
92 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
91 shell_flags['pylab'] = (
93 shell_flags['pylab'] = (
92 {'InteractiveShellApp' : {'pylab' : 'auto'}},
94 {'InteractiveShellApp' : {'pylab' : 'auto'}},
93 """Pre-load matplotlib and numpy for interactive use with
95 """Pre-load matplotlib and numpy for interactive use with
94 the default matplotlib backend."""
96 the default matplotlib backend."""
95 )
97 )
96 shell_flags['matplotlib'] = (
98 shell_flags['matplotlib'] = (
97 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
99 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
98 """Configure matplotlib for interactive use with
100 """Configure matplotlib for interactive use with
99 the default matplotlib backend."""
101 the default matplotlib backend."""
100 )
102 )
101
103
102 # it's possible we don't want short aliases for *all* of these:
104 # it's possible we don't want short aliases for *all* of these:
103 shell_aliases = dict(
105 shell_aliases = dict(
104 autocall='InteractiveShell.autocall',
106 autocall='InteractiveShell.autocall',
105 colors='InteractiveShell.colors',
107 colors='InteractiveShell.colors',
106 logfile='InteractiveShell.logfile',
108 logfile='InteractiveShell.logfile',
107 logappend='InteractiveShell.logappend',
109 logappend='InteractiveShell.logappend',
108 c='InteractiveShellApp.code_to_run',
110 c='InteractiveShellApp.code_to_run',
109 m='InteractiveShellApp.module_to_run',
111 m='InteractiveShellApp.module_to_run',
110 ext='InteractiveShellApp.extra_extension',
112 ext='InteractiveShellApp.extra_extension',
111 gui='InteractiveShellApp.gui',
113 gui='InteractiveShellApp.gui',
112 pylab='InteractiveShellApp.pylab',
114 pylab='InteractiveShellApp.pylab',
113 matplotlib='InteractiveShellApp.matplotlib',
115 matplotlib='InteractiveShellApp.matplotlib',
114 )
116 )
115 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
117 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
116
118
117 #-----------------------------------------------------------------------------
119 #-----------------------------------------------------------------------------
118 # Main classes and functions
120 # Main classes and functions
119 #-----------------------------------------------------------------------------
121 #-----------------------------------------------------------------------------
120
122
121 class InteractiveShellApp(Configurable):
123 class InteractiveShellApp(Configurable):
122 """A Mixin for applications that start InteractiveShell instances.
124 """A Mixin for applications that start InteractiveShell instances.
123
125
124 Provides configurables for loading extensions and executing files
126 Provides configurables for loading extensions and executing files
125 as part of configuring a Shell environment.
127 as part of configuring a Shell environment.
126
128
127 The following methods should be called by the :meth:`initialize` method
129 The following methods should be called by the :meth:`initialize` method
128 of the subclass:
130 of the subclass:
129
131
130 - :meth:`init_path`
132 - :meth:`init_path`
131 - :meth:`init_shell` (to be implemented by the subclass)
133 - :meth:`init_shell` (to be implemented by the subclass)
132 - :meth:`init_gui_pylab`
134 - :meth:`init_gui_pylab`
133 - :meth:`init_extensions`
135 - :meth:`init_extensions`
134 - :meth:`init_code`
136 - :meth:`init_code`
135 """
137 """
136 extensions = List(Unicode(), config=True,
138 extensions = List(Unicode(), config=True,
137 help="A list of dotted module names of IPython extensions to load."
139 help="A list of dotted module names of IPython extensions to load."
138 )
140 )
139 extra_extension = Unicode('', config=True,
141 extra_extension = Unicode('', config=True,
140 help="dotted module name of an IPython extension to load."
142 help="dotted module name of an IPython extension to load."
141 )
143 )
142
144
143 reraise_ipython_extension_failures = Bool(
145 reraise_ipython_extension_failures = Bool(
144 False,
146 False,
145 config=True,
147 config=True,
146 help="Reraise exceptions encountered loading IPython extensions?",
148 help="Reraise exceptions encountered loading IPython extensions?",
147 )
149 )
148
150
149 # Extensions that are always loaded (not configurable)
151 # Extensions that are always loaded (not configurable)
150 default_extensions = List(Unicode(), [u'storemagic'], config=False)
152 default_extensions = List(Unicode(), [u'storemagic'], config=False)
151
153
152 hide_initial_ns = Bool(True, config=True,
154 hide_initial_ns = Bool(True, config=True,
153 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
155 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
154 be hidden from tools like %who?"""
156 be hidden from tools like %who?"""
155 )
157 )
156
158
157 exec_files = List(Unicode(), config=True,
159 exec_files = List(Unicode(), config=True,
158 help="""List of files to run at IPython startup."""
160 help="""List of files to run at IPython startup."""
159 )
161 )
160 exec_PYTHONSTARTUP = Bool(True, config=True,
162 exec_PYTHONSTARTUP = Bool(True, config=True,
161 help="""Run the file referenced by the PYTHONSTARTUP environment
163 help="""Run the file referenced by the PYTHONSTARTUP environment
162 variable at IPython startup."""
164 variable at IPython startup."""
163 )
165 )
164 file_to_run = Unicode('', config=True,
166 file_to_run = Unicode('', config=True,
165 help="""A file to be run""")
167 help="""A file to be run""")
166
168
167 exec_lines = List(Unicode(), config=True,
169 exec_lines = List(Unicode(), config=True,
168 help="""lines of code to run at IPython startup."""
170 help="""lines of code to run at IPython startup."""
169 )
171 )
170 code_to_run = Unicode('', config=True,
172 code_to_run = Unicode('', config=True,
171 help="Execute the given command string."
173 help="Execute the given command string."
172 )
174 )
173 module_to_run = Unicode('', config=True,
175 module_to_run = Unicode('', config=True,
174 help="Run the module as a script."
176 help="Run the module as a script."
175 )
177 )
176 gui = CaselessStrEnum(gui_keys, config=True, allow_none=True,
178 gui = CaselessStrEnum(gui_keys, config=True, allow_none=True,
177 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
179 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
178 )
180 )
179 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
181 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
180 config=True,
182 config=True,
181 help="""Configure matplotlib for interactive use with
183 help="""Configure matplotlib for interactive use with
182 the default matplotlib backend."""
184 the default matplotlib backend."""
183 )
185 )
184 pylab = CaselessStrEnum(backend_keys, allow_none=True,
186 pylab = CaselessStrEnum(backend_keys, allow_none=True,
185 config=True,
187 config=True,
186 help="""Pre-load matplotlib and numpy for interactive use,
188 help="""Pre-load matplotlib and numpy for interactive use,
187 selecting a particular matplotlib backend and loop integration.
189 selecting a particular matplotlib backend and loop integration.
188 """
190 """
189 )
191 )
190 pylab_import_all = Bool(True, config=True,
192 pylab_import_all = Bool(True, config=True,
191 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
193 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
192 and an ``import *`` is done from numpy and pylab, when using pylab mode.
194 and an ``import *`` is done from numpy and pylab, when using pylab mode.
193
195
194 When False, pylab mode should not import any names into the user namespace.
196 When False, pylab mode should not import any names into the user namespace.
195 """
197 """
196 )
198 )
197 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
199 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
198 allow_none=True)
200 allow_none=True)
199
201
200 user_ns = Instance(dict, args=None, allow_none=True)
202 user_ns = Instance(dict, args=None, allow_none=True)
201 def _user_ns_changed(self, name, old, new):
203 def _user_ns_changed(self, name, old, new):
202 if self.shell is not None:
204 if self.shell is not None:
203 self.shell.user_ns = new
205 self.shell.user_ns = new
204 self.shell.init_user_ns()
206 self.shell.init_user_ns()
205
207
206 def init_path(self):
208 def init_path(self):
207 """Add current working directory, '', to sys.path"""
209 """Add current working directory, '', to sys.path"""
208 if sys.path[0] != '':
210 if sys.path[0] != '':
209 sys.path.insert(0, '')
211 sys.path.insert(0, '')
210
212
211 def init_shell(self):
213 def init_shell(self):
212 raise NotImplementedError("Override in subclasses")
214 raise NotImplementedError("Override in subclasses")
213
215
214 def init_gui_pylab(self):
216 def init_gui_pylab(self):
215 """Enable GUI event loop integration, taking pylab into account."""
217 """Enable GUI event loop integration, taking pylab into account."""
216 enable = False
218 enable = False
217 shell = self.shell
219 shell = self.shell
218 if self.pylab:
220 if self.pylab:
219 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
221 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
220 key = self.pylab
222 key = self.pylab
221 elif self.matplotlib:
223 elif self.matplotlib:
222 enable = shell.enable_matplotlib
224 enable = shell.enable_matplotlib
223 key = self.matplotlib
225 key = self.matplotlib
224 elif self.gui:
226 elif self.gui:
225 enable = shell.enable_gui
227 enable = shell.enable_gui
226 key = self.gui
228 key = self.gui
227
229
228 if not enable:
230 if not enable:
229 return
231 return
230
232
231 try:
233 try:
232 r = enable(key)
234 r = enable(key)
233 except ImportError:
235 except ImportError:
234 self.log.warn("Eventloop or matplotlib integration failed. Is matplotlib installed?")
236 self.log.warn("Eventloop or matplotlib integration failed. Is matplotlib installed?")
235 self.shell.showtraceback()
237 self.shell.showtraceback()
236 return
238 return
237 except Exception:
239 except Exception:
238 self.log.warn("GUI event loop or pylab initialization failed")
240 self.log.warn("GUI event loop or pylab initialization failed")
239 self.shell.showtraceback()
241 self.shell.showtraceback()
240 return
242 return
241
243
242 if isinstance(r, tuple):
244 if isinstance(r, tuple):
243 gui, backend = r[:2]
245 gui, backend = r[:2]
244 self.log.info("Enabling GUI event loop integration, "
246 self.log.info("Enabling GUI event loop integration, "
245 "eventloop=%s, matplotlib=%s", gui, backend)
247 "eventloop=%s, matplotlib=%s", gui, backend)
246 if key == "auto":
248 if key == "auto":
247 print("Using matplotlib backend: %s" % backend)
249 print("Using matplotlib backend: %s" % backend)
248 else:
250 else:
249 gui = r
251 gui = r
250 self.log.info("Enabling GUI event loop integration, "
252 self.log.info("Enabling GUI event loop integration, "
251 "eventloop=%s", gui)
253 "eventloop=%s", gui)
252
254
253 def init_extensions(self):
255 def init_extensions(self):
254 """Load all IPython extensions in IPythonApp.extensions.
256 """Load all IPython extensions in IPythonApp.extensions.
255
257
256 This uses the :meth:`ExtensionManager.load_extensions` to load all
258 This uses the :meth:`ExtensionManager.load_extensions` to load all
257 the extensions listed in ``self.extensions``.
259 the extensions listed in ``self.extensions``.
258 """
260 """
259 try:
261 try:
260 self.log.debug("Loading IPython extensions...")
262 self.log.debug("Loading IPython extensions...")
261 extensions = self.default_extensions + self.extensions
263 extensions = self.default_extensions + self.extensions
262 if self.extra_extension:
264 if self.extra_extension:
263 extensions.append(self.extra_extension)
265 extensions.append(self.extra_extension)
264 for ext in extensions:
266 for ext in extensions:
265 try:
267 try:
266 self.log.info("Loading IPython extension: %s" % ext)
268 self.log.info("Loading IPython extension: %s" % ext)
267 self.shell.extension_manager.load_extension(ext)
269 self.shell.extension_manager.load_extension(ext)
268 except:
270 except:
269 if self.reraise_ipython_extension_failures:
271 if self.reraise_ipython_extension_failures:
270 raise
272 raise
271 msg = ("Error in loading extension: {ext}\n"
273 msg = ("Error in loading extension: {ext}\n"
272 "Check your config files in {location}".format(
274 "Check your config files in {location}".format(
273 ext=ext,
275 ext=ext,
274 location=self.profile_dir.location
276 location=self.profile_dir.location
275 ))
277 ))
276 self.log.warn(msg, exc_info=True)
278 self.log.warn(msg, exc_info=True)
277 except:
279 except:
278 if self.reraise_ipython_extension_failures:
280 if self.reraise_ipython_extension_failures:
279 raise
281 raise
280 self.log.warn("Unknown error in loading extensions:", exc_info=True)
282 self.log.warn("Unknown error in loading extensions:", exc_info=True)
281
283
282 def init_code(self):
284 def init_code(self):
283 """run the pre-flight code, specified via exec_lines"""
285 """run the pre-flight code, specified via exec_lines"""
284 self._run_startup_files()
286 self._run_startup_files()
285 self._run_exec_lines()
287 self._run_exec_lines()
286 self._run_exec_files()
288 self._run_exec_files()
287
289
288 # Hide variables defined here from %who etc.
290 # Hide variables defined here from %who etc.
289 if self.hide_initial_ns:
291 if self.hide_initial_ns:
290 self.shell.user_ns_hidden.update(self.shell.user_ns)
292 self.shell.user_ns_hidden.update(self.shell.user_ns)
291
293
292 # command-line execution (ipython -i script.py, ipython -m module)
294 # command-line execution (ipython -i script.py, ipython -m module)
293 # should *not* be excluded from %whos
295 # should *not* be excluded from %whos
294 self._run_cmd_line_code()
296 self._run_cmd_line_code()
295 self._run_module()
297 self._run_module()
296
298
297 # flush output, so itwon't be attached to the first cell
299 # flush output, so itwon't be attached to the first cell
298 sys.stdout.flush()
300 sys.stdout.flush()
299 sys.stderr.flush()
301 sys.stderr.flush()
300
302
301 def _run_exec_lines(self):
303 def _run_exec_lines(self):
302 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
304 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
303 if not self.exec_lines:
305 if not self.exec_lines:
304 return
306 return
305 try:
307 try:
306 self.log.debug("Running code from IPythonApp.exec_lines...")
308 self.log.debug("Running code from IPythonApp.exec_lines...")
307 for line in self.exec_lines:
309 for line in self.exec_lines:
308 try:
310 try:
309 self.log.info("Running code in user namespace: %s" %
311 self.log.info("Running code in user namespace: %s" %
310 line)
312 line)
311 self.shell.run_cell(line, store_history=False)
313 self.shell.run_cell(line, store_history=False)
312 except:
314 except:
313 self.log.warn("Error in executing line in user "
315 self.log.warn("Error in executing line in user "
314 "namespace: %s" % line)
316 "namespace: %s" % line)
315 self.shell.showtraceback()
317 self.shell.showtraceback()
316 except:
318 except:
317 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
319 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
318 self.shell.showtraceback()
320 self.shell.showtraceback()
319
321
320 def _exec_file(self, fname, shell_futures=False):
322 def _exec_file(self, fname, shell_futures=False):
321 try:
323 try:
322 full_filename = filefind(fname, [u'.', self.ipython_dir])
324 full_filename = filefind(fname, [u'.', self.ipython_dir])
323 except IOError as e:
325 except IOError as e:
324 self.log.warn("File not found: %r"%fname)
326 self.log.warn("File not found: %r"%fname)
325 return
327 return
326 # Make sure that the running script gets a proper sys.argv as if it
328 # Make sure that the running script gets a proper sys.argv as if it
327 # were run from a system shell.
329 # were run from a system shell.
328 save_argv = sys.argv
330 save_argv = sys.argv
329 sys.argv = [full_filename] + self.extra_args[1:]
331 sys.argv = [full_filename] + self.extra_args[1:]
330 # protect sys.argv from potential unicode strings on Python 2:
332 # protect sys.argv from potential unicode strings on Python 2:
331 if not py3compat.PY3:
333 if not py3compat.PY3:
332 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
334 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
333 try:
335 try:
334 if os.path.isfile(full_filename):
336 if os.path.isfile(full_filename):
335 self.log.info("Running file in user namespace: %s" %
337 self.log.info("Running file in user namespace: %s" %
336 full_filename)
338 full_filename)
337 # Ensure that __file__ is always defined to match Python
339 # Ensure that __file__ is always defined to match Python
338 # behavior.
340 # behavior.
339 with preserve_keys(self.shell.user_ns, '__file__'):
341 with preserve_keys(self.shell.user_ns, '__file__'):
340 self.shell.user_ns['__file__'] = fname
342 self.shell.user_ns['__file__'] = fname
341 if full_filename.endswith('.ipy'):
343 if full_filename.endswith('.ipy'):
342 self.shell.safe_execfile_ipy(full_filename,
344 self.shell.safe_execfile_ipy(full_filename,
343 shell_futures=shell_futures)
345 shell_futures=shell_futures)
344 else:
346 else:
345 # default to python, even without extension
347 # default to python, even without extension
346 self.shell.safe_execfile(full_filename,
348 self.shell.safe_execfile(full_filename,
347 self.shell.user_ns,
349 self.shell.user_ns,
348 shell_futures=shell_futures,
350 shell_futures=shell_futures,
349 raise_exceptions=True)
351 raise_exceptions=True)
350 finally:
352 finally:
351 sys.argv = save_argv
353 sys.argv = save_argv
352
354
353 def _run_startup_files(self):
355 def _run_startup_files(self):
354 """Run files from profile startup directory"""
356 """Run files from profile startup directory"""
355 startup_dir = self.profile_dir.startup_dir
357 startup_dir = self.profile_dir.startup_dir
356 startup_files = []
358 startup_files = []
357
359
358 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
360 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
359 not (self.file_to_run or self.code_to_run or self.module_to_run):
361 not (self.file_to_run or self.code_to_run or self.module_to_run):
360 python_startup = os.environ['PYTHONSTARTUP']
362 python_startup = os.environ['PYTHONSTARTUP']
361 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
363 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
362 try:
364 try:
363 self._exec_file(python_startup)
365 self._exec_file(python_startup)
364 except:
366 except:
365 self.log.warn("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
367 self.log.warn("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
366 self.shell.showtraceback()
368 self.shell.showtraceback()
367 finally:
369 finally:
368 # Many PYTHONSTARTUP files set up the readline completions,
370 # Many PYTHONSTARTUP files set up the readline completions,
369 # but this is often at odds with IPython's own completions.
371 # but this is often at odds with IPython's own completions.
370 # Do not allow PYTHONSTARTUP to set up readline.
372 # Do not allow PYTHONSTARTUP to set up readline.
371 if self.shell.has_readline:
373 if self.shell.has_readline:
372 self.shell.set_readline_completer()
374 self.shell.set_readline_completer()
373
375
374 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
376 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
375 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
377 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
376 if not startup_files:
378 if not startup_files:
377 return
379 return
378
380
379 self.log.debug("Running startup files from %s...", startup_dir)
381 self.log.debug("Running startup files from %s...", startup_dir)
380 try:
382 try:
381 for fname in sorted(startup_files):
383 for fname in sorted(startup_files):
382 self._exec_file(fname)
384 self._exec_file(fname)
383 except:
385 except:
384 self.log.warn("Unknown error in handling startup files:")
386 self.log.warn("Unknown error in handling startup files:")
385 self.shell.showtraceback()
387 self.shell.showtraceback()
386
388
387 def _run_exec_files(self):
389 def _run_exec_files(self):
388 """Run files from IPythonApp.exec_files"""
390 """Run files from IPythonApp.exec_files"""
389 if not self.exec_files:
391 if not self.exec_files:
390 return
392 return
391
393
392 self.log.debug("Running files in IPythonApp.exec_files...")
394 self.log.debug("Running files in IPythonApp.exec_files...")
393 try:
395 try:
394 for fname in self.exec_files:
396 for fname in self.exec_files:
395 self._exec_file(fname)
397 self._exec_file(fname)
396 except:
398 except:
397 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
399 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
398 self.shell.showtraceback()
400 self.shell.showtraceback()
399
401
400 def _run_cmd_line_code(self):
402 def _run_cmd_line_code(self):
401 """Run code or file specified at the command-line"""
403 """Run code or file specified at the command-line"""
402 if self.code_to_run:
404 if self.code_to_run:
403 line = self.code_to_run
405 line = self.code_to_run
404 try:
406 try:
405 self.log.info("Running code given at command line (c=): %s" %
407 self.log.info("Running code given at command line (c=): %s" %
406 line)
408 line)
407 self.shell.run_cell(line, store_history=False)
409 self.shell.run_cell(line, store_history=False)
408 except:
410 except:
409 self.log.warn("Error in executing line in user namespace: %s" %
411 self.log.warn("Error in executing line in user namespace: %s" %
410 line)
412 line)
411 self.shell.showtraceback()
413 self.shell.showtraceback()
412
414
413 # Like Python itself, ignore the second if the first of these is present
415 # Like Python itself, ignore the second if the first of these is present
414 elif self.file_to_run:
416 elif self.file_to_run:
415 fname = self.file_to_run
417 fname = self.file_to_run
416 try:
418 try:
417 self._exec_file(fname, shell_futures=True)
419 self._exec_file(fname, shell_futures=True)
418 except:
420 except:
419 self.shell.showtraceback(tb_offset=4)
421 self.shell.showtraceback(tb_offset=4)
420 self.exit(1)
422 self.exit(1)
421
423
422 def _run_module(self):
424 def _run_module(self):
423 """Run module specified at the command-line."""
425 """Run module specified at the command-line."""
424 if self.module_to_run:
426 if self.module_to_run:
425 # Make sure that the module gets a proper sys.argv as if it were
427 # Make sure that the module gets a proper sys.argv as if it were
426 # run using `python -m`.
428 # run using `python -m`.
427 save_argv = sys.argv
429 save_argv = sys.argv
428 sys.argv = [sys.executable] + self.extra_args
430 sys.argv = [sys.executable] + self.extra_args
429 try:
431 try:
430 self.shell.safe_run_module(self.module_to_run,
432 self.shell.safe_run_module(self.module_to_run,
431 self.shell.user_ns)
433 self.shell.user_ns)
432 finally:
434 finally:
433 sys.argv = save_argv
435 sys.argv = save_argv
@@ -1,944 +1,943 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for the key interactiveshell module.
2 """Tests for the key interactiveshell module.
3
3
4 Historically the main classes in interactiveshell have been under-tested. This
4 Historically the main classes in interactiveshell have been under-tested. This
5 module should grow as many single-method tests as possible to trap many of the
5 module should grow as many single-method tests as possible to trap many of the
6 recurring bugs we seem to encounter with high-level interaction.
6 recurring bugs we seem to encounter with high-level interaction.
7 """
7 """
8
8
9 # Copyright (c) IPython Development Team.
9 # Copyright (c) IPython Development Team.
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11
11
12 import ast
12 import ast
13 import os
13 import os
14 import signal
14 import signal
15 import shutil
15 import shutil
16 import sys
16 import sys
17 import tempfile
17 import tempfile
18 import unittest
18 import unittest
19 try:
19 try:
20 from unittest import mock
20 from unittest import mock
21 except ImportError:
21 except ImportError:
22 import mock
22 import mock
23 from os.path import join
23 from os.path import join
24
24
25 import nose.tools as nt
25 import nose.tools as nt
26
26
27 from IPython.core.error import InputRejected
27 from IPython.core.error import InputRejected
28 from IPython.core.inputtransformer import InputTransformer
28 from IPython.core.inputtransformer import InputTransformer
29 from IPython.testing.decorators import (
29 from IPython.testing.decorators import (
30 skipif, skip_win32, onlyif_unicode_paths, onlyif_cmds_exist,
30 skipif, skip_win32, onlyif_unicode_paths, onlyif_cmds_exist,
31 )
31 )
32 from IPython.testing import tools as tt
32 from IPython.testing import tools as tt
33 from IPython.utils import io
34 from IPython.utils.process import find_cmd
33 from IPython.utils.process import find_cmd
35 from IPython.utils import py3compat
34 from IPython.utils import py3compat
36 from IPython.utils.py3compat import unicode_type, PY3
35 from IPython.utils.py3compat import unicode_type, PY3
37
36
38 if PY3:
37 if PY3:
39 from io import StringIO
38 from io import StringIO
40 else:
39 else:
41 from StringIO import StringIO
40 from StringIO import StringIO
42
41
43 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
44 # Globals
43 # Globals
45 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
46 # This is used by every single test, no point repeating it ad nauseam
45 # This is used by every single test, no point repeating it ad nauseam
47 ip = get_ipython()
46 ip = get_ipython()
48
47
49 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
50 # Tests
49 # Tests
51 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
52
51
53 class DerivedInterrupt(KeyboardInterrupt):
52 class DerivedInterrupt(KeyboardInterrupt):
54 pass
53 pass
55
54
56 class InteractiveShellTestCase(unittest.TestCase):
55 class InteractiveShellTestCase(unittest.TestCase):
57 def test_naked_string_cells(self):
56 def test_naked_string_cells(self):
58 """Test that cells with only naked strings are fully executed"""
57 """Test that cells with only naked strings are fully executed"""
59 # First, single-line inputs
58 # First, single-line inputs
60 ip.run_cell('"a"\n')
59 ip.run_cell('"a"\n')
61 self.assertEqual(ip.user_ns['_'], 'a')
60 self.assertEqual(ip.user_ns['_'], 'a')
62 # And also multi-line cells
61 # And also multi-line cells
63 ip.run_cell('"""a\nb"""\n')
62 ip.run_cell('"""a\nb"""\n')
64 self.assertEqual(ip.user_ns['_'], 'a\nb')
63 self.assertEqual(ip.user_ns['_'], 'a\nb')
65
64
66 def test_run_empty_cell(self):
65 def test_run_empty_cell(self):
67 """Just make sure we don't get a horrible error with a blank
66 """Just make sure we don't get a horrible error with a blank
68 cell of input. Yes, I did overlook that."""
67 cell of input. Yes, I did overlook that."""
69 old_xc = ip.execution_count
68 old_xc = ip.execution_count
70 res = ip.run_cell('')
69 res = ip.run_cell('')
71 self.assertEqual(ip.execution_count, old_xc)
70 self.assertEqual(ip.execution_count, old_xc)
72 self.assertEqual(res.execution_count, None)
71 self.assertEqual(res.execution_count, None)
73
72
74 def test_run_cell_multiline(self):
73 def test_run_cell_multiline(self):
75 """Multi-block, multi-line cells must execute correctly.
74 """Multi-block, multi-line cells must execute correctly.
76 """
75 """
77 src = '\n'.join(["x=1",
76 src = '\n'.join(["x=1",
78 "y=2",
77 "y=2",
79 "if 1:",
78 "if 1:",
80 " x += 1",
79 " x += 1",
81 " y += 1",])
80 " y += 1",])
82 res = ip.run_cell(src)
81 res = ip.run_cell(src)
83 self.assertEqual(ip.user_ns['x'], 2)
82 self.assertEqual(ip.user_ns['x'], 2)
84 self.assertEqual(ip.user_ns['y'], 3)
83 self.assertEqual(ip.user_ns['y'], 3)
85 self.assertEqual(res.success, True)
84 self.assertEqual(res.success, True)
86 self.assertEqual(res.result, None)
85 self.assertEqual(res.result, None)
87
86
88 def test_multiline_string_cells(self):
87 def test_multiline_string_cells(self):
89 "Code sprinkled with multiline strings should execute (GH-306)"
88 "Code sprinkled with multiline strings should execute (GH-306)"
90 ip.run_cell('tmp=0')
89 ip.run_cell('tmp=0')
91 self.assertEqual(ip.user_ns['tmp'], 0)
90 self.assertEqual(ip.user_ns['tmp'], 0)
92 res = ip.run_cell('tmp=1;"""a\nb"""\n')
91 res = ip.run_cell('tmp=1;"""a\nb"""\n')
93 self.assertEqual(ip.user_ns['tmp'], 1)
92 self.assertEqual(ip.user_ns['tmp'], 1)
94 self.assertEqual(res.success, True)
93 self.assertEqual(res.success, True)
95 self.assertEqual(res.result, "a\nb")
94 self.assertEqual(res.result, "a\nb")
96
95
97 def test_dont_cache_with_semicolon(self):
96 def test_dont_cache_with_semicolon(self):
98 "Ending a line with semicolon should not cache the returned object (GH-307)"
97 "Ending a line with semicolon should not cache the returned object (GH-307)"
99 oldlen = len(ip.user_ns['Out'])
98 oldlen = len(ip.user_ns['Out'])
100 for cell in ['1;', '1;1;']:
99 for cell in ['1;', '1;1;']:
101 res = ip.run_cell(cell, store_history=True)
100 res = ip.run_cell(cell, store_history=True)
102 newlen = len(ip.user_ns['Out'])
101 newlen = len(ip.user_ns['Out'])
103 self.assertEqual(oldlen, newlen)
102 self.assertEqual(oldlen, newlen)
104 self.assertIsNone(res.result)
103 self.assertIsNone(res.result)
105 i = 0
104 i = 0
106 #also test the default caching behavior
105 #also test the default caching behavior
107 for cell in ['1', '1;1']:
106 for cell in ['1', '1;1']:
108 ip.run_cell(cell, store_history=True)
107 ip.run_cell(cell, store_history=True)
109 newlen = len(ip.user_ns['Out'])
108 newlen = len(ip.user_ns['Out'])
110 i += 1
109 i += 1
111 self.assertEqual(oldlen+i, newlen)
110 self.assertEqual(oldlen+i, newlen)
112
111
113 def test_syntax_error(self):
112 def test_syntax_error(self):
114 res = ip.run_cell("raise = 3")
113 res = ip.run_cell("raise = 3")
115 self.assertIsInstance(res.error_before_exec, SyntaxError)
114 self.assertIsInstance(res.error_before_exec, SyntaxError)
116
115
117 def test_In_variable(self):
116 def test_In_variable(self):
118 "Verify that In variable grows with user input (GH-284)"
117 "Verify that In variable grows with user input (GH-284)"
119 oldlen = len(ip.user_ns['In'])
118 oldlen = len(ip.user_ns['In'])
120 ip.run_cell('1;', store_history=True)
119 ip.run_cell('1;', store_history=True)
121 newlen = len(ip.user_ns['In'])
120 newlen = len(ip.user_ns['In'])
122 self.assertEqual(oldlen+1, newlen)
121 self.assertEqual(oldlen+1, newlen)
123 self.assertEqual(ip.user_ns['In'][-1],'1;')
122 self.assertEqual(ip.user_ns['In'][-1],'1;')
124
123
125 def test_magic_names_in_string(self):
124 def test_magic_names_in_string(self):
126 ip.run_cell('a = """\n%exit\n"""')
125 ip.run_cell('a = """\n%exit\n"""')
127 self.assertEqual(ip.user_ns['a'], '\n%exit\n')
126 self.assertEqual(ip.user_ns['a'], '\n%exit\n')
128
127
129 def test_trailing_newline(self):
128 def test_trailing_newline(self):
130 """test that running !(command) does not raise a SyntaxError"""
129 """test that running !(command) does not raise a SyntaxError"""
131 ip.run_cell('!(true)\n', False)
130 ip.run_cell('!(true)\n', False)
132 ip.run_cell('!(true)\n\n\n', False)
131 ip.run_cell('!(true)\n\n\n', False)
133
132
134 def test_gh_597(self):
133 def test_gh_597(self):
135 """Pretty-printing lists of objects with non-ascii reprs may cause
134 """Pretty-printing lists of objects with non-ascii reprs may cause
136 problems."""
135 problems."""
137 class Spam(object):
136 class Spam(object):
138 def __repr__(self):
137 def __repr__(self):
139 return "\xe9"*50
138 return "\xe9"*50
140 import IPython.core.formatters
139 import IPython.core.formatters
141 f = IPython.core.formatters.PlainTextFormatter()
140 f = IPython.core.formatters.PlainTextFormatter()
142 f([Spam(),Spam()])
141 f([Spam(),Spam()])
143
142
144
143
145 def test_future_flags(self):
144 def test_future_flags(self):
146 """Check that future flags are used for parsing code (gh-777)"""
145 """Check that future flags are used for parsing code (gh-777)"""
147 ip.run_cell('from __future__ import print_function')
146 ip.run_cell('from __future__ import print_function')
148 try:
147 try:
149 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
148 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
150 assert 'prfunc_return_val' in ip.user_ns
149 assert 'prfunc_return_val' in ip.user_ns
151 finally:
150 finally:
152 # Reset compiler flags so we don't mess up other tests.
151 # Reset compiler flags so we don't mess up other tests.
153 ip.compile.reset_compiler_flags()
152 ip.compile.reset_compiler_flags()
154
153
155 def test_future_unicode(self):
154 def test_future_unicode(self):
156 """Check that unicode_literals is imported from __future__ (gh #786)"""
155 """Check that unicode_literals is imported from __future__ (gh #786)"""
157 try:
156 try:
158 ip.run_cell(u'byte_str = "a"')
157 ip.run_cell(u'byte_str = "a"')
159 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
158 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
160 ip.run_cell('from __future__ import unicode_literals')
159 ip.run_cell('from __future__ import unicode_literals')
161 ip.run_cell(u'unicode_str = "a"')
160 ip.run_cell(u'unicode_str = "a"')
162 assert isinstance(ip.user_ns['unicode_str'], unicode_type) # strings literals are now unicode
161 assert isinstance(ip.user_ns['unicode_str'], unicode_type) # strings literals are now unicode
163 finally:
162 finally:
164 # Reset compiler flags so we don't mess up other tests.
163 # Reset compiler flags so we don't mess up other tests.
165 ip.compile.reset_compiler_flags()
164 ip.compile.reset_compiler_flags()
166
165
167 def test_can_pickle(self):
166 def test_can_pickle(self):
168 "Can we pickle objects defined interactively (GH-29)"
167 "Can we pickle objects defined interactively (GH-29)"
169 ip = get_ipython()
168 ip = get_ipython()
170 ip.reset()
169 ip.reset()
171 ip.run_cell(("class Mylist(list):\n"
170 ip.run_cell(("class Mylist(list):\n"
172 " def __init__(self,x=[]):\n"
171 " def __init__(self,x=[]):\n"
173 " list.__init__(self,x)"))
172 " list.__init__(self,x)"))
174 ip.run_cell("w=Mylist([1,2,3])")
173 ip.run_cell("w=Mylist([1,2,3])")
175
174
176 from pickle import dumps
175 from pickle import dumps
177
176
178 # We need to swap in our main module - this is only necessary
177 # We need to swap in our main module - this is only necessary
179 # inside the test framework, because IPython puts the interactive module
178 # inside the test framework, because IPython puts the interactive module
180 # in place (but the test framework undoes this).
179 # in place (but the test framework undoes this).
181 _main = sys.modules['__main__']
180 _main = sys.modules['__main__']
182 sys.modules['__main__'] = ip.user_module
181 sys.modules['__main__'] = ip.user_module
183 try:
182 try:
184 res = dumps(ip.user_ns["w"])
183 res = dumps(ip.user_ns["w"])
185 finally:
184 finally:
186 sys.modules['__main__'] = _main
185 sys.modules['__main__'] = _main
187 self.assertTrue(isinstance(res, bytes))
186 self.assertTrue(isinstance(res, bytes))
188
187
189 def test_global_ns(self):
188 def test_global_ns(self):
190 "Code in functions must be able to access variables outside them."
189 "Code in functions must be able to access variables outside them."
191 ip = get_ipython()
190 ip = get_ipython()
192 ip.run_cell("a = 10")
191 ip.run_cell("a = 10")
193 ip.run_cell(("def f(x):\n"
192 ip.run_cell(("def f(x):\n"
194 " return x + a"))
193 " return x + a"))
195 ip.run_cell("b = f(12)")
194 ip.run_cell("b = f(12)")
196 self.assertEqual(ip.user_ns["b"], 22)
195 self.assertEqual(ip.user_ns["b"], 22)
197
196
198 def test_bad_custom_tb(self):
197 def test_bad_custom_tb(self):
199 """Check that InteractiveShell is protected from bad custom exception handlers"""
198 """Check that InteractiveShell is protected from bad custom exception handlers"""
200 from IPython.utils import io
199 from IPython.utils import io
201 save_stderr = io.stderr
200 save_stderr = io.stderr
202 try:
201 try:
203 # capture stderr
202 # capture stderr
204 io.stderr = StringIO()
203 io.stderr = StringIO()
205 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
204 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
206 self.assertEqual(ip.custom_exceptions, (IOError,))
205 self.assertEqual(ip.custom_exceptions, (IOError,))
207 ip.run_cell(u'raise IOError("foo")')
206 ip.run_cell(u'raise IOError("foo")')
208 self.assertEqual(ip.custom_exceptions, ())
207 self.assertEqual(ip.custom_exceptions, ())
209 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
208 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
210 finally:
209 finally:
211 io.stderr = save_stderr
210 io.stderr = save_stderr
212
211
213 def test_bad_custom_tb_return(self):
212 def test_bad_custom_tb_return(self):
214 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
213 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
215 from IPython.utils import io
214 from IPython.utils import io
216 save_stderr = io.stderr
215 save_stderr = io.stderr
217 try:
216 try:
218 # capture stderr
217 # capture stderr
219 io.stderr = StringIO()
218 io.stderr = StringIO()
220 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
219 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
221 self.assertEqual(ip.custom_exceptions, (NameError,))
220 self.assertEqual(ip.custom_exceptions, (NameError,))
222 ip.run_cell(u'a=abracadabra')
221 ip.run_cell(u'a=abracadabra')
223 self.assertEqual(ip.custom_exceptions, ())
222 self.assertEqual(ip.custom_exceptions, ())
224 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
223 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
225 finally:
224 finally:
226 io.stderr = save_stderr
225 io.stderr = save_stderr
227
226
228 def test_drop_by_id(self):
227 def test_drop_by_id(self):
229 myvars = {"a":object(), "b":object(), "c": object()}
228 myvars = {"a":object(), "b":object(), "c": object()}
230 ip.push(myvars, interactive=False)
229 ip.push(myvars, interactive=False)
231 for name in myvars:
230 for name in myvars:
232 assert name in ip.user_ns, name
231 assert name in ip.user_ns, name
233 assert name in ip.user_ns_hidden, name
232 assert name in ip.user_ns_hidden, name
234 ip.user_ns['b'] = 12
233 ip.user_ns['b'] = 12
235 ip.drop_by_id(myvars)
234 ip.drop_by_id(myvars)
236 for name in ["a", "c"]:
235 for name in ["a", "c"]:
237 assert name not in ip.user_ns, name
236 assert name not in ip.user_ns, name
238 assert name not in ip.user_ns_hidden, name
237 assert name not in ip.user_ns_hidden, name
239 assert ip.user_ns['b'] == 12
238 assert ip.user_ns['b'] == 12
240 ip.reset()
239 ip.reset()
241
240
242 def test_var_expand(self):
241 def test_var_expand(self):
243 ip.user_ns['f'] = u'Ca\xf1o'
242 ip.user_ns['f'] = u'Ca\xf1o'
244 self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o')
243 self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o')
245 self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o')
244 self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o')
246 self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1')
245 self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1')
247 self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2')
246 self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2')
248
247
249 ip.user_ns['f'] = b'Ca\xc3\xb1o'
248 ip.user_ns['f'] = b'Ca\xc3\xb1o'
250 # This should not raise any exception:
249 # This should not raise any exception:
251 ip.var_expand(u'echo $f')
250 ip.var_expand(u'echo $f')
252
251
253 def test_var_expand_local(self):
252 def test_var_expand_local(self):
254 """Test local variable expansion in !system and %magic calls"""
253 """Test local variable expansion in !system and %magic calls"""
255 # !system
254 # !system
256 ip.run_cell('def test():\n'
255 ip.run_cell('def test():\n'
257 ' lvar = "ttt"\n'
256 ' lvar = "ttt"\n'
258 ' ret = !echo {lvar}\n'
257 ' ret = !echo {lvar}\n'
259 ' return ret[0]\n')
258 ' return ret[0]\n')
260 res = ip.user_ns['test']()
259 res = ip.user_ns['test']()
261 nt.assert_in('ttt', res)
260 nt.assert_in('ttt', res)
262
261
263 # %magic
262 # %magic
264 ip.run_cell('def makemacro():\n'
263 ip.run_cell('def makemacro():\n'
265 ' macroname = "macro_var_expand_locals"\n'
264 ' macroname = "macro_var_expand_locals"\n'
266 ' %macro {macroname} codestr\n')
265 ' %macro {macroname} codestr\n')
267 ip.user_ns['codestr'] = "str(12)"
266 ip.user_ns['codestr'] = "str(12)"
268 ip.run_cell('makemacro()')
267 ip.run_cell('makemacro()')
269 nt.assert_in('macro_var_expand_locals', ip.user_ns)
268 nt.assert_in('macro_var_expand_locals', ip.user_ns)
270
269
271 def test_var_expand_self(self):
270 def test_var_expand_self(self):
272 """Test variable expansion with the name 'self', which was failing.
271 """Test variable expansion with the name 'self', which was failing.
273
272
274 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
273 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
275 """
274 """
276 ip.run_cell('class cTest:\n'
275 ip.run_cell('class cTest:\n'
277 ' classvar="see me"\n'
276 ' classvar="see me"\n'
278 ' def test(self):\n'
277 ' def test(self):\n'
279 ' res = !echo Variable: {self.classvar}\n'
278 ' res = !echo Variable: {self.classvar}\n'
280 ' return res[0]\n')
279 ' return res[0]\n')
281 nt.assert_in('see me', ip.user_ns['cTest']().test())
280 nt.assert_in('see me', ip.user_ns['cTest']().test())
282
281
283 def test_bad_var_expand(self):
282 def test_bad_var_expand(self):
284 """var_expand on invalid formats shouldn't raise"""
283 """var_expand on invalid formats shouldn't raise"""
285 # SyntaxError
284 # SyntaxError
286 self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}")
285 self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}")
287 # NameError
286 # NameError
288 self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}")
287 self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}")
289 # ZeroDivisionError
288 # ZeroDivisionError
290 self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}")
289 self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}")
291
290
292 def test_silent_postexec(self):
291 def test_silent_postexec(self):
293 """run_cell(silent=True) doesn't invoke pre/post_run_cell callbacks"""
292 """run_cell(silent=True) doesn't invoke pre/post_run_cell callbacks"""
294 pre_explicit = mock.Mock()
293 pre_explicit = mock.Mock()
295 pre_always = mock.Mock()
294 pre_always = mock.Mock()
296 post_explicit = mock.Mock()
295 post_explicit = mock.Mock()
297 post_always = mock.Mock()
296 post_always = mock.Mock()
298
297
299 ip.events.register('pre_run_cell', pre_explicit)
298 ip.events.register('pre_run_cell', pre_explicit)
300 ip.events.register('pre_execute', pre_always)
299 ip.events.register('pre_execute', pre_always)
301 ip.events.register('post_run_cell', post_explicit)
300 ip.events.register('post_run_cell', post_explicit)
302 ip.events.register('post_execute', post_always)
301 ip.events.register('post_execute', post_always)
303
302
304 try:
303 try:
305 ip.run_cell("1", silent=True)
304 ip.run_cell("1", silent=True)
306 assert pre_always.called
305 assert pre_always.called
307 assert not pre_explicit.called
306 assert not pre_explicit.called
308 assert post_always.called
307 assert post_always.called
309 assert not post_explicit.called
308 assert not post_explicit.called
310 # double-check that non-silent exec did what we expected
309 # double-check that non-silent exec did what we expected
311 # silent to avoid
310 # silent to avoid
312 ip.run_cell("1")
311 ip.run_cell("1")
313 assert pre_explicit.called
312 assert pre_explicit.called
314 assert post_explicit.called
313 assert post_explicit.called
315 finally:
314 finally:
316 # remove post-exec
315 # remove post-exec
317 ip.events.unregister('pre_run_cell', pre_explicit)
316 ip.events.unregister('pre_run_cell', pre_explicit)
318 ip.events.unregister('pre_execute', pre_always)
317 ip.events.unregister('pre_execute', pre_always)
319 ip.events.unregister('post_run_cell', post_explicit)
318 ip.events.unregister('post_run_cell', post_explicit)
320 ip.events.unregister('post_execute', post_always)
319 ip.events.unregister('post_execute', post_always)
321
320
322 def test_silent_noadvance(self):
321 def test_silent_noadvance(self):
323 """run_cell(silent=True) doesn't advance execution_count"""
322 """run_cell(silent=True) doesn't advance execution_count"""
324 ec = ip.execution_count
323 ec = ip.execution_count
325 # silent should force store_history=False
324 # silent should force store_history=False
326 ip.run_cell("1", store_history=True, silent=True)
325 ip.run_cell("1", store_history=True, silent=True)
327
326
328 self.assertEqual(ec, ip.execution_count)
327 self.assertEqual(ec, ip.execution_count)
329 # double-check that non-silent exec did what we expected
328 # double-check that non-silent exec did what we expected
330 # silent to avoid
329 # silent to avoid
331 ip.run_cell("1", store_history=True)
330 ip.run_cell("1", store_history=True)
332 self.assertEqual(ec+1, ip.execution_count)
331 self.assertEqual(ec+1, ip.execution_count)
333
332
334 def test_silent_nodisplayhook(self):
333 def test_silent_nodisplayhook(self):
335 """run_cell(silent=True) doesn't trigger displayhook"""
334 """run_cell(silent=True) doesn't trigger displayhook"""
336 d = dict(called=False)
335 d = dict(called=False)
337
336
338 trap = ip.display_trap
337 trap = ip.display_trap
339 save_hook = trap.hook
338 save_hook = trap.hook
340
339
341 def failing_hook(*args, **kwargs):
340 def failing_hook(*args, **kwargs):
342 d['called'] = True
341 d['called'] = True
343
342
344 try:
343 try:
345 trap.hook = failing_hook
344 trap.hook = failing_hook
346 res = ip.run_cell("1", silent=True)
345 res = ip.run_cell("1", silent=True)
347 self.assertFalse(d['called'])
346 self.assertFalse(d['called'])
348 self.assertIsNone(res.result)
347 self.assertIsNone(res.result)
349 # double-check that non-silent exec did what we expected
348 # double-check that non-silent exec did what we expected
350 # silent to avoid
349 # silent to avoid
351 ip.run_cell("1")
350 ip.run_cell("1")
352 self.assertTrue(d['called'])
351 self.assertTrue(d['called'])
353 finally:
352 finally:
354 trap.hook = save_hook
353 trap.hook = save_hook
355
354
356 @skipif(sys.version_info[0] >= 3, "softspace removed in py3")
355 @skipif(sys.version_info[0] >= 3, "softspace removed in py3")
357 def test_print_softspace(self):
356 def test_print_softspace(self):
358 """Verify that softspace is handled correctly when executing multiple
357 """Verify that softspace is handled correctly when executing multiple
359 statements.
358 statements.
360
359
361 In [1]: print 1; print 2
360 In [1]: print 1; print 2
362 1
361 1
363 2
362 2
364
363
365 In [2]: print 1,; print 2
364 In [2]: print 1,; print 2
366 1 2
365 1 2
367 """
366 """
368
367
369 def test_ofind_line_magic(self):
368 def test_ofind_line_magic(self):
370 from IPython.core.magic import register_line_magic
369 from IPython.core.magic import register_line_magic
371
370
372 @register_line_magic
371 @register_line_magic
373 def lmagic(line):
372 def lmagic(line):
374 "A line magic"
373 "A line magic"
375
374
376 # Get info on line magic
375 # Get info on line magic
377 lfind = ip._ofind('lmagic')
376 lfind = ip._ofind('lmagic')
378 info = dict(found=True, isalias=False, ismagic=True,
377 info = dict(found=True, isalias=False, ismagic=True,
379 namespace = 'IPython internal', obj= lmagic.__wrapped__,
378 namespace = 'IPython internal', obj= lmagic.__wrapped__,
380 parent = None)
379 parent = None)
381 nt.assert_equal(lfind, info)
380 nt.assert_equal(lfind, info)
382
381
383 def test_ofind_cell_magic(self):
382 def test_ofind_cell_magic(self):
384 from IPython.core.magic import register_cell_magic
383 from IPython.core.magic import register_cell_magic
385
384
386 @register_cell_magic
385 @register_cell_magic
387 def cmagic(line, cell):
386 def cmagic(line, cell):
388 "A cell magic"
387 "A cell magic"
389
388
390 # Get info on cell magic
389 # Get info on cell magic
391 find = ip._ofind('cmagic')
390 find = ip._ofind('cmagic')
392 info = dict(found=True, isalias=False, ismagic=True,
391 info = dict(found=True, isalias=False, ismagic=True,
393 namespace = 'IPython internal', obj= cmagic.__wrapped__,
392 namespace = 'IPython internal', obj= cmagic.__wrapped__,
394 parent = None)
393 parent = None)
395 nt.assert_equal(find, info)
394 nt.assert_equal(find, info)
396
395
397 def test_ofind_property_with_error(self):
396 def test_ofind_property_with_error(self):
398 class A(object):
397 class A(object):
399 @property
398 @property
400 def foo(self):
399 def foo(self):
401 raise NotImplementedError()
400 raise NotImplementedError()
402 a = A()
401 a = A()
403
402
404 found = ip._ofind('a.foo', [('locals', locals())])
403 found = ip._ofind('a.foo', [('locals', locals())])
405 info = dict(found=True, isalias=False, ismagic=False,
404 info = dict(found=True, isalias=False, ismagic=False,
406 namespace='locals', obj=A.foo, parent=a)
405 namespace='locals', obj=A.foo, parent=a)
407 nt.assert_equal(found, info)
406 nt.assert_equal(found, info)
408
407
409 def test_ofind_multiple_attribute_lookups(self):
408 def test_ofind_multiple_attribute_lookups(self):
410 class A(object):
409 class A(object):
411 @property
410 @property
412 def foo(self):
411 def foo(self):
413 raise NotImplementedError()
412 raise NotImplementedError()
414
413
415 a = A()
414 a = A()
416 a.a = A()
415 a.a = A()
417 a.a.a = A()
416 a.a.a = A()
418
417
419 found = ip._ofind('a.a.a.foo', [('locals', locals())])
418 found = ip._ofind('a.a.a.foo', [('locals', locals())])
420 info = dict(found=True, isalias=False, ismagic=False,
419 info = dict(found=True, isalias=False, ismagic=False,
421 namespace='locals', obj=A.foo, parent=a.a.a)
420 namespace='locals', obj=A.foo, parent=a.a.a)
422 nt.assert_equal(found, info)
421 nt.assert_equal(found, info)
423
422
424 def test_ofind_slotted_attributes(self):
423 def test_ofind_slotted_attributes(self):
425 class A(object):
424 class A(object):
426 __slots__ = ['foo']
425 __slots__ = ['foo']
427 def __init__(self):
426 def __init__(self):
428 self.foo = 'bar'
427 self.foo = 'bar'
429
428
430 a = A()
429 a = A()
431 found = ip._ofind('a.foo', [('locals', locals())])
430 found = ip._ofind('a.foo', [('locals', locals())])
432 info = dict(found=True, isalias=False, ismagic=False,
431 info = dict(found=True, isalias=False, ismagic=False,
433 namespace='locals', obj=a.foo, parent=a)
432 namespace='locals', obj=a.foo, parent=a)
434 nt.assert_equal(found, info)
433 nt.assert_equal(found, info)
435
434
436 found = ip._ofind('a.bar', [('locals', locals())])
435 found = ip._ofind('a.bar', [('locals', locals())])
437 info = dict(found=False, isalias=False, ismagic=False,
436 info = dict(found=False, isalias=False, ismagic=False,
438 namespace=None, obj=None, parent=a)
437 namespace=None, obj=None, parent=a)
439 nt.assert_equal(found, info)
438 nt.assert_equal(found, info)
440
439
441 def test_ofind_prefers_property_to_instance_level_attribute(self):
440 def test_ofind_prefers_property_to_instance_level_attribute(self):
442 class A(object):
441 class A(object):
443 @property
442 @property
444 def foo(self):
443 def foo(self):
445 return 'bar'
444 return 'bar'
446 a = A()
445 a = A()
447 a.__dict__['foo'] = 'baz'
446 a.__dict__['foo'] = 'baz'
448 nt.assert_equal(a.foo, 'bar')
447 nt.assert_equal(a.foo, 'bar')
449 found = ip._ofind('a.foo', [('locals', locals())])
448 found = ip._ofind('a.foo', [('locals', locals())])
450 nt.assert_is(found['obj'], A.foo)
449 nt.assert_is(found['obj'], A.foo)
451
450
452 def test_custom_exception(self):
451 def test_custom_exception(self):
453 called = []
452 called = []
454 def my_handler(shell, etype, value, tb, tb_offset=None):
453 def my_handler(shell, etype, value, tb, tb_offset=None):
455 called.append(etype)
454 called.append(etype)
456 shell.showtraceback((etype, value, tb), tb_offset=tb_offset)
455 shell.showtraceback((etype, value, tb), tb_offset=tb_offset)
457
456
458 ip.set_custom_exc((ValueError,), my_handler)
457 ip.set_custom_exc((ValueError,), my_handler)
459 try:
458 try:
460 res = ip.run_cell("raise ValueError('test')")
459 res = ip.run_cell("raise ValueError('test')")
461 # Check that this was called, and only once.
460 # Check that this was called, and only once.
462 self.assertEqual(called, [ValueError])
461 self.assertEqual(called, [ValueError])
463 # Check that the error is on the result object
462 # Check that the error is on the result object
464 self.assertIsInstance(res.error_in_exec, ValueError)
463 self.assertIsInstance(res.error_in_exec, ValueError)
465 finally:
464 finally:
466 # Reset the custom exception hook
465 # Reset the custom exception hook
467 ip.set_custom_exc((), None)
466 ip.set_custom_exc((), None)
468
467
469 @skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
468 @skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
470 def test_future_environment(self):
469 def test_future_environment(self):
471 "Can we run code with & without the shell's __future__ imports?"
470 "Can we run code with & without the shell's __future__ imports?"
472 ip.run_cell("from __future__ import division")
471 ip.run_cell("from __future__ import division")
473 ip.run_cell("a = 1/2", shell_futures=True)
472 ip.run_cell("a = 1/2", shell_futures=True)
474 self.assertEqual(ip.user_ns['a'], 0.5)
473 self.assertEqual(ip.user_ns['a'], 0.5)
475 ip.run_cell("b = 1/2", shell_futures=False)
474 ip.run_cell("b = 1/2", shell_futures=False)
476 self.assertEqual(ip.user_ns['b'], 0)
475 self.assertEqual(ip.user_ns['b'], 0)
477
476
478 ip.compile.reset_compiler_flags()
477 ip.compile.reset_compiler_flags()
479 # This shouldn't leak to the shell's compiler
478 # This shouldn't leak to the shell's compiler
480 ip.run_cell("from __future__ import division \nc=1/2", shell_futures=False)
479 ip.run_cell("from __future__ import division \nc=1/2", shell_futures=False)
481 self.assertEqual(ip.user_ns['c'], 0.5)
480 self.assertEqual(ip.user_ns['c'], 0.5)
482 ip.run_cell("d = 1/2", shell_futures=True)
481 ip.run_cell("d = 1/2", shell_futures=True)
483 self.assertEqual(ip.user_ns['d'], 0)
482 self.assertEqual(ip.user_ns['d'], 0)
484
483
485 def test_mktempfile(self):
484 def test_mktempfile(self):
486 filename = ip.mktempfile()
485 filename = ip.mktempfile()
487 # Check that we can open the file again on Windows
486 # Check that we can open the file again on Windows
488 with open(filename, 'w') as f:
487 with open(filename, 'w') as f:
489 f.write('abc')
488 f.write('abc')
490
489
491 filename = ip.mktempfile(data='blah')
490 filename = ip.mktempfile(data='blah')
492 with open(filename, 'r') as f:
491 with open(filename, 'r') as f:
493 self.assertEqual(f.read(), 'blah')
492 self.assertEqual(f.read(), 'blah')
494
493
495 def test_new_main_mod(self):
494 def test_new_main_mod(self):
496 # Smoketest to check that this accepts a unicode module name
495 # Smoketest to check that this accepts a unicode module name
497 name = u'jiefmw'
496 name = u'jiefmw'
498 mod = ip.new_main_mod(u'%s.py' % name, name)
497 mod = ip.new_main_mod(u'%s.py' % name, name)
499 self.assertEqual(mod.__name__, name)
498 self.assertEqual(mod.__name__, name)
500
499
501 def test_get_exception_only(self):
500 def test_get_exception_only(self):
502 try:
501 try:
503 raise KeyboardInterrupt
502 raise KeyboardInterrupt
504 except KeyboardInterrupt:
503 except KeyboardInterrupt:
505 msg = ip.get_exception_only()
504 msg = ip.get_exception_only()
506 self.assertEqual(msg, 'KeyboardInterrupt\n')
505 self.assertEqual(msg, 'KeyboardInterrupt\n')
507
506
508 try:
507 try:
509 raise DerivedInterrupt("foo")
508 raise DerivedInterrupt("foo")
510 except KeyboardInterrupt:
509 except KeyboardInterrupt:
511 msg = ip.get_exception_only()
510 msg = ip.get_exception_only()
512 if sys.version_info[0] <= 2:
511 if sys.version_info[0] <= 2:
513 self.assertEqual(msg, 'DerivedInterrupt: foo\n')
512 self.assertEqual(msg, 'DerivedInterrupt: foo\n')
514 else:
513 else:
515 self.assertEqual(msg, 'IPython.core.tests.test_interactiveshell.DerivedInterrupt: foo\n')
514 self.assertEqual(msg, 'IPython.core.tests.test_interactiveshell.DerivedInterrupt: foo\n')
516
515
517 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
516 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
518
517
519 @onlyif_unicode_paths
518 @onlyif_unicode_paths
520 def setUp(self):
519 def setUp(self):
521 self.BASETESTDIR = tempfile.mkdtemp()
520 self.BASETESTDIR = tempfile.mkdtemp()
522 self.TESTDIR = join(self.BASETESTDIR, u"Γ₯Àâ")
521 self.TESTDIR = join(self.BASETESTDIR, u"Γ₯Àâ")
523 os.mkdir(self.TESTDIR)
522 os.mkdir(self.TESTDIR)
524 with open(join(self.TESTDIR, u"Γ₯Àâtestscript.py"), "w") as sfile:
523 with open(join(self.TESTDIR, u"Γ₯Àâtestscript.py"), "w") as sfile:
525 sfile.write("pass\n")
524 sfile.write("pass\n")
526 self.oldpath = py3compat.getcwd()
525 self.oldpath = py3compat.getcwd()
527 os.chdir(self.TESTDIR)
526 os.chdir(self.TESTDIR)
528 self.fname = u"Γ₯Àâtestscript.py"
527 self.fname = u"Γ₯Àâtestscript.py"
529
528
530 def tearDown(self):
529 def tearDown(self):
531 os.chdir(self.oldpath)
530 os.chdir(self.oldpath)
532 shutil.rmtree(self.BASETESTDIR)
531 shutil.rmtree(self.BASETESTDIR)
533
532
534 @onlyif_unicode_paths
533 @onlyif_unicode_paths
535 def test_1(self):
534 def test_1(self):
536 """Test safe_execfile with non-ascii path
535 """Test safe_execfile with non-ascii path
537 """
536 """
538 ip.safe_execfile(self.fname, {}, raise_exceptions=True)
537 ip.safe_execfile(self.fname, {}, raise_exceptions=True)
539
538
540 class ExitCodeChecks(tt.TempFileMixin):
539 class ExitCodeChecks(tt.TempFileMixin):
541 def test_exit_code_ok(self):
540 def test_exit_code_ok(self):
542 self.system('exit 0')
541 self.system('exit 0')
543 self.assertEqual(ip.user_ns['_exit_code'], 0)
542 self.assertEqual(ip.user_ns['_exit_code'], 0)
544
543
545 def test_exit_code_error(self):
544 def test_exit_code_error(self):
546 self.system('exit 1')
545 self.system('exit 1')
547 self.assertEqual(ip.user_ns['_exit_code'], 1)
546 self.assertEqual(ip.user_ns['_exit_code'], 1)
548
547
549 @skipif(not hasattr(signal, 'SIGALRM'))
548 @skipif(not hasattr(signal, 'SIGALRM'))
550 def test_exit_code_signal(self):
549 def test_exit_code_signal(self):
551 self.mktmp("import signal, time\n"
550 self.mktmp("import signal, time\n"
552 "signal.setitimer(signal.ITIMER_REAL, 0.1)\n"
551 "signal.setitimer(signal.ITIMER_REAL, 0.1)\n"
553 "time.sleep(1)\n")
552 "time.sleep(1)\n")
554 self.system("%s %s" % (sys.executable, self.fname))
553 self.system("%s %s" % (sys.executable, self.fname))
555 self.assertEqual(ip.user_ns['_exit_code'], -signal.SIGALRM)
554 self.assertEqual(ip.user_ns['_exit_code'], -signal.SIGALRM)
556
555
557 @onlyif_cmds_exist("csh")
556 @onlyif_cmds_exist("csh")
558 def test_exit_code_signal_csh(self):
557 def test_exit_code_signal_csh(self):
559 SHELL = os.environ.get('SHELL', None)
558 SHELL = os.environ.get('SHELL', None)
560 os.environ['SHELL'] = find_cmd("csh")
559 os.environ['SHELL'] = find_cmd("csh")
561 try:
560 try:
562 self.test_exit_code_signal()
561 self.test_exit_code_signal()
563 finally:
562 finally:
564 if SHELL is not None:
563 if SHELL is not None:
565 os.environ['SHELL'] = SHELL
564 os.environ['SHELL'] = SHELL
566 else:
565 else:
567 del os.environ['SHELL']
566 del os.environ['SHELL']
568
567
569 class TestSystemRaw(unittest.TestCase, ExitCodeChecks):
568 class TestSystemRaw(unittest.TestCase, ExitCodeChecks):
570 system = ip.system_raw
569 system = ip.system_raw
571
570
572 @onlyif_unicode_paths
571 @onlyif_unicode_paths
573 def test_1(self):
572 def test_1(self):
574 """Test system_raw with non-ascii cmd
573 """Test system_raw with non-ascii cmd
575 """
574 """
576 cmd = u'''python -c "'Γ₯Àâ'" '''
575 cmd = u'''python -c "'Γ₯Àâ'" '''
577 ip.system_raw(cmd)
576 ip.system_raw(cmd)
578
577
579 @mock.patch('subprocess.call', side_effect=KeyboardInterrupt)
578 @mock.patch('subprocess.call', side_effect=KeyboardInterrupt)
580 @mock.patch('os.system', side_effect=KeyboardInterrupt)
579 @mock.patch('os.system', side_effect=KeyboardInterrupt)
581 def test_control_c(self, *mocks):
580 def test_control_c(self, *mocks):
582 try:
581 try:
583 self.system("sleep 1 # wont happen")
582 self.system("sleep 1 # wont happen")
584 except KeyboardInterrupt:
583 except KeyboardInterrupt:
585 self.fail("system call should intercept "
584 self.fail("system call should intercept "
586 "keyboard interrupt from subprocess.call")
585 "keyboard interrupt from subprocess.call")
587 self.assertEqual(ip.user_ns['_exit_code'], -signal.SIGINT)
586 self.assertEqual(ip.user_ns['_exit_code'], -signal.SIGINT)
588
587
589 # TODO: Exit codes are currently ignored on Windows.
588 # TODO: Exit codes are currently ignored on Windows.
590 class TestSystemPipedExitCode(unittest.TestCase, ExitCodeChecks):
589 class TestSystemPipedExitCode(unittest.TestCase, ExitCodeChecks):
591 system = ip.system_piped
590 system = ip.system_piped
592
591
593 @skip_win32
592 @skip_win32
594 def test_exit_code_ok(self):
593 def test_exit_code_ok(self):
595 ExitCodeChecks.test_exit_code_ok(self)
594 ExitCodeChecks.test_exit_code_ok(self)
596
595
597 @skip_win32
596 @skip_win32
598 def test_exit_code_error(self):
597 def test_exit_code_error(self):
599 ExitCodeChecks.test_exit_code_error(self)
598 ExitCodeChecks.test_exit_code_error(self)
600
599
601 @skip_win32
600 @skip_win32
602 def test_exit_code_signal(self):
601 def test_exit_code_signal(self):
603 ExitCodeChecks.test_exit_code_signal(self)
602 ExitCodeChecks.test_exit_code_signal(self)
604
603
605 class TestModules(unittest.TestCase, tt.TempFileMixin):
604 class TestModules(unittest.TestCase, tt.TempFileMixin):
606 def test_extraneous_loads(self):
605 def test_extraneous_loads(self):
607 """Test we're not loading modules on startup that we shouldn't.
606 """Test we're not loading modules on startup that we shouldn't.
608 """
607 """
609 self.mktmp("import sys\n"
608 self.mktmp("import sys\n"
610 "print('numpy' in sys.modules)\n"
609 "print('numpy' in sys.modules)\n"
611 "print('ipyparallel' in sys.modules)\n"
610 "print('ipyparallel' in sys.modules)\n"
612 "print('ipykernel' in sys.modules)\n"
611 "print('ipykernel' in sys.modules)\n"
613 )
612 )
614 out = "False\nFalse\nFalse\n"
613 out = "False\nFalse\nFalse\n"
615 tt.ipexec_validate(self.fname, out)
614 tt.ipexec_validate(self.fname, out)
616
615
617 class Negator(ast.NodeTransformer):
616 class Negator(ast.NodeTransformer):
618 """Negates all number literals in an AST."""
617 """Negates all number literals in an AST."""
619 def visit_Num(self, node):
618 def visit_Num(self, node):
620 node.n = -node.n
619 node.n = -node.n
621 return node
620 return node
622
621
623 class TestAstTransform(unittest.TestCase):
622 class TestAstTransform(unittest.TestCase):
624 def setUp(self):
623 def setUp(self):
625 self.negator = Negator()
624 self.negator = Negator()
626 ip.ast_transformers.append(self.negator)
625 ip.ast_transformers.append(self.negator)
627
626
628 def tearDown(self):
627 def tearDown(self):
629 ip.ast_transformers.remove(self.negator)
628 ip.ast_transformers.remove(self.negator)
630
629
631 def test_run_cell(self):
630 def test_run_cell(self):
632 with tt.AssertPrints('-34'):
631 with tt.AssertPrints('-34'):
633 ip.run_cell('print (12 + 22)')
632 ip.run_cell('print (12 + 22)')
634
633
635 # A named reference to a number shouldn't be transformed.
634 # A named reference to a number shouldn't be transformed.
636 ip.user_ns['n'] = 55
635 ip.user_ns['n'] = 55
637 with tt.AssertNotPrints('-55'):
636 with tt.AssertNotPrints('-55'):
638 ip.run_cell('print (n)')
637 ip.run_cell('print (n)')
639
638
640 def test_timeit(self):
639 def test_timeit(self):
641 called = set()
640 called = set()
642 def f(x):
641 def f(x):
643 called.add(x)
642 called.add(x)
644 ip.push({'f':f})
643 ip.push({'f':f})
645
644
646 with tt.AssertPrints("best of "):
645 with tt.AssertPrints("best of "):
647 ip.run_line_magic("timeit", "-n1 f(1)")
646 ip.run_line_magic("timeit", "-n1 f(1)")
648 self.assertEqual(called, {-1})
647 self.assertEqual(called, {-1})
649 called.clear()
648 called.clear()
650
649
651 with tt.AssertPrints("best of "):
650 with tt.AssertPrints("best of "):
652 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
651 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
653 self.assertEqual(called, {-2, -3})
652 self.assertEqual(called, {-2, -3})
654
653
655 def test_time(self):
654 def test_time(self):
656 called = []
655 called = []
657 def f(x):
656 def f(x):
658 called.append(x)
657 called.append(x)
659 ip.push({'f':f})
658 ip.push({'f':f})
660
659
661 # Test with an expression
660 # Test with an expression
662 with tt.AssertPrints("Wall time: "):
661 with tt.AssertPrints("Wall time: "):
663 ip.run_line_magic("time", "f(5+9)")
662 ip.run_line_magic("time", "f(5+9)")
664 self.assertEqual(called, [-14])
663 self.assertEqual(called, [-14])
665 called[:] = []
664 called[:] = []
666
665
667 # Test with a statement (different code path)
666 # Test with a statement (different code path)
668 with tt.AssertPrints("Wall time: "):
667 with tt.AssertPrints("Wall time: "):
669 ip.run_line_magic("time", "a = f(-3 + -2)")
668 ip.run_line_magic("time", "a = f(-3 + -2)")
670 self.assertEqual(called, [5])
669 self.assertEqual(called, [5])
671
670
672 def test_macro(self):
671 def test_macro(self):
673 ip.push({'a':10})
672 ip.push({'a':10})
674 # The AST transformation makes this do a+=-1
673 # The AST transformation makes this do a+=-1
675 ip.define_macro("amacro", "a+=1\nprint(a)")
674 ip.define_macro("amacro", "a+=1\nprint(a)")
676
675
677 with tt.AssertPrints("9"):
676 with tt.AssertPrints("9"):
678 ip.run_cell("amacro")
677 ip.run_cell("amacro")
679 with tt.AssertPrints("8"):
678 with tt.AssertPrints("8"):
680 ip.run_cell("amacro")
679 ip.run_cell("amacro")
681
680
682 class IntegerWrapper(ast.NodeTransformer):
681 class IntegerWrapper(ast.NodeTransformer):
683 """Wraps all integers in a call to Integer()"""
682 """Wraps all integers in a call to Integer()"""
684 def visit_Num(self, node):
683 def visit_Num(self, node):
685 if isinstance(node.n, int):
684 if isinstance(node.n, int):
686 return ast.Call(func=ast.Name(id='Integer', ctx=ast.Load()),
685 return ast.Call(func=ast.Name(id='Integer', ctx=ast.Load()),
687 args=[node], keywords=[])
686 args=[node], keywords=[])
688 return node
687 return node
689
688
690 class TestAstTransform2(unittest.TestCase):
689 class TestAstTransform2(unittest.TestCase):
691 def setUp(self):
690 def setUp(self):
692 self.intwrapper = IntegerWrapper()
691 self.intwrapper = IntegerWrapper()
693 ip.ast_transformers.append(self.intwrapper)
692 ip.ast_transformers.append(self.intwrapper)
694
693
695 self.calls = []
694 self.calls = []
696 def Integer(*args):
695 def Integer(*args):
697 self.calls.append(args)
696 self.calls.append(args)
698 return args
697 return args
699 ip.push({"Integer": Integer})
698 ip.push({"Integer": Integer})
700
699
701 def tearDown(self):
700 def tearDown(self):
702 ip.ast_transformers.remove(self.intwrapper)
701 ip.ast_transformers.remove(self.intwrapper)
703 del ip.user_ns['Integer']
702 del ip.user_ns['Integer']
704
703
705 def test_run_cell(self):
704 def test_run_cell(self):
706 ip.run_cell("n = 2")
705 ip.run_cell("n = 2")
707 self.assertEqual(self.calls, [(2,)])
706 self.assertEqual(self.calls, [(2,)])
708
707
709 # This shouldn't throw an error
708 # This shouldn't throw an error
710 ip.run_cell("o = 2.0")
709 ip.run_cell("o = 2.0")
711 self.assertEqual(ip.user_ns['o'], 2.0)
710 self.assertEqual(ip.user_ns['o'], 2.0)
712
711
713 def test_timeit(self):
712 def test_timeit(self):
714 called = set()
713 called = set()
715 def f(x):
714 def f(x):
716 called.add(x)
715 called.add(x)
717 ip.push({'f':f})
716 ip.push({'f':f})
718
717
719 with tt.AssertPrints("best of "):
718 with tt.AssertPrints("best of "):
720 ip.run_line_magic("timeit", "-n1 f(1)")
719 ip.run_line_magic("timeit", "-n1 f(1)")
721 self.assertEqual(called, {(1,)})
720 self.assertEqual(called, {(1,)})
722 called.clear()
721 called.clear()
723
722
724 with tt.AssertPrints("best of "):
723 with tt.AssertPrints("best of "):
725 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
724 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
726 self.assertEqual(called, {(2,), (3,)})
725 self.assertEqual(called, {(2,), (3,)})
727
726
728 class ErrorTransformer(ast.NodeTransformer):
727 class ErrorTransformer(ast.NodeTransformer):
729 """Throws an error when it sees a number."""
728 """Throws an error when it sees a number."""
730 def visit_Num(self, node):
729 def visit_Num(self, node):
731 raise ValueError("test")
730 raise ValueError("test")
732
731
733 class TestAstTransformError(unittest.TestCase):
732 class TestAstTransformError(unittest.TestCase):
734 def test_unregistering(self):
733 def test_unregistering(self):
735 err_transformer = ErrorTransformer()
734 err_transformer = ErrorTransformer()
736 ip.ast_transformers.append(err_transformer)
735 ip.ast_transformers.append(err_transformer)
737
736
738 with tt.AssertPrints("unregister", channel='stderr'):
737 with tt.AssertPrints("unregister", channel='stderr'):
739 ip.run_cell("1 + 2")
738 ip.run_cell("1 + 2")
740
739
741 # This should have been removed.
740 # This should have been removed.
742 nt.assert_not_in(err_transformer, ip.ast_transformers)
741 nt.assert_not_in(err_transformer, ip.ast_transformers)
743
742
744
743
745 class StringRejector(ast.NodeTransformer):
744 class StringRejector(ast.NodeTransformer):
746 """Throws an InputRejected when it sees a string literal.
745 """Throws an InputRejected when it sees a string literal.
747
746
748 Used to verify that NodeTransformers can signal that a piece of code should
747 Used to verify that NodeTransformers can signal that a piece of code should
749 not be executed by throwing an InputRejected.
748 not be executed by throwing an InputRejected.
750 """
749 """
751
750
752 def visit_Str(self, node):
751 def visit_Str(self, node):
753 raise InputRejected("test")
752 raise InputRejected("test")
754
753
755
754
756 class TestAstTransformInputRejection(unittest.TestCase):
755 class TestAstTransformInputRejection(unittest.TestCase):
757
756
758 def setUp(self):
757 def setUp(self):
759 self.transformer = StringRejector()
758 self.transformer = StringRejector()
760 ip.ast_transformers.append(self.transformer)
759 ip.ast_transformers.append(self.transformer)
761
760
762 def tearDown(self):
761 def tearDown(self):
763 ip.ast_transformers.remove(self.transformer)
762 ip.ast_transformers.remove(self.transformer)
764
763
765 def test_input_rejection(self):
764 def test_input_rejection(self):
766 """Check that NodeTransformers can reject input."""
765 """Check that NodeTransformers can reject input."""
767
766
768 expect_exception_tb = tt.AssertPrints("InputRejected: test")
767 expect_exception_tb = tt.AssertPrints("InputRejected: test")
769 expect_no_cell_output = tt.AssertNotPrints("'unsafe'", suppress=False)
768 expect_no_cell_output = tt.AssertNotPrints("'unsafe'", suppress=False)
770
769
771 # Run the same check twice to verify that the transformer is not
770 # Run the same check twice to verify that the transformer is not
772 # disabled after raising.
771 # disabled after raising.
773 with expect_exception_tb, expect_no_cell_output:
772 with expect_exception_tb, expect_no_cell_output:
774 ip.run_cell("'unsafe'")
773 ip.run_cell("'unsafe'")
775
774
776 with expect_exception_tb, expect_no_cell_output:
775 with expect_exception_tb, expect_no_cell_output:
777 res = ip.run_cell("'unsafe'")
776 res = ip.run_cell("'unsafe'")
778
777
779 self.assertIsInstance(res.error_before_exec, InputRejected)
778 self.assertIsInstance(res.error_before_exec, InputRejected)
780
779
781 def test__IPYTHON__():
780 def test__IPYTHON__():
782 # This shouldn't raise a NameError, that's all
781 # This shouldn't raise a NameError, that's all
783 __IPYTHON__
782 __IPYTHON__
784
783
785
784
786 class DummyRepr(object):
785 class DummyRepr(object):
787 def __repr__(self):
786 def __repr__(self):
788 return "DummyRepr"
787 return "DummyRepr"
789
788
790 def _repr_html_(self):
789 def _repr_html_(self):
791 return "<b>dummy</b>"
790 return "<b>dummy</b>"
792
791
793 def _repr_javascript_(self):
792 def _repr_javascript_(self):
794 return "console.log('hi');", {'key': 'value'}
793 return "console.log('hi');", {'key': 'value'}
795
794
796
795
797 def test_user_variables():
796 def test_user_variables():
798 # enable all formatters
797 # enable all formatters
799 ip.display_formatter.active_types = ip.display_formatter.format_types
798 ip.display_formatter.active_types = ip.display_formatter.format_types
800
799
801 ip.user_ns['dummy'] = d = DummyRepr()
800 ip.user_ns['dummy'] = d = DummyRepr()
802 keys = {'dummy', 'doesnotexist'}
801 keys = {'dummy', 'doesnotexist'}
803 r = ip.user_expressions({ key:key for key in keys})
802 r = ip.user_expressions({ key:key for key in keys})
804
803
805 nt.assert_equal(keys, set(r.keys()))
804 nt.assert_equal(keys, set(r.keys()))
806 dummy = r['dummy']
805 dummy = r['dummy']
807 nt.assert_equal({'status', 'data', 'metadata'}, set(dummy.keys()))
806 nt.assert_equal({'status', 'data', 'metadata'}, set(dummy.keys()))
808 nt.assert_equal(dummy['status'], 'ok')
807 nt.assert_equal(dummy['status'], 'ok')
809 data = dummy['data']
808 data = dummy['data']
810 metadata = dummy['metadata']
809 metadata = dummy['metadata']
811 nt.assert_equal(data.get('text/html'), d._repr_html_())
810 nt.assert_equal(data.get('text/html'), d._repr_html_())
812 js, jsmd = d._repr_javascript_()
811 js, jsmd = d._repr_javascript_()
813 nt.assert_equal(data.get('application/javascript'), js)
812 nt.assert_equal(data.get('application/javascript'), js)
814 nt.assert_equal(metadata.get('application/javascript'), jsmd)
813 nt.assert_equal(metadata.get('application/javascript'), jsmd)
815
814
816 dne = r['doesnotexist']
815 dne = r['doesnotexist']
817 nt.assert_equal(dne['status'], 'error')
816 nt.assert_equal(dne['status'], 'error')
818 nt.assert_equal(dne['ename'], 'NameError')
817 nt.assert_equal(dne['ename'], 'NameError')
819
818
820 # back to text only
819 # back to text only
821 ip.display_formatter.active_types = ['text/plain']
820 ip.display_formatter.active_types = ['text/plain']
822
821
823 def test_user_expression():
822 def test_user_expression():
824 # enable all formatters
823 # enable all formatters
825 ip.display_formatter.active_types = ip.display_formatter.format_types
824 ip.display_formatter.active_types = ip.display_formatter.format_types
826 query = {
825 query = {
827 'a' : '1 + 2',
826 'a' : '1 + 2',
828 'b' : '1/0',
827 'b' : '1/0',
829 }
828 }
830 r = ip.user_expressions(query)
829 r = ip.user_expressions(query)
831 import pprint
830 import pprint
832 pprint.pprint(r)
831 pprint.pprint(r)
833 nt.assert_equal(set(r.keys()), set(query.keys()))
832 nt.assert_equal(set(r.keys()), set(query.keys()))
834 a = r['a']
833 a = r['a']
835 nt.assert_equal({'status', 'data', 'metadata'}, set(a.keys()))
834 nt.assert_equal({'status', 'data', 'metadata'}, set(a.keys()))
836 nt.assert_equal(a['status'], 'ok')
835 nt.assert_equal(a['status'], 'ok')
837 data = a['data']
836 data = a['data']
838 metadata = a['metadata']
837 metadata = a['metadata']
839 nt.assert_equal(data.get('text/plain'), '3')
838 nt.assert_equal(data.get('text/plain'), '3')
840
839
841 b = r['b']
840 b = r['b']
842 nt.assert_equal(b['status'], 'error')
841 nt.assert_equal(b['status'], 'error')
843 nt.assert_equal(b['ename'], 'ZeroDivisionError')
842 nt.assert_equal(b['ename'], 'ZeroDivisionError')
844
843
845 # back to text only
844 # back to text only
846 ip.display_formatter.active_types = ['text/plain']
845 ip.display_formatter.active_types = ['text/plain']
847
846
848
847
849
848
850
849
851
850
852 class TestSyntaxErrorTransformer(unittest.TestCase):
851 class TestSyntaxErrorTransformer(unittest.TestCase):
853 """Check that SyntaxError raised by an input transformer is handled by run_cell()"""
852 """Check that SyntaxError raised by an input transformer is handled by run_cell()"""
854
853
855 class SyntaxErrorTransformer(InputTransformer):
854 class SyntaxErrorTransformer(InputTransformer):
856
855
857 def push(self, line):
856 def push(self, line):
858 pos = line.find('syntaxerror')
857 pos = line.find('syntaxerror')
859 if pos >= 0:
858 if pos >= 0:
860 e = SyntaxError('input contains "syntaxerror"')
859 e = SyntaxError('input contains "syntaxerror"')
861 e.text = line
860 e.text = line
862 e.offset = pos + 1
861 e.offset = pos + 1
863 raise e
862 raise e
864 return line
863 return line
865
864
866 def reset(self):
865 def reset(self):
867 pass
866 pass
868
867
869 def setUp(self):
868 def setUp(self):
870 self.transformer = TestSyntaxErrorTransformer.SyntaxErrorTransformer()
869 self.transformer = TestSyntaxErrorTransformer.SyntaxErrorTransformer()
871 ip.input_splitter.python_line_transforms.append(self.transformer)
870 ip.input_splitter.python_line_transforms.append(self.transformer)
872 ip.input_transformer_manager.python_line_transforms.append(self.transformer)
871 ip.input_transformer_manager.python_line_transforms.append(self.transformer)
873
872
874 def tearDown(self):
873 def tearDown(self):
875 ip.input_splitter.python_line_transforms.remove(self.transformer)
874 ip.input_splitter.python_line_transforms.remove(self.transformer)
876 ip.input_transformer_manager.python_line_transforms.remove(self.transformer)
875 ip.input_transformer_manager.python_line_transforms.remove(self.transformer)
877
876
878 def test_syntaxerror_input_transformer(self):
877 def test_syntaxerror_input_transformer(self):
879 with tt.AssertPrints('1234'):
878 with tt.AssertPrints('1234'):
880 ip.run_cell('1234')
879 ip.run_cell('1234')
881 with tt.AssertPrints('SyntaxError: invalid syntax'):
880 with tt.AssertPrints('SyntaxError: invalid syntax'):
882 ip.run_cell('1 2 3') # plain python syntax error
881 ip.run_cell('1 2 3') # plain python syntax error
883 with tt.AssertPrints('SyntaxError: input contains "syntaxerror"'):
882 with tt.AssertPrints('SyntaxError: input contains "syntaxerror"'):
884 ip.run_cell('2345 # syntaxerror') # input transformer syntax error
883 ip.run_cell('2345 # syntaxerror') # input transformer syntax error
885 with tt.AssertPrints('3456'):
884 with tt.AssertPrints('3456'):
886 ip.run_cell('3456')
885 ip.run_cell('3456')
887
886
888
887
889
888
890 def test_warning_suppression():
889 def test_warning_suppression():
891 ip.run_cell("import warnings")
890 ip.run_cell("import warnings")
892 try:
891 try:
893 with tt.AssertPrints("UserWarning: asdf", channel="stderr"):
892 with tt.AssertPrints("UserWarning: asdf", channel="stderr"):
894 ip.run_cell("warnings.warn('asdf')")
893 ip.run_cell("warnings.warn('asdf')")
895 # Here's the real test -- if we run that again, we should get the
894 # Here's the real test -- if we run that again, we should get the
896 # warning again. Traditionally, each warning was only issued once per
895 # warning again. Traditionally, each warning was only issued once per
897 # IPython session (approximately), even if the user typed in new and
896 # IPython session (approximately), even if the user typed in new and
898 # different code that should have also triggered the warning, leading
897 # different code that should have also triggered the warning, leading
899 # to much confusion.
898 # to much confusion.
900 with tt.AssertPrints("UserWarning: asdf", channel="stderr"):
899 with tt.AssertPrints("UserWarning: asdf", channel="stderr"):
901 ip.run_cell("warnings.warn('asdf')")
900 ip.run_cell("warnings.warn('asdf')")
902 finally:
901 finally:
903 ip.run_cell("del warnings")
902 ip.run_cell("del warnings")
904
903
905
904
906 def test_deprecation_warning():
905 def test_deprecation_warning():
907 ip.run_cell("""
906 ip.run_cell("""
908 import warnings
907 import warnings
909 def wrn():
908 def wrn():
910 warnings.warn(
909 warnings.warn(
911 "I AM A WARNING",
910 "I AM A WARNING",
912 DeprecationWarning
911 DeprecationWarning
913 )
912 )
914 """)
913 """)
915 try:
914 try:
916 with tt.AssertPrints("I AM A WARNING", channel="stderr"):
915 with tt.AssertPrints("I AM A WARNING", channel="stderr"):
917 ip.run_cell("wrn()")
916 ip.run_cell("wrn()")
918 finally:
917 finally:
919 ip.run_cell("del warnings")
918 ip.run_cell("del warnings")
920 ip.run_cell("del wrn")
919 ip.run_cell("del wrn")
921
920
922
921
923 class TestImportNoDeprecate(tt.TempFileMixin):
922 class TestImportNoDeprecate(tt.TempFileMixin):
924
923
925 def setup(self):
924 def setup(self):
926 """Make a valid python temp file."""
925 """Make a valid python temp file."""
927 self.mktmp("""
926 self.mktmp("""
928 import warnings
927 import warnings
929 def wrn():
928 def wrn():
930 warnings.warn(
929 warnings.warn(
931 "I AM A WARNING",
930 "I AM A WARNING",
932 DeprecationWarning
931 DeprecationWarning
933 )
932 )
934 """)
933 """)
935
934
936 def test_no_dep(self):
935 def test_no_dep(self):
937 """
936 """
938 No deprecation warning should be raised from imported functions
937 No deprecation warning should be raised from imported functions
939 """
938 """
940 ip.run_cell("from {} import wrn".format(self.fname))
939 ip.run_cell("from {} import wrn".format(self.fname))
941
940
942 with tt.AssertNotPrints("I AM A WARNING"):
941 with tt.AssertNotPrints("I AM A WARNING"):
943 ip.run_cell("wrn()")
942 ip.run_cell("wrn()")
944 ip.run_cell("del wrn")
943 ip.run_cell("del wrn")
@@ -1,360 +1,361 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Provides a reload() function that acts recursively.
3 Provides a reload() function that acts recursively.
4
4
5 Python's normal :func:`python:reload` function only reloads the module that it's
5 Python's normal :func:`python:reload` function only reloads the module that it's
6 passed. The :func:`reload` function in this module also reloads everything
6 passed. The :func:`reload` function in this module also reloads everything
7 imported from that module, which is useful when you're changing files deep
7 imported from that module, which is useful when you're changing files deep
8 inside a package.
8 inside a package.
9
9
10 To use this as your default reload function, type this for Python 2::
10 To use this as your default reload function, type this for Python 2::
11
11
12 import __builtin__
12 import __builtin__
13 from IPython.lib import deepreload
13 from IPython.lib import deepreload
14 __builtin__.reload = deepreload.reload
14 __builtin__.reload = deepreload.reload
15
15
16 Or this for Python 3::
16 Or this for Python 3::
17
17
18 import builtins
18 import builtins
19 from IPython.lib import deepreload
19 from IPython.lib import deepreload
20 builtins.reload = deepreload.reload
20 builtins.reload = deepreload.reload
21
21
22 A reference to the original :func:`python:reload` is stored in this module as
22 A reference to the original :func:`python:reload` is stored in this module as
23 :data:`original_reload`, so you can restore it later.
23 :data:`original_reload`, so you can restore it later.
24
24
25 This code is almost entirely based on knee.py, which is a Python
25 This code is almost entirely based on knee.py, which is a Python
26 re-implementation of hierarchical module import.
26 re-implementation of hierarchical module import.
27 """
27 """
28 from __future__ import print_function
28 from __future__ import print_function
29 #*****************************************************************************
29 #*****************************************************************************
30 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
30 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
31 #
31 #
32 # Distributed under the terms of the BSD License. The full license is in
32 # Distributed under the terms of the BSD License. The full license is in
33 # the file COPYING, distributed as part of this software.
33 # the file COPYING, distributed as part of this software.
34 #*****************************************************************************
34 #*****************************************************************************
35
35
36 from contextlib import contextmanager
36 from contextlib import contextmanager
37 import imp
37 import imp
38 import sys
38 import sys
39
39
40 from types import ModuleType
40 from types import ModuleType
41 from warnings import warn
41 from warnings import warn
42
42
43 from IPython.utils.py3compat import builtin_mod, builtin_mod_name
43 from IPython.utils.py3compat import builtin_mod, builtin_mod_name
44
44
45 original_import = builtin_mod.__import__
45 original_import = builtin_mod.__import__
46
46
47 @contextmanager
47 @contextmanager
48 def replace_import_hook(new_import):
48 def replace_import_hook(new_import):
49 saved_import = builtin_mod.__import__
49 saved_import = builtin_mod.__import__
50 builtin_mod.__import__ = new_import
50 builtin_mod.__import__ = new_import
51 try:
51 try:
52 yield
52 yield
53 finally:
53 finally:
54 builtin_mod.__import__ = saved_import
54 builtin_mod.__import__ = saved_import
55
55
56 def get_parent(globals, level):
56 def get_parent(globals, level):
57 """
57 """
58 parent, name = get_parent(globals, level)
58 parent, name = get_parent(globals, level)
59
59
60 Return the package that an import is being performed in. If globals comes
60 Return the package that an import is being performed in. If globals comes
61 from the module foo.bar.bat (not itself a package), this returns the
61 from the module foo.bar.bat (not itself a package), this returns the
62 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
62 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
63 the package's entry in sys.modules is returned.
63 the package's entry in sys.modules is returned.
64
64
65 If globals doesn't come from a package or a module in a package, or a
65 If globals doesn't come from a package or a module in a package, or a
66 corresponding entry is not found in sys.modules, None is returned.
66 corresponding entry is not found in sys.modules, None is returned.
67 """
67 """
68 orig_level = level
68 orig_level = level
69
69
70 if not level or not isinstance(globals, dict):
70 if not level or not isinstance(globals, dict):
71 return None, ''
71 return None, ''
72
72
73 pkgname = globals.get('__package__', None)
73 pkgname = globals.get('__package__', None)
74
74
75 if pkgname is not None:
75 if pkgname is not None:
76 # __package__ is set, so use it
76 # __package__ is set, so use it
77 if not hasattr(pkgname, 'rindex'):
77 if not hasattr(pkgname, 'rindex'):
78 raise ValueError('__package__ set to non-string')
78 raise ValueError('__package__ set to non-string')
79 if len(pkgname) == 0:
79 if len(pkgname) == 0:
80 if level > 0:
80 if level > 0:
81 raise ValueError('Attempted relative import in non-package')
81 raise ValueError('Attempted relative import in non-package')
82 return None, ''
82 return None, ''
83 name = pkgname
83 name = pkgname
84 else:
84 else:
85 # __package__ not set, so figure it out and set it
85 # __package__ not set, so figure it out and set it
86 if '__name__' not in globals:
86 if '__name__' not in globals:
87 return None, ''
87 return None, ''
88 modname = globals['__name__']
88 modname = globals['__name__']
89
89
90 if '__path__' in globals:
90 if '__path__' in globals:
91 # __path__ is set, so modname is already the package name
91 # __path__ is set, so modname is already the package name
92 globals['__package__'] = name = modname
92 globals['__package__'] = name = modname
93 else:
93 else:
94 # Normal module, so work out the package name if any
94 # Normal module, so work out the package name if any
95 lastdot = modname.rfind('.')
95 lastdot = modname.rfind('.')
96 if lastdot < 0 < level:
96 if lastdot < 0 < level:
97 raise ValueError("Attempted relative import in non-package")
97 raise ValueError("Attempted relative import in non-package")
98 if lastdot < 0:
98 if lastdot < 0:
99 globals['__package__'] = None
99 globals['__package__'] = None
100 return None, ''
100 return None, ''
101 globals['__package__'] = name = modname[:lastdot]
101 globals['__package__'] = name = modname[:lastdot]
102
102
103 dot = len(name)
103 dot = len(name)
104 for x in range(level, 1, -1):
104 for x in range(level, 1, -1):
105 try:
105 try:
106 dot = name.rindex('.', 0, dot)
106 dot = name.rindex('.', 0, dot)
107 except ValueError:
107 except ValueError:
108 raise ValueError("attempted relative import beyond top-level "
108 raise ValueError("attempted relative import beyond top-level "
109 "package")
109 "package")
110 name = name[:dot]
110 name = name[:dot]
111
111
112 try:
112 try:
113 parent = sys.modules[name]
113 parent = sys.modules[name]
114 except:
114 except:
115 if orig_level < 1:
115 if orig_level < 1:
116 warn("Parent module '%.200s' not found while handling absolute "
116 warn("Parent module '%.200s' not found while handling absolute "
117 "import" % name)
117 "import" % name)
118 parent = None
118 parent = None
119 else:
119 else:
120 raise SystemError("Parent module '%.200s' not loaded, cannot "
120 raise SystemError("Parent module '%.200s' not loaded, cannot "
121 "perform relative import" % name)
121 "perform relative import" % name)
122
122
123 # We expect, but can't guarantee, if parent != None, that:
123 # We expect, but can't guarantee, if parent != None, that:
124 # - parent.__name__ == name
124 # - parent.__name__ == name
125 # - parent.__dict__ is globals
125 # - parent.__dict__ is globals
126 # If this is violated... Who cares?
126 # If this is violated... Who cares?
127 return parent, name
127 return parent, name
128
128
129 def load_next(mod, altmod, name, buf):
129 def load_next(mod, altmod, name, buf):
130 """
130 """
131 mod, name, buf = load_next(mod, altmod, name, buf)
131 mod, name, buf = load_next(mod, altmod, name, buf)
132
132
133 altmod is either None or same as mod
133 altmod is either None or same as mod
134 """
134 """
135
135
136 if len(name) == 0:
136 if len(name) == 0:
137 # completely empty module name should only happen in
137 # completely empty module name should only happen in
138 # 'from . import' (or '__import__("")')
138 # 'from . import' (or '__import__("")')
139 return mod, None, buf
139 return mod, None, buf
140
140
141 dot = name.find('.')
141 dot = name.find('.')
142 if dot == 0:
142 if dot == 0:
143 raise ValueError('Empty module name')
143 raise ValueError('Empty module name')
144
144
145 if dot < 0:
145 if dot < 0:
146 subname = name
146 subname = name
147 next = None
147 next = None
148 else:
148 else:
149 subname = name[:dot]
149 subname = name[:dot]
150 next = name[dot+1:]
150 next = name[dot+1:]
151
151
152 if buf != '':
152 if buf != '':
153 buf += '.'
153 buf += '.'
154 buf += subname
154 buf += subname
155
155
156 result = import_submodule(mod, subname, buf)
156 result = import_submodule(mod, subname, buf)
157 if result is None and mod != altmod:
157 if result is None and mod != altmod:
158 result = import_submodule(altmod, subname, subname)
158 result = import_submodule(altmod, subname, subname)
159 if result is not None:
159 if result is not None:
160 buf = subname
160 buf = subname
161
161
162 if result is None:
162 if result is None:
163 raise ImportError("No module named %.200s" % name)
163 raise ImportError("No module named %.200s" % name)
164
164
165 return result, next, buf
165 return result, next, buf
166
166
167 # Need to keep track of what we've already reloaded to prevent cyclic evil
167 # Need to keep track of what we've already reloaded to prevent cyclic evil
168 found_now = {}
168 found_now = {}
169
169
170 def import_submodule(mod, subname, fullname):
170 def import_submodule(mod, subname, fullname):
171 """m = import_submodule(mod, subname, fullname)"""
171 """m = import_submodule(mod, subname, fullname)"""
172 # Require:
172 # Require:
173 # if mod == None: subname == fullname
173 # if mod == None: subname == fullname
174 # else: mod.__name__ + "." + subname == fullname
174 # else: mod.__name__ + "." + subname == fullname
175
175
176 global found_now
176 global found_now
177 if fullname in found_now and fullname in sys.modules:
177 if fullname in found_now and fullname in sys.modules:
178 m = sys.modules[fullname]
178 m = sys.modules[fullname]
179 else:
179 else:
180 print('Reloading', fullname)
180 print('Reloading', fullname)
181 found_now[fullname] = 1
181 found_now[fullname] = 1
182 oldm = sys.modules.get(fullname, None)
182 oldm = sys.modules.get(fullname, None)
183
183
184 if mod is None:
184 if mod is None:
185 path = None
185 path = None
186 elif hasattr(mod, '__path__'):
186 elif hasattr(mod, '__path__'):
187 path = mod.__path__
187 path = mod.__path__
188 else:
188 else:
189 return None
189 return None
190
190
191 try:
191 try:
192 # This appears to be necessary on Python 3, because imp.find_module()
192 # This appears to be necessary on Python 3, because imp.find_module()
193 # tries to import standard libraries (like io) itself, and we don't
193 # tries to import standard libraries (like io) itself, and we don't
194 # want them to be processed by our deep_import_hook.
194 # want them to be processed by our deep_import_hook.
195 with replace_import_hook(original_import):
195 with replace_import_hook(original_import):
196 fp, filename, stuff = imp.find_module(subname, path)
196 fp, filename, stuff = imp.find_module(subname, path)
197 except ImportError:
197 except ImportError:
198 return None
198 return None
199
199
200 try:
200 try:
201 m = imp.load_module(fullname, fp, filename, stuff)
201 m = imp.load_module(fullname, fp, filename, stuff)
202 except:
202 except:
203 # load_module probably removed name from modules because of
203 # load_module probably removed name from modules because of
204 # the error. Put back the original module object.
204 # the error. Put back the original module object.
205 if oldm:
205 if oldm:
206 sys.modules[fullname] = oldm
206 sys.modules[fullname] = oldm
207 raise
207 raise
208 finally:
208 finally:
209 if fp: fp.close()
209 if fp: fp.close()
210
210
211 add_submodule(mod, m, fullname, subname)
211 add_submodule(mod, m, fullname, subname)
212
212
213 return m
213 return m
214
214
215 def add_submodule(mod, submod, fullname, subname):
215 def add_submodule(mod, submod, fullname, subname):
216 """mod.{subname} = submod"""
216 """mod.{subname} = submod"""
217 if mod is None:
217 if mod is None:
218 return #Nothing to do here.
218 return #Nothing to do here.
219
219
220 if submod is None:
220 if submod is None:
221 submod = sys.modules[fullname]
221 submod = sys.modules[fullname]
222
222
223 setattr(mod, subname, submod)
223 setattr(mod, subname, submod)
224
224
225 return
225 return
226
226
227 def ensure_fromlist(mod, fromlist, buf, recursive):
227 def ensure_fromlist(mod, fromlist, buf, recursive):
228 """Handle 'from module import a, b, c' imports."""
228 """Handle 'from module import a, b, c' imports."""
229 if not hasattr(mod, '__path__'):
229 if not hasattr(mod, '__path__'):
230 return
230 return
231 for item in fromlist:
231 for item in fromlist:
232 if not hasattr(item, 'rindex'):
232 if not hasattr(item, 'rindex'):
233 raise TypeError("Item in ``from list'' not a string")
233 raise TypeError("Item in ``from list'' not a string")
234 if item == '*':
234 if item == '*':
235 if recursive:
235 if recursive:
236 continue # avoid endless recursion
236 continue # avoid endless recursion
237 try:
237 try:
238 all = mod.__all__
238 all = mod.__all__
239 except AttributeError:
239 except AttributeError:
240 pass
240 pass
241 else:
241 else:
242 ret = ensure_fromlist(mod, all, buf, 1)
242 ret = ensure_fromlist(mod, all, buf, 1)
243 if not ret:
243 if not ret:
244 return 0
244 return 0
245 elif not hasattr(mod, item):
245 elif not hasattr(mod, item):
246 import_submodule(mod, item, buf + '.' + item)
246 import_submodule(mod, item, buf + '.' + item)
247
247
248 def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
248 def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
249 """Replacement for __import__()"""
249 """Replacement for __import__()"""
250 parent, buf = get_parent(globals, level)
250 parent, buf = get_parent(globals, level)
251
251
252 head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
252 head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
253
253
254 tail = head
254 tail = head
255 while name:
255 while name:
256 tail, name, buf = load_next(tail, tail, name, buf)
256 tail, name, buf = load_next(tail, tail, name, buf)
257
257
258 # If tail is None, both get_parent and load_next found
258 # If tail is None, both get_parent and load_next found
259 # an empty module name: someone called __import__("") or
259 # an empty module name: someone called __import__("") or
260 # doctored faulty bytecode
260 # doctored faulty bytecode
261 if tail is None:
261 if tail is None:
262 raise ValueError('Empty module name')
262 raise ValueError('Empty module name')
263
263
264 if not fromlist:
264 if not fromlist:
265 return head
265 return head
266
266
267 ensure_fromlist(tail, fromlist, buf, 0)
267 ensure_fromlist(tail, fromlist, buf, 0)
268 return tail
268 return tail
269
269
270 modules_reloading = {}
270 modules_reloading = {}
271
271
272 def deep_reload_hook(m):
272 def deep_reload_hook(m):
273 """Replacement for reload()."""
273 """Replacement for reload()."""
274 if not isinstance(m, ModuleType):
274 if not isinstance(m, ModuleType):
275 raise TypeError("reload() argument must be module")
275 raise TypeError("reload() argument must be module")
276
276
277 name = m.__name__
277 name = m.__name__
278
278
279 if name not in sys.modules:
279 if name not in sys.modules:
280 raise ImportError("reload(): module %.200s not in sys.modules" % name)
280 raise ImportError("reload(): module %.200s not in sys.modules" % name)
281
281
282 global modules_reloading
282 global modules_reloading
283 try:
283 try:
284 return modules_reloading[name]
284 return modules_reloading[name]
285 except:
285 except:
286 modules_reloading[name] = m
286 modules_reloading[name] = m
287
287
288 dot = name.rfind('.')
288 dot = name.rfind('.')
289 if dot < 0:
289 if dot < 0:
290 subname = name
290 subname = name
291 path = None
291 path = None
292 else:
292 else:
293 try:
293 try:
294 parent = sys.modules[name[:dot]]
294 parent = sys.modules[name[:dot]]
295 except KeyError:
295 except KeyError:
296 modules_reloading.clear()
296 modules_reloading.clear()
297 raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
297 raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
298 subname = name[dot+1:]
298 subname = name[dot+1:]
299 path = getattr(parent, "__path__", None)
299 path = getattr(parent, "__path__", None)
300
300
301 try:
301 try:
302 # This appears to be necessary on Python 3, because imp.find_module()
302 # This appears to be necessary on Python 3, because imp.find_module()
303 # tries to import standard libraries (like io) itself, and we don't
303 # tries to import standard libraries (like io) itself, and we don't
304 # want them to be processed by our deep_import_hook.
304 # want them to be processed by our deep_import_hook.
305 with replace_import_hook(original_import):
305 with replace_import_hook(original_import):
306 fp, filename, stuff = imp.find_module(subname, path)
306 fp, filename, stuff = imp.find_module(subname, path)
307 finally:
307 finally:
308 modules_reloading.clear()
308 modules_reloading.clear()
309
309
310 try:
310 try:
311 newm = imp.load_module(name, fp, filename, stuff)
311 newm = imp.load_module(name, fp, filename, stuff)
312 except:
312 except:
313 # load_module probably removed name from modules because of
313 # load_module probably removed name from modules because of
314 # the error. Put back the original module object.
314 # the error. Put back the original module object.
315 sys.modules[name] = m
315 sys.modules[name] = m
316 raise
316 raise
317 finally:
317 finally:
318 if fp: fp.close()
318 if fp: fp.close()
319
319
320 modules_reloading.clear()
320 modules_reloading.clear()
321 return newm
321 return newm
322
322
323 # Save the original hooks
323 # Save the original hooks
324 try:
324 try:
325 original_reload = builtin_mod.reload
325 original_reload = builtin_mod.reload
326 except AttributeError:
326 except AttributeError:
327 original_reload = imp.reload # Python 3
327 original_reload = imp.reload # Python 3
328
328
329 # Replacement for reload()
329 # Replacement for reload()
330 def reload(module, exclude=('sys', 'os.path', builtin_mod_name, '__main__')):
330 def reload(module, exclude=('sys', 'os.path', builtin_mod_name, '__main__')):
331 """Recursively reload all modules used in the given module. Optionally
331 """Recursively reload all modules used in the given module. Optionally
332 takes a list of modules to exclude from reloading. The default exclude
332 takes a list of modules to exclude from reloading. The default exclude
333 list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
333 list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
334 display, exception, and io hooks.
334 display, exception, and io hooks.
335 """
335 """
336 global found_now
336 global found_now
337 for i in exclude:
337 for i in exclude:
338 found_now[i] = 1
338 found_now[i] = 1
339 try:
339 try:
340 with replace_import_hook(deep_import_hook):
340 with replace_import_hook(deep_import_hook):
341 return deep_reload_hook(module)
341 return deep_reload_hook(module)
342 finally:
342 finally:
343 found_now = {}
343 found_now = {}
344
344
345
345
346 def _dreload(module, **kwargs):
346 def _dreload(module, **kwargs):
347 """
347 """
348 **deprecated**
348 **deprecated**
349
349
350 import reload explicitly from `IPython.lib.deepreload` to use it
350 import reload explicitly from `IPython.lib.deepreload` to use it
351
351
352 """
352 """
353 warn("""
353 warn("""
354 injecting `dreload` in interactive namespace is deprecated, please import `reload` explicitly from `IPython.lib.deepreload`
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 """, DeprecationWarning, stacklevel=2)
356 """, DeprecationWarning, stacklevel=2)
356 reload(module, **kwargs)
357 reload(module, **kwargs)
357
358
358 # Uncomment the following to automatically activate deep reloading whenever
359 # Uncomment the following to automatically activate deep reloading whenever
359 # this module is imported
360 # this module is imported
360 #builtin_mod.reload = reload
361 #builtin_mod.reload = reload
@@ -1,12 +1,13 b''
1 """[DEPRECATED] Utilities for connecting to kernels
1 """[DEPRECATED] Utilities for connecting to kernels
2
2
3 Moved to IPython.kernel.connect
3 Moved to IPython.kernel.connect
4 """
4 """
5
5
6 import warnings
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 DeprecationWarning
9 DeprecationWarning
9 )
10 )
10
11
11 from ipykernel.connect import *
12 from ipykernel.connect import *
12
13
@@ -1,278 +1,278 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 An embedded IPython shell.
3 An embedded IPython shell.
4 """
4 """
5 # Copyright (c) IPython Development Team.
5 # Copyright (c) IPython Development Team.
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7
7
8 from __future__ import with_statement
8 from __future__ import with_statement
9 from __future__ import print_function
9 from __future__ import print_function
10
10
11 import sys
11 import sys
12 import warnings
12 import warnings
13
13
14 from IPython.core import ultratb, compilerop
14 from IPython.core import ultratb, compilerop
15 from IPython.core.magic import Magics, magics_class, line_magic
15 from IPython.core.magic import Magics, magics_class, line_magic
16 from IPython.core.interactiveshell import DummyMod
16 from IPython.core.interactiveshell import DummyMod
17 from IPython.core.interactiveshell import InteractiveShell
17 from IPython.core.interactiveshell import InteractiveShell
18 from IPython.terminal.interactiveshell import TerminalInteractiveShell
18 from IPython.terminal.interactiveshell import TerminalInteractiveShell
19 from IPython.terminal.ipapp import load_default_config
19 from IPython.terminal.ipapp import load_default_config
20
20
21 from traitlets import Bool, CBool, Unicode
21 from traitlets import Bool, CBool, Unicode
22 from IPython.utils.io import ask_yes_no
22 from IPython.utils.io import ask_yes_no
23
23
24
24
25 # This is an additional magic that is exposed in embedded shells.
25 # This is an additional magic that is exposed in embedded shells.
26 @magics_class
26 @magics_class
27 class EmbeddedMagics(Magics):
27 class EmbeddedMagics(Magics):
28
28
29 @line_magic
29 @line_magic
30 def kill_embedded(self, parameter_s=''):
30 def kill_embedded(self, parameter_s=''):
31 """%kill_embedded : deactivate for good the current embedded IPython.
31 """%kill_embedded : deactivate for good the current embedded IPython.
32
32
33 This function (after asking for confirmation) sets an internal flag so
33 This function (after asking for confirmation) sets an internal flag so
34 that an embedded IPython will never activate again. This is useful to
34 that an embedded IPython will never activate again. This is useful to
35 permanently disable a shell that is being called inside a loop: once
35 permanently disable a shell that is being called inside a loop: once
36 you've figured out what you needed from it, you may then kill it and
36 you've figured out what you needed from it, you may then kill it and
37 the program will then continue to run without the interactive shell
37 the program will then continue to run without the interactive shell
38 interfering again.
38 interfering again.
39 """
39 """
40
40
41 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
41 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
42 "(y/n)? [y/N] ",'n')
42 "(y/n)? [y/N] ",'n')
43 if kill:
43 if kill:
44 self.shell.embedded_active = False
44 self.shell.embedded_active = False
45 print ("This embedded IPython will not reactivate anymore "
45 print ("This embedded IPython will not reactivate anymore "
46 "once you exit.")
46 "once you exit.")
47
47
48
48
49 class InteractiveShellEmbed(TerminalInteractiveShell):
49 class InteractiveShellEmbed(TerminalInteractiveShell):
50
50
51 dummy_mode = Bool(False)
51 dummy_mode = Bool(False)
52 exit_msg = Unicode('')
52 exit_msg = Unicode('')
53 embedded = CBool(True)
53 embedded = CBool(True)
54 embedded_active = CBool(True)
54 embedded_active = CBool(True)
55 # Like the base class display_banner is not configurable, but here it
55 # Like the base class display_banner is not configurable, but here it
56 # is True by default.
56 # is True by default.
57 display_banner = CBool(True)
57 display_banner = CBool(True)
58 exit_msg = Unicode()
58 exit_msg = Unicode()
59
59
60
60
61 def __init__(self, **kw):
61 def __init__(self, **kw):
62
62
63
63
64 if kw.get('user_global_ns', None) is not None:
64 if kw.get('user_global_ns', None) is not None:
65 warnings.warn("user_global_ns has been replaced by user_module. The\
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 super(InteractiveShellEmbed,self).__init__(**kw)
68 super(InteractiveShellEmbed,self).__init__(**kw)
69
69
70 # don't use the ipython crash handler so that user exceptions aren't
70 # don't use the ipython crash handler so that user exceptions aren't
71 # trapped
71 # trapped
72 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
72 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
73 mode=self.xmode,
73 mode=self.xmode,
74 call_pdb=self.pdb)
74 call_pdb=self.pdb)
75
75
76 def init_sys_modules(self):
76 def init_sys_modules(self):
77 pass
77 pass
78
78
79 def init_magics(self):
79 def init_magics(self):
80 super(InteractiveShellEmbed, self).init_magics()
80 super(InteractiveShellEmbed, self).init_magics()
81 self.register_magics(EmbeddedMagics)
81 self.register_magics(EmbeddedMagics)
82
82
83 def __call__(self, header='', local_ns=None, module=None, dummy=None,
83 def __call__(self, header='', local_ns=None, module=None, dummy=None,
84 stack_depth=1, global_ns=None, compile_flags=None):
84 stack_depth=1, global_ns=None, compile_flags=None):
85 """Activate the interactive interpreter.
85 """Activate the interactive interpreter.
86
86
87 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
87 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
88 the interpreter shell with the given local and global namespaces, and
88 the interpreter shell with the given local and global namespaces, and
89 optionally print a header string at startup.
89 optionally print a header string at startup.
90
90
91 The shell can be globally activated/deactivated using the
91 The shell can be globally activated/deactivated using the
92 dummy_mode attribute. This allows you to turn off a shell used
92 dummy_mode attribute. This allows you to turn off a shell used
93 for debugging globally.
93 for debugging globally.
94
94
95 However, *each* time you call the shell you can override the current
95 However, *each* time you call the shell you can override the current
96 state of dummy_mode with the optional keyword parameter 'dummy'. For
96 state of dummy_mode with the optional keyword parameter 'dummy'. For
97 example, if you set dummy mode on with IPShell.dummy_mode = True, you
97 example, if you set dummy mode on with IPShell.dummy_mode = True, you
98 can still have a specific call work by making it as IPShell(dummy=False).
98 can still have a specific call work by making it as IPShell(dummy=False).
99 """
99 """
100
100
101 # If the user has turned it off, go away
101 # If the user has turned it off, go away
102 if not self.embedded_active:
102 if not self.embedded_active:
103 return
103 return
104
104
105 # Normal exits from interactive mode set this flag, so the shell can't
105 # Normal exits from interactive mode set this flag, so the shell can't
106 # re-enter (it checks this variable at the start of interactive mode).
106 # re-enter (it checks this variable at the start of interactive mode).
107 self.exit_now = False
107 self.exit_now = False
108
108
109 # Allow the dummy parameter to override the global __dummy_mode
109 # Allow the dummy parameter to override the global __dummy_mode
110 if dummy or (dummy != 0 and self.dummy_mode):
110 if dummy or (dummy != 0 and self.dummy_mode):
111 return
111 return
112
112
113 if self.has_readline:
113 if self.has_readline:
114 self.set_readline_completer()
114 self.set_readline_completer()
115
115
116 # self.banner is auto computed
116 # self.banner is auto computed
117 if header:
117 if header:
118 self.old_banner2 = self.banner2
118 self.old_banner2 = self.banner2
119 self.banner2 = self.banner2 + '\n' + header + '\n'
119 self.banner2 = self.banner2 + '\n' + header + '\n'
120 else:
120 else:
121 self.old_banner2 = ''
121 self.old_banner2 = ''
122
122
123 # Call the embedding code with a stack depth of 1 so it can skip over
123 # Call the embedding code with a stack depth of 1 so it can skip over
124 # our call and get the original caller's namespaces.
124 # our call and get the original caller's namespaces.
125 self.mainloop(local_ns, module, stack_depth=stack_depth,
125 self.mainloop(local_ns, module, stack_depth=stack_depth,
126 global_ns=global_ns, compile_flags=compile_flags)
126 global_ns=global_ns, compile_flags=compile_flags)
127
127
128 self.banner2 = self.old_banner2
128 self.banner2 = self.old_banner2
129
129
130 if self.exit_msg is not None:
130 if self.exit_msg is not None:
131 print(self.exit_msg)
131 print(self.exit_msg)
132
132
133 def mainloop(self, local_ns=None, module=None, stack_depth=0,
133 def mainloop(self, local_ns=None, module=None, stack_depth=0,
134 display_banner=None, global_ns=None, compile_flags=None):
134 display_banner=None, global_ns=None, compile_flags=None):
135 """Embeds IPython into a running python program.
135 """Embeds IPython into a running python program.
136
136
137 Parameters
137 Parameters
138 ----------
138 ----------
139
139
140 local_ns, module
140 local_ns, module
141 Working local namespace (a dict) and module (a module or similar
141 Working local namespace (a dict) and module (a module or similar
142 object). If given as None, they are automatically taken from the scope
142 object). If given as None, they are automatically taken from the scope
143 where the shell was called, so that program variables become visible.
143 where the shell was called, so that program variables become visible.
144
144
145 stack_depth : int
145 stack_depth : int
146 How many levels in the stack to go to looking for namespaces (when
146 How many levels in the stack to go to looking for namespaces (when
147 local_ns or module is None). This allows an intermediate caller to
147 local_ns or module is None). This allows an intermediate caller to
148 make sure that this function gets the namespace from the intended
148 make sure that this function gets the namespace from the intended
149 level in the stack. By default (0) it will get its locals and globals
149 level in the stack. By default (0) it will get its locals and globals
150 from the immediate caller.
150 from the immediate caller.
151
151
152 compile_flags
152 compile_flags
153 A bit field identifying the __future__ features
153 A bit field identifying the __future__ features
154 that are enabled, as passed to the builtin :func:`compile` function.
154 that are enabled, as passed to the builtin :func:`compile` function.
155 If given as None, they are automatically taken from the scope where
155 If given as None, they are automatically taken from the scope where
156 the shell was called.
156 the shell was called.
157
157
158 """
158 """
159
159
160 if (global_ns is not None) and (module is None):
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 module = DummyMod()
162 module = DummyMod()
163 module.__dict__ = global_ns
163 module.__dict__ = global_ns
164
164
165 # Get locals and globals from caller
165 # Get locals and globals from caller
166 if ((local_ns is None or module is None or compile_flags is None)
166 if ((local_ns is None or module is None or compile_flags is None)
167 and self.default_user_namespaces):
167 and self.default_user_namespaces):
168 call_frame = sys._getframe(stack_depth).f_back
168 call_frame = sys._getframe(stack_depth).f_back
169
169
170 if local_ns is None:
170 if local_ns is None:
171 local_ns = call_frame.f_locals
171 local_ns = call_frame.f_locals
172 if module is None:
172 if module is None:
173 global_ns = call_frame.f_globals
173 global_ns = call_frame.f_globals
174 module = sys.modules[global_ns['__name__']]
174 module = sys.modules[global_ns['__name__']]
175 if compile_flags is None:
175 if compile_flags is None:
176 compile_flags = (call_frame.f_code.co_flags &
176 compile_flags = (call_frame.f_code.co_flags &
177 compilerop.PyCF_MASK)
177 compilerop.PyCF_MASK)
178
178
179 # Save original namespace and module so we can restore them after
179 # Save original namespace and module so we can restore them after
180 # embedding; otherwise the shell doesn't shut down correctly.
180 # embedding; otherwise the shell doesn't shut down correctly.
181 orig_user_module = self.user_module
181 orig_user_module = self.user_module
182 orig_user_ns = self.user_ns
182 orig_user_ns = self.user_ns
183 orig_compile_flags = self.compile.flags
183 orig_compile_flags = self.compile.flags
184
184
185 # Update namespaces and fire up interpreter
185 # Update namespaces and fire up interpreter
186
186
187 # The global one is easy, we can just throw it in
187 # The global one is easy, we can just throw it in
188 if module is not None:
188 if module is not None:
189 self.user_module = module
189 self.user_module = module
190
190
191 # But the user/local one is tricky: ipython needs it to store internal
191 # But the user/local one is tricky: ipython needs it to store internal
192 # data, but we also need the locals. We'll throw our hidden variables
192 # data, but we also need the locals. We'll throw our hidden variables
193 # like _ih and get_ipython() into the local namespace, but delete them
193 # like _ih and get_ipython() into the local namespace, but delete them
194 # later.
194 # later.
195 if local_ns is not None:
195 if local_ns is not None:
196 reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
196 reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
197 self.user_ns = reentrant_local_ns
197 self.user_ns = reentrant_local_ns
198 self.init_user_ns()
198 self.init_user_ns()
199
199
200 # Compiler flags
200 # Compiler flags
201 if compile_flags is not None:
201 if compile_flags is not None:
202 self.compile.flags = compile_flags
202 self.compile.flags = compile_flags
203
203
204 # make sure the tab-completer has the correct frame information, so it
204 # make sure the tab-completer has the correct frame information, so it
205 # actually completes using the frame's locals/globals
205 # actually completes using the frame's locals/globals
206 self.set_completer_frame()
206 self.set_completer_frame()
207
207
208 with self.builtin_trap, self.display_trap:
208 with self.builtin_trap, self.display_trap:
209 self.interact(display_banner=display_banner)
209 self.interact(display_banner=display_banner)
210
210
211 # now, purge out the local namespace of IPython's hidden variables.
211 # now, purge out the local namespace of IPython's hidden variables.
212 if local_ns is not None:
212 if local_ns is not None:
213 local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
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 # Restore original namespace so shell can shut down when we exit.
216 # Restore original namespace so shell can shut down when we exit.
217 self.user_module = orig_user_module
217 self.user_module = orig_user_module
218 self.user_ns = orig_user_ns
218 self.user_ns = orig_user_ns
219 self.compile.flags = orig_compile_flags
219 self.compile.flags = orig_compile_flags
220
220
221
221
222 def embed(**kwargs):
222 def embed(**kwargs):
223 """Call this to embed IPython at the current point in your program.
223 """Call this to embed IPython at the current point in your program.
224
224
225 The first invocation of this will create an :class:`InteractiveShellEmbed`
225 The first invocation of this will create an :class:`InteractiveShellEmbed`
226 instance and then call it. Consecutive calls just call the already
226 instance and then call it. Consecutive calls just call the already
227 created instance.
227 created instance.
228
228
229 If you don't want the kernel to initialize the namespace
229 If you don't want the kernel to initialize the namespace
230 from the scope of the surrounding function,
230 from the scope of the surrounding function,
231 and/or you want to load full IPython configuration,
231 and/or you want to load full IPython configuration,
232 you probably want `IPython.start_ipython()` instead.
232 you probably want `IPython.start_ipython()` instead.
233
233
234 Here is a simple example::
234 Here is a simple example::
235
235
236 from IPython import embed
236 from IPython import embed
237 a = 10
237 a = 10
238 b = 20
238 b = 20
239 embed(header='First time')
239 embed(header='First time')
240 c = 30
240 c = 30
241 d = 40
241 d = 40
242 embed()
242 embed()
243
243
244 Full customization can be done by passing a :class:`Config` in as the
244 Full customization can be done by passing a :class:`Config` in as the
245 config argument.
245 config argument.
246 """
246 """
247 config = kwargs.get('config')
247 config = kwargs.get('config')
248 header = kwargs.pop('header', u'')
248 header = kwargs.pop('header', u'')
249 compile_flags = kwargs.pop('compile_flags', None)
249 compile_flags = kwargs.pop('compile_flags', None)
250 if config is None:
250 if config is None:
251 config = load_default_config()
251 config = load_default_config()
252 config.InteractiveShellEmbed = config.TerminalInteractiveShell
252 config.InteractiveShellEmbed = config.TerminalInteractiveShell
253 kwargs['config'] = config
253 kwargs['config'] = config
254 #save ps1/ps2 if defined
254 #save ps1/ps2 if defined
255 ps1 = None
255 ps1 = None
256 ps2 = None
256 ps2 = None
257 try:
257 try:
258 ps1 = sys.ps1
258 ps1 = sys.ps1
259 ps2 = sys.ps2
259 ps2 = sys.ps2
260 except AttributeError:
260 except AttributeError:
261 pass
261 pass
262 #save previous instance
262 #save previous instance
263 saved_shell_instance = InteractiveShell._instance
263 saved_shell_instance = InteractiveShell._instance
264 if saved_shell_instance is not None:
264 if saved_shell_instance is not None:
265 cls = type(saved_shell_instance)
265 cls = type(saved_shell_instance)
266 cls.clear_instance()
266 cls.clear_instance()
267 shell = InteractiveShellEmbed.instance(**kwargs)
267 shell = InteractiveShellEmbed.instance(**kwargs)
268 shell(header=header, stack_depth=2, compile_flags=compile_flags)
268 shell(header=header, stack_depth=2, compile_flags=compile_flags)
269 InteractiveShellEmbed.clear_instance()
269 InteractiveShellEmbed.clear_instance()
270 #restore previous instance
270 #restore previous instance
271 if saved_shell_instance is not None:
271 if saved_shell_instance is not None:
272 cls = type(saved_shell_instance)
272 cls = type(saved_shell_instance)
273 cls.clear_instance()
273 cls.clear_instance()
274 for subclass in cls._walk_mro():
274 for subclass in cls._walk_mro():
275 subclass._instance = saved_shell_instance
275 subclass._instance = saved_shell_instance
276 if ps1 is not None:
276 if ps1 is not None:
277 sys.ps1 = ps1
277 sys.ps1 = ps1
278 sys.ps2 = ps2
278 sys.ps2 = ps2
@@ -1,369 +1,369 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6 """
6 """
7
7
8 # Copyright (c) IPython Development Team.
8 # Copyright (c) IPython Development Team.
9 # Distributed under the terms of the Modified BSD License.
9 # Distributed under the terms of the Modified BSD License.
10
10
11 from __future__ import absolute_import
11 from __future__ import absolute_import
12 from __future__ import print_function
12 from __future__ import print_function
13
13
14 import logging
14 import logging
15 import os
15 import os
16 import sys
16 import sys
17
17
18 from traitlets.config.loader import Config
18 from traitlets.config.loader import Config
19 from traitlets.config.application import boolean_flag, catch_config_error, Application
19 from traitlets.config.application import boolean_flag, catch_config_error, Application
20 from IPython.core import release
20 from IPython.core import release
21 from IPython.core import usage
21 from IPython.core import usage
22 from IPython.core.completer import IPCompleter
22 from IPython.core.completer import IPCompleter
23 from IPython.core.crashhandler import CrashHandler
23 from IPython.core.crashhandler import CrashHandler
24 from IPython.core.formatters import PlainTextFormatter
24 from IPython.core.formatters import PlainTextFormatter
25 from IPython.core.history import HistoryManager
25 from IPython.core.history import HistoryManager
26 from IPython.core.prompts import PromptManager
26 from IPython.core.prompts import PromptManager
27 from IPython.core.application import (
27 from IPython.core.application import (
28 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
28 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
29 )
29 )
30 from IPython.core.magics import ScriptMagics
30 from IPython.core.magics import ScriptMagics
31 from IPython.core.shellapp import (
31 from IPython.core.shellapp import (
32 InteractiveShellApp, shell_flags, shell_aliases
32 InteractiveShellApp, shell_flags, shell_aliases
33 )
33 )
34 from IPython.extensions.storemagic import StoreMagics
34 from IPython.extensions.storemagic import StoreMagics
35 from IPython.terminal.interactiveshell import TerminalInteractiveShell
35 from IPython.terminal.interactiveshell import TerminalInteractiveShell
36 from IPython.utils import warn
36 from IPython.utils import warn
37 from IPython.paths import get_ipython_dir
37 from IPython.paths import get_ipython_dir
38 from traitlets import (
38 from traitlets import (
39 Bool, List, Dict,
39 Bool, List, Dict,
40 )
40 )
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # Globals, utilities and helpers
43 # Globals, utilities and helpers
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45
45
46 _examples = """
46 _examples = """
47 ipython --matplotlib # enable matplotlib integration
47 ipython --matplotlib # enable matplotlib integration
48 ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
48 ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
49
49
50 ipython --log-level=DEBUG # set logging to DEBUG
50 ipython --log-level=DEBUG # set logging to DEBUG
51 ipython --profile=foo # start with profile foo
51 ipython --profile=foo # start with profile foo
52
52
53 ipython profile create foo # create profile foo w/ default config files
53 ipython profile create foo # create profile foo w/ default config files
54 ipython help profile # show the help for the profile subcmd
54 ipython help profile # show the help for the profile subcmd
55
55
56 ipython locate # print the path to the IPython directory
56 ipython locate # print the path to the IPython directory
57 ipython locate profile foo # print the path to the directory for profile `foo`
57 ipython locate profile foo # print the path to the directory for profile `foo`
58 """
58 """
59
59
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61 # Crash handler for this application
61 # Crash handler for this application
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63
63
64 class IPAppCrashHandler(CrashHandler):
64 class IPAppCrashHandler(CrashHandler):
65 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
65 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
66
66
67 def __init__(self, app):
67 def __init__(self, app):
68 contact_name = release.author
68 contact_name = release.author
69 contact_email = release.author_email
69 contact_email = release.author_email
70 bug_tracker = 'https://github.com/ipython/ipython/issues'
70 bug_tracker = 'https://github.com/ipython/ipython/issues'
71 super(IPAppCrashHandler,self).__init__(
71 super(IPAppCrashHandler,self).__init__(
72 app, contact_name, contact_email, bug_tracker
72 app, contact_name, contact_email, bug_tracker
73 )
73 )
74
74
75 def make_report(self,traceback):
75 def make_report(self,traceback):
76 """Return a string containing a crash report."""
76 """Return a string containing a crash report."""
77
77
78 sec_sep = self.section_sep
78 sec_sep = self.section_sep
79 # Start with parent report
79 # Start with parent report
80 report = [super(IPAppCrashHandler, self).make_report(traceback)]
80 report = [super(IPAppCrashHandler, self).make_report(traceback)]
81 # Add interactive-specific info we may have
81 # Add interactive-specific info we may have
82 rpt_add = report.append
82 rpt_add = report.append
83 try:
83 try:
84 rpt_add(sec_sep+"History of session input:")
84 rpt_add(sec_sep+"History of session input:")
85 for line in self.app.shell.user_ns['_ih']:
85 for line in self.app.shell.user_ns['_ih']:
86 rpt_add(line)
86 rpt_add(line)
87 rpt_add('\n*** Last line of input (may not be in above history):\n')
87 rpt_add('\n*** Last line of input (may not be in above history):\n')
88 rpt_add(self.app.shell._last_input_line+'\n')
88 rpt_add(self.app.shell._last_input_line+'\n')
89 except:
89 except:
90 pass
90 pass
91
91
92 return ''.join(report)
92 return ''.join(report)
93
93
94 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
95 # Aliases and Flags
95 # Aliases and Flags
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97 flags = dict(base_flags)
97 flags = dict(base_flags)
98 flags.update(shell_flags)
98 flags.update(shell_flags)
99 frontend_flags = {}
99 frontend_flags = {}
100 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
100 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
101 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
101 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
102 'Turn on auto editing of files with syntax errors.',
102 'Turn on auto editing of files with syntax errors.',
103 'Turn off auto editing of files with syntax errors.'
103 'Turn off auto editing of files with syntax errors.'
104 )
104 )
105 addflag('banner', 'TerminalIPythonApp.display_banner',
105 addflag('banner', 'TerminalIPythonApp.display_banner',
106 "Display a banner upon starting IPython.",
106 "Display a banner upon starting IPython.",
107 "Don't display a banner upon starting IPython."
107 "Don't display a banner upon starting IPython."
108 )
108 )
109 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
109 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
110 """Set to confirm when you try to exit IPython with an EOF (Control-D
110 """Set to confirm when you try to exit IPython with an EOF (Control-D
111 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
111 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
112 you can force a direct exit without any confirmation.""",
112 you can force a direct exit without any confirmation.""",
113 "Don't prompt the user when exiting."
113 "Don't prompt the user when exiting."
114 )
114 )
115 addflag('term-title', 'TerminalInteractiveShell.term_title',
115 addflag('term-title', 'TerminalInteractiveShell.term_title',
116 "Enable auto setting the terminal title.",
116 "Enable auto setting the terminal title.",
117 "Disable auto setting the terminal title."
117 "Disable auto setting the terminal title."
118 )
118 )
119 classic_config = Config()
119 classic_config = Config()
120 classic_config.InteractiveShell.cache_size = 0
120 classic_config.InteractiveShell.cache_size = 0
121 classic_config.PlainTextFormatter.pprint = False
121 classic_config.PlainTextFormatter.pprint = False
122 classic_config.PromptManager.in_template = '>>> '
122 classic_config.PromptManager.in_template = '>>> '
123 classic_config.PromptManager.in2_template = '... '
123 classic_config.PromptManager.in2_template = '... '
124 classic_config.PromptManager.out_template = ''
124 classic_config.PromptManager.out_template = ''
125 classic_config.InteractiveShell.separate_in = ''
125 classic_config.InteractiveShell.separate_in = ''
126 classic_config.InteractiveShell.separate_out = ''
126 classic_config.InteractiveShell.separate_out = ''
127 classic_config.InteractiveShell.separate_out2 = ''
127 classic_config.InteractiveShell.separate_out2 = ''
128 classic_config.InteractiveShell.colors = 'NoColor'
128 classic_config.InteractiveShell.colors = 'NoColor'
129 classic_config.InteractiveShell.xmode = 'Plain'
129 classic_config.InteractiveShell.xmode = 'Plain'
130
130
131 frontend_flags['classic']=(
131 frontend_flags['classic']=(
132 classic_config,
132 classic_config,
133 "Gives IPython a similar feel to the classic Python prompt."
133 "Gives IPython a similar feel to the classic Python prompt."
134 )
134 )
135 # # log doesn't make so much sense this way anymore
135 # # log doesn't make so much sense this way anymore
136 # paa('--log','-l',
136 # paa('--log','-l',
137 # action='store_true', dest='InteractiveShell.logstart',
137 # action='store_true', dest='InteractiveShell.logstart',
138 # help="Start logging to the default log file (./ipython_log.py).")
138 # help="Start logging to the default log file (./ipython_log.py).")
139 #
139 #
140 # # quick is harder to implement
140 # # quick is harder to implement
141 frontend_flags['quick']=(
141 frontend_flags['quick']=(
142 {'TerminalIPythonApp' : {'quick' : True}},
142 {'TerminalIPythonApp' : {'quick' : True}},
143 "Enable quick startup with no config files."
143 "Enable quick startup with no config files."
144 )
144 )
145
145
146 frontend_flags['i'] = (
146 frontend_flags['i'] = (
147 {'TerminalIPythonApp' : {'force_interact' : True}},
147 {'TerminalIPythonApp' : {'force_interact' : True}},
148 """If running code from the command line, become interactive afterwards.
148 """If running code from the command line, become interactive afterwards.
149 It is often useful to follow this with `--` to treat remaining flags as
149 It is often useful to follow this with `--` to treat remaining flags as
150 script arguments.
150 script arguments.
151 """
151 """
152 )
152 )
153 flags.update(frontend_flags)
153 flags.update(frontend_flags)
154
154
155 aliases = dict(base_aliases)
155 aliases = dict(base_aliases)
156 aliases.update(shell_aliases)
156 aliases.update(shell_aliases)
157
157
158 #-----------------------------------------------------------------------------
158 #-----------------------------------------------------------------------------
159 # Main classes and functions
159 # Main classes and functions
160 #-----------------------------------------------------------------------------
160 #-----------------------------------------------------------------------------
161
161
162
162
163 class LocateIPythonApp(BaseIPythonApplication):
163 class LocateIPythonApp(BaseIPythonApplication):
164 description = """print the path to the IPython dir"""
164 description = """print the path to the IPython dir"""
165 subcommands = Dict(dict(
165 subcommands = Dict(dict(
166 profile=('IPython.core.profileapp.ProfileLocate',
166 profile=('IPython.core.profileapp.ProfileLocate',
167 "print the path to an IPython profile directory",
167 "print the path to an IPython profile directory",
168 ),
168 ),
169 ))
169 ))
170 def start(self):
170 def start(self):
171 if self.subapp is not None:
171 if self.subapp is not None:
172 return self.subapp.start()
172 return self.subapp.start()
173 else:
173 else:
174 print(self.ipython_dir)
174 print(self.ipython_dir)
175
175
176
176
177 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
177 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
178 name = u'ipython'
178 name = u'ipython'
179 description = usage.cl_usage
179 description = usage.cl_usage
180 crash_handler_class = IPAppCrashHandler
180 crash_handler_class = IPAppCrashHandler
181 examples = _examples
181 examples = _examples
182
182
183 flags = Dict(flags)
183 flags = Dict(flags)
184 aliases = Dict(aliases)
184 aliases = Dict(aliases)
185 classes = List()
185 classes = List()
186 def _classes_default(self):
186 def _classes_default(self):
187 """This has to be in a method, for TerminalIPythonApp to be available."""
187 """This has to be in a method, for TerminalIPythonApp to be available."""
188 return [
188 return [
189 InteractiveShellApp, # ShellApp comes before TerminalApp, because
189 InteractiveShellApp, # ShellApp comes before TerminalApp, because
190 self.__class__, # it will also affect subclasses (e.g. QtConsole)
190 self.__class__, # it will also affect subclasses (e.g. QtConsole)
191 TerminalInteractiveShell,
191 TerminalInteractiveShell,
192 PromptManager,
192 PromptManager,
193 HistoryManager,
193 HistoryManager,
194 ProfileDir,
194 ProfileDir,
195 PlainTextFormatter,
195 PlainTextFormatter,
196 IPCompleter,
196 IPCompleter,
197 ScriptMagics,
197 ScriptMagics,
198 StoreMagics,
198 StoreMagics,
199 ]
199 ]
200
200
201 deprecated_subcommands = dict(
201 deprecated_subcommands = dict(
202 qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp',
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 notebook=('notebook.notebookapp.NotebookApp',
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 console=('jupyter_console.app.ZMQTerminalIPythonApp',
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 nbconvert=('nbconvert.nbconvertapp.NbConvertApp',
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 trust=('nbformat.sign.TrustNotebookApp',
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 kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp',
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 subcommands = dict(
221 subcommands = dict(
222 profile = ("IPython.core.profileapp.ProfileApp",
222 profile = ("IPython.core.profileapp.ProfileApp",
223 "Create and manage IPython profiles."
223 "Create and manage IPython profiles."
224 ),
224 ),
225 kernel = ("ipykernel.kernelapp.IPKernelApp",
225 kernel = ("ipykernel.kernelapp.IPKernelApp",
226 "Start a kernel without an attached frontend."
226 "Start a kernel without an attached frontend."
227 ),
227 ),
228 locate=('IPython.terminal.ipapp.LocateIPythonApp',
228 locate=('IPython.terminal.ipapp.LocateIPythonApp',
229 LocateIPythonApp.description
229 LocateIPythonApp.description
230 ),
230 ),
231 history=('IPython.core.historyapp.HistoryApp',
231 history=('IPython.core.historyapp.HistoryApp',
232 "Manage the IPython history database."
232 "Manage the IPython history database."
233 ),
233 ),
234 )
234 )
235 deprecated_subcommands['install-nbextension'] = (
235 deprecated_subcommands['install-nbextension'] = (
236 "notebook.nbextensions.InstallNBExtensionApp",
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 subcommands.update(deprecated_subcommands)
239 subcommands.update(deprecated_subcommands)
240
240
241 # *do* autocreate requested profile, but don't create the config file.
241 # *do* autocreate requested profile, but don't create the config file.
242 auto_create=Bool(True)
242 auto_create=Bool(True)
243 # configurables
243 # configurables
244 quick = Bool(False, config=True,
244 quick = Bool(False, config=True,
245 help="""Start IPython quickly by skipping the loading of config files."""
245 help="""Start IPython quickly by skipping the loading of config files."""
246 )
246 )
247 def _quick_changed(self, name, old, new):
247 def _quick_changed(self, name, old, new):
248 if new:
248 if new:
249 self.load_config_file = lambda *a, **kw: None
249 self.load_config_file = lambda *a, **kw: None
250
250
251 display_banner = Bool(True, config=True,
251 display_banner = Bool(True, config=True,
252 help="Whether to display a banner upon starting IPython."
252 help="Whether to display a banner upon starting IPython."
253 )
253 )
254
254
255 # if there is code of files to run from the cmd line, don't interact
255 # if there is code of files to run from the cmd line, don't interact
256 # unless the --i flag (App.force_interact) is true.
256 # unless the --i flag (App.force_interact) is true.
257 force_interact = Bool(False, config=True,
257 force_interact = Bool(False, config=True,
258 help="""If a command or file is given via the command-line,
258 help="""If a command or file is given via the command-line,
259 e.g. 'ipython foo.py', start an interactive shell after executing the
259 e.g. 'ipython foo.py', start an interactive shell after executing the
260 file or command."""
260 file or command."""
261 )
261 )
262 def _force_interact_changed(self, name, old, new):
262 def _force_interact_changed(self, name, old, new):
263 if new:
263 if new:
264 self.interact = True
264 self.interact = True
265
265
266 def _file_to_run_changed(self, name, old, new):
266 def _file_to_run_changed(self, name, old, new):
267 if new:
267 if new:
268 self.something_to_run = True
268 self.something_to_run = True
269 if new and not self.force_interact:
269 if new and not self.force_interact:
270 self.interact = False
270 self.interact = False
271 _code_to_run_changed = _file_to_run_changed
271 _code_to_run_changed = _file_to_run_changed
272 _module_to_run_changed = _file_to_run_changed
272 _module_to_run_changed = _file_to_run_changed
273
273
274 # internal, not-configurable
274 # internal, not-configurable
275 interact=Bool(True)
275 interact=Bool(True)
276 something_to_run=Bool(False)
276 something_to_run=Bool(False)
277
277
278 def parse_command_line(self, argv=None):
278 def parse_command_line(self, argv=None):
279 """override to allow old '-pylab' flag with deprecation warning"""
279 """override to allow old '-pylab' flag with deprecation warning"""
280
280
281 argv = sys.argv[1:] if argv is None else argv
281 argv = sys.argv[1:] if argv is None else argv
282
282
283 if '-pylab' in argv:
283 if '-pylab' in argv:
284 # deprecated `-pylab` given,
284 # deprecated `-pylab` given,
285 # warn and transform into current syntax
285 # warn and transform into current syntax
286 argv = argv[:] # copy, don't clobber
286 argv = argv[:] # copy, don't clobber
287 idx = argv.index('-pylab')
287 idx = argv.index('-pylab')
288 warn.warn("`-pylab` flag has been deprecated.\n"
288 warn.warn("`-pylab` flag has been deprecated.\n"
289 " Use `--matplotlib <backend>` and import pylab manually.")
289 " Use `--matplotlib <backend>` and import pylab manually.")
290 argv[idx] = '--pylab'
290 argv[idx] = '--pylab'
291
291
292 return super(TerminalIPythonApp, self).parse_command_line(argv)
292 return super(TerminalIPythonApp, self).parse_command_line(argv)
293
293
294 @catch_config_error
294 @catch_config_error
295 def initialize(self, argv=None):
295 def initialize(self, argv=None):
296 """Do actions after construct, but before starting the app."""
296 """Do actions after construct, but before starting the app."""
297 super(TerminalIPythonApp, self).initialize(argv)
297 super(TerminalIPythonApp, self).initialize(argv)
298 if self.subapp is not None:
298 if self.subapp is not None:
299 # don't bother initializing further, starting subapp
299 # don't bother initializing further, starting subapp
300 return
300 return
301 # print self.extra_args
301 # print self.extra_args
302 if self.extra_args and not self.something_to_run:
302 if self.extra_args and not self.something_to_run:
303 self.file_to_run = self.extra_args[0]
303 self.file_to_run = self.extra_args[0]
304 self.init_path()
304 self.init_path()
305 # create the shell
305 # create the shell
306 self.init_shell()
306 self.init_shell()
307 # and draw the banner
307 # and draw the banner
308 self.init_banner()
308 self.init_banner()
309 # Now a variety of things that happen after the banner is printed.
309 # Now a variety of things that happen after the banner is printed.
310 self.init_gui_pylab()
310 self.init_gui_pylab()
311 self.init_extensions()
311 self.init_extensions()
312 self.init_code()
312 self.init_code()
313
313
314 def init_shell(self):
314 def init_shell(self):
315 """initialize the InteractiveShell instance"""
315 """initialize the InteractiveShell instance"""
316 # Create an InteractiveShell instance.
316 # Create an InteractiveShell instance.
317 # shell.display_banner should always be False for the terminal
317 # shell.display_banner should always be False for the terminal
318 # based app, because we call shell.show_banner() by hand below
318 # based app, because we call shell.show_banner() by hand below
319 # so the banner shows *before* all extension loading stuff.
319 # so the banner shows *before* all extension loading stuff.
320 self.shell = TerminalInteractiveShell.instance(parent=self,
320 self.shell = TerminalInteractiveShell.instance(parent=self,
321 display_banner=False, profile_dir=self.profile_dir,
321 display_banner=False, profile_dir=self.profile_dir,
322 ipython_dir=self.ipython_dir, user_ns=self.user_ns)
322 ipython_dir=self.ipython_dir, user_ns=self.user_ns)
323 self.shell.configurables.append(self)
323 self.shell.configurables.append(self)
324
324
325 def init_banner(self):
325 def init_banner(self):
326 """optionally display the banner"""
326 """optionally display the banner"""
327 if self.display_banner and self.interact:
327 if self.display_banner and self.interact:
328 self.shell.show_banner()
328 self.shell.show_banner()
329 # Make sure there is a space below the banner.
329 # Make sure there is a space below the banner.
330 if self.log_level <= logging.INFO: print()
330 if self.log_level <= logging.INFO: print()
331
331
332 def _pylab_changed(self, name, old, new):
332 def _pylab_changed(self, name, old, new):
333 """Replace --pylab='inline' with --pylab='auto'"""
333 """Replace --pylab='inline' with --pylab='auto'"""
334 if new == 'inline':
334 if new == 'inline':
335 warn.warn("'inline' not available as pylab backend, "
335 warn.warn("'inline' not available as pylab backend, "
336 "using 'auto' instead.")
336 "using 'auto' instead.")
337 self.pylab = 'auto'
337 self.pylab = 'auto'
338
338
339 def start(self):
339 def start(self):
340 if self.subapp is not None:
340 if self.subapp is not None:
341 return self.subapp.start()
341 return self.subapp.start()
342 # perform any prexec steps:
342 # perform any prexec steps:
343 if self.interact:
343 if self.interact:
344 self.log.debug("Starting IPython's mainloop...")
344 self.log.debug("Starting IPython's mainloop...")
345 self.shell.mainloop()
345 self.shell.mainloop()
346 else:
346 else:
347 self.log.debug("IPython not interactive...")
347 self.log.debug("IPython not interactive...")
348
348
349 def load_default_config(ipython_dir=None):
349 def load_default_config(ipython_dir=None):
350 """Load the default config file from the default ipython_dir.
350 """Load the default config file from the default ipython_dir.
351
351
352 This is useful for embedded shells.
352 This is useful for embedded shells.
353 """
353 """
354 if ipython_dir is None:
354 if ipython_dir is None:
355 ipython_dir = get_ipython_dir()
355 ipython_dir = get_ipython_dir()
356
356
357 profile_dir = os.path.join(ipython_dir, 'profile_default')
357 profile_dir = os.path.join(ipython_dir, 'profile_default')
358
358
359 config = Config()
359 config = Config()
360 for cf in Application._load_config_files("ipython_config", path=profile_dir):
360 for cf in Application._load_config_files("ipython_config", path=profile_dir):
361 config.update(cf)
361 config.update(cf)
362
362
363 return config
363 return config
364
364
365 launch_new_instance = TerminalIPythonApp.launch_instance
365 launch_new_instance = TerminalIPythonApp.launch_instance
366
366
367
367
368 if __name__ == '__main__':
368 if __name__ == '__main__':
369 launch_new_instance()
369 launch_new_instance()
@@ -1,379 +1,379 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Decorators for labeling test objects.
2 """Decorators for labeling test objects.
3
3
4 Decorators that merely return a modified version of the original function
4 Decorators that merely return a modified version of the original function
5 object are straightforward. Decorators that return a new function object need
5 object are straightforward. Decorators that return a new function object need
6 to use nose.tools.make_decorator(original_function)(decorator) in returning the
6 to use nose.tools.make_decorator(original_function)(decorator) in returning the
7 decorator, in order to preserve metadata such as function name, setup and
7 decorator, in order to preserve metadata such as function name, setup and
8 teardown functions and so on - see nose.tools for more information.
8 teardown functions and so on - see nose.tools for more information.
9
9
10 This module provides a set of useful decorators meant to be ready to use in
10 This module provides a set of useful decorators meant to be ready to use in
11 your own tests. See the bottom of the file for the ready-made ones, and if you
11 your own tests. See the bottom of the file for the ready-made ones, and if you
12 find yourself writing a new one that may be of generic use, add it here.
12 find yourself writing a new one that may be of generic use, add it here.
13
13
14 Included decorators:
14 Included decorators:
15
15
16
16
17 Lightweight testing that remains unittest-compatible.
17 Lightweight testing that remains unittest-compatible.
18
18
19 - An @as_unittest decorator can be used to tag any normal parameter-less
19 - An @as_unittest decorator can be used to tag any normal parameter-less
20 function as a unittest TestCase. Then, both nose and normal unittest will
20 function as a unittest TestCase. Then, both nose and normal unittest will
21 recognize it as such. This will make it easier to migrate away from Nose if
21 recognize it as such. This will make it easier to migrate away from Nose if
22 we ever need/want to while maintaining very lightweight tests.
22 we ever need/want to while maintaining very lightweight tests.
23
23
24 NOTE: This file contains IPython-specific decorators. Using the machinery in
24 NOTE: This file contains IPython-specific decorators. Using the machinery in
25 IPython.external.decorators, we import either numpy.testing.decorators if numpy is
25 IPython.external.decorators, we import either numpy.testing.decorators if numpy is
26 available, OR use equivalent code in IPython.external._decorators, which
26 available, OR use equivalent code in IPython.external._decorators, which
27 we've copied verbatim from numpy.
27 we've copied verbatim from numpy.
28
28
29 """
29 """
30
30
31 # Copyright (c) IPython Development Team.
31 # Copyright (c) IPython Development Team.
32 # Distributed under the terms of the Modified BSD License.
32 # Distributed under the terms of the Modified BSD License.
33
33
34 import sys
34 import sys
35 import os
35 import os
36 import tempfile
36 import tempfile
37 import unittest
37 import unittest
38 import warnings
38 import warnings
39
39
40 from decorator import decorator
40 from decorator import decorator
41
41
42 # Expose the unittest-driven decorators
42 # Expose the unittest-driven decorators
43 from .ipunittest import ipdoctest, ipdocstring
43 from .ipunittest import ipdoctest, ipdocstring
44
44
45 # Grab the numpy-specific decorators which we keep in a file that we
45 # Grab the numpy-specific decorators which we keep in a file that we
46 # occasionally update from upstream: decorators.py is a copy of
46 # occasionally update from upstream: decorators.py is a copy of
47 # numpy.testing.decorators, we expose all of it here.
47 # numpy.testing.decorators, we expose all of it here.
48 from IPython.external.decorators import *
48 from IPython.external.decorators import *
49
49
50 # For onlyif_cmd_exists decorator
50 # For onlyif_cmd_exists decorator
51 from IPython.utils.py3compat import string_types, which, PY2, PY3
51 from IPython.utils.py3compat import string_types, which, PY2, PY3
52
52
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54 # Classes and functions
54 # Classes and functions
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56
56
57 # Simple example of the basic idea
57 # Simple example of the basic idea
58 def as_unittest(func):
58 def as_unittest(func):
59 """Decorator to make a simple function into a normal test via unittest."""
59 """Decorator to make a simple function into a normal test via unittest."""
60 class Tester(unittest.TestCase):
60 class Tester(unittest.TestCase):
61 def test(self):
61 def test(self):
62 func()
62 func()
63
63
64 Tester.__name__ = func.__name__
64 Tester.__name__ = func.__name__
65
65
66 return Tester
66 return Tester
67
67
68 # Utility functions
68 # Utility functions
69
69
70 def apply_wrapper(wrapper,func):
70 def apply_wrapper(wrapper,func):
71 """Apply a wrapper to a function for decoration.
71 """Apply a wrapper to a function for decoration.
72
72
73 This mixes Michele Simionato's decorator tool with nose's make_decorator,
73 This mixes Michele Simionato's decorator tool with nose's make_decorator,
74 to apply a wrapper in a decorator so that all nose attributes, as well as
74 to apply a wrapper in a decorator so that all nose attributes, as well as
75 function signature and other properties, survive the decoration cleanly.
75 function signature and other properties, survive the decoration cleanly.
76 This will ensure that wrapped functions can still be well introspected via
76 This will ensure that wrapped functions can still be well introspected via
77 IPython, for example.
77 IPython, for example.
78 """
78 """
79 warnings.warn("The function `apply_wrapper` is deprecated and might be removed in next major version of IPython", DeprecationWarning)
79 warnings.warn("The function `apply_wrapper` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
80
80
81 import nose.tools
81 import nose.tools
82
82
83 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
83 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
84
84
85
85
86 def make_label_dec(label,ds=None):
86 def make_label_dec(label,ds=None):
87 """Factory function to create a decorator that applies one or more labels.
87 """Factory function to create a decorator that applies one or more labels.
88
88
89 Parameters
89 Parameters
90 ----------
90 ----------
91 label : string or sequence
91 label : string or sequence
92 One or more labels that will be applied by the decorator to the functions
92 One or more labels that will be applied by the decorator to the functions
93 it decorates. Labels are attributes of the decorated function with their
93 it decorates. Labels are attributes of the decorated function with their
94 value set to True.
94 value set to True.
95
95
96 ds : string
96 ds : string
97 An optional docstring for the resulting decorator. If not given, a
97 An optional docstring for the resulting decorator. If not given, a
98 default docstring is auto-generated.
98 default docstring is auto-generated.
99
99
100 Returns
100 Returns
101 -------
101 -------
102 A decorator.
102 A decorator.
103
103
104 Examples
104 Examples
105 --------
105 --------
106
106
107 A simple labeling decorator:
107 A simple labeling decorator:
108
108
109 >>> slow = make_label_dec('slow')
109 >>> slow = make_label_dec('slow')
110 >>> slow.__doc__
110 >>> slow.__doc__
111 "Labels a test as 'slow'."
111 "Labels a test as 'slow'."
112
112
113 And one that uses multiple labels and a custom docstring:
113 And one that uses multiple labels and a custom docstring:
114
114
115 >>> rare = make_label_dec(['slow','hard'],
115 >>> rare = make_label_dec(['slow','hard'],
116 ... "Mix labels 'slow' and 'hard' for rare tests.")
116 ... "Mix labels 'slow' and 'hard' for rare tests.")
117 >>> rare.__doc__
117 >>> rare.__doc__
118 "Mix labels 'slow' and 'hard' for rare tests."
118 "Mix labels 'slow' and 'hard' for rare tests."
119
119
120 Now, let's test using this one:
120 Now, let's test using this one:
121 >>> @rare
121 >>> @rare
122 ... def f(): pass
122 ... def f(): pass
123 ...
123 ...
124 >>>
124 >>>
125 >>> f.slow
125 >>> f.slow
126 True
126 True
127 >>> f.hard
127 >>> f.hard
128 True
128 True
129 """
129 """
130
130
131 warnings.warn("The function `make_label_dec` is deprecated and might be removed in next major version of IPython", DeprecationWarning)
131 warnings.warn("The function `make_label_dec` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
132 if isinstance(label, string_types):
132 if isinstance(label, string_types):
133 labels = [label]
133 labels = [label]
134 else:
134 else:
135 labels = label
135 labels = label
136
136
137 # Validate that the given label(s) are OK for use in setattr() by doing a
137 # Validate that the given label(s) are OK for use in setattr() by doing a
138 # dry run on a dummy function.
138 # dry run on a dummy function.
139 tmp = lambda : None
139 tmp = lambda : None
140 for label in labels:
140 for label in labels:
141 setattr(tmp,label,True)
141 setattr(tmp,label,True)
142
142
143 # This is the actual decorator we'll return
143 # This is the actual decorator we'll return
144 def decor(f):
144 def decor(f):
145 for label in labels:
145 for label in labels:
146 setattr(f,label,True)
146 setattr(f,label,True)
147 return f
147 return f
148
148
149 # Apply the user's docstring, or autogenerate a basic one
149 # Apply the user's docstring, or autogenerate a basic one
150 if ds is None:
150 if ds is None:
151 ds = "Labels a test as %r." % label
151 ds = "Labels a test as %r." % label
152 decor.__doc__ = ds
152 decor.__doc__ = ds
153
153
154 return decor
154 return decor
155
155
156
156
157 # Inspired by numpy's skipif, but uses the full apply_wrapper utility to
157 # Inspired by numpy's skipif, but uses the full apply_wrapper utility to
158 # preserve function metadata better and allows the skip condition to be a
158 # preserve function metadata better and allows the skip condition to be a
159 # callable.
159 # callable.
160 def skipif(skip_condition, msg=None):
160 def skipif(skip_condition, msg=None):
161 ''' Make function raise SkipTest exception if skip_condition is true
161 ''' Make function raise SkipTest exception if skip_condition is true
162
162
163 Parameters
163 Parameters
164 ----------
164 ----------
165
165
166 skip_condition : bool or callable
166 skip_condition : bool or callable
167 Flag to determine whether to skip test. If the condition is a
167 Flag to determine whether to skip test. If the condition is a
168 callable, it is used at runtime to dynamically make the decision. This
168 callable, it is used at runtime to dynamically make the decision. This
169 is useful for tests that may require costly imports, to delay the cost
169 is useful for tests that may require costly imports, to delay the cost
170 until the test suite is actually executed.
170 until the test suite is actually executed.
171 msg : string
171 msg : string
172 Message to give on raising a SkipTest exception.
172 Message to give on raising a SkipTest exception.
173
173
174 Returns
174 Returns
175 -------
175 -------
176 decorator : function
176 decorator : function
177 Decorator, which, when applied to a function, causes SkipTest
177 Decorator, which, when applied to a function, causes SkipTest
178 to be raised when the skip_condition was True, and the function
178 to be raised when the skip_condition was True, and the function
179 to be called normally otherwise.
179 to be called normally otherwise.
180
180
181 Notes
181 Notes
182 -----
182 -----
183 You will see from the code that we had to further decorate the
183 You will see from the code that we had to further decorate the
184 decorator with the nose.tools.make_decorator function in order to
184 decorator with the nose.tools.make_decorator function in order to
185 transmit function name, and various other metadata.
185 transmit function name, and various other metadata.
186 '''
186 '''
187
187
188 def skip_decorator(f):
188 def skip_decorator(f):
189 # Local import to avoid a hard nose dependency and only incur the
189 # Local import to avoid a hard nose dependency and only incur the
190 # import time overhead at actual test-time.
190 # import time overhead at actual test-time.
191 import nose
191 import nose
192
192
193 # Allow for both boolean or callable skip conditions.
193 # Allow for both boolean or callable skip conditions.
194 if callable(skip_condition):
194 if callable(skip_condition):
195 skip_val = skip_condition
195 skip_val = skip_condition
196 else:
196 else:
197 skip_val = lambda : skip_condition
197 skip_val = lambda : skip_condition
198
198
199 def get_msg(func,msg=None):
199 def get_msg(func,msg=None):
200 """Skip message with information about function being skipped."""
200 """Skip message with information about function being skipped."""
201 if msg is None: out = 'Test skipped due to test condition.'
201 if msg is None: out = 'Test skipped due to test condition.'
202 else: out = msg
202 else: out = msg
203 return "Skipping test: %s. %s" % (func.__name__,out)
203 return "Skipping test: %s. %s" % (func.__name__,out)
204
204
205 # We need to define *two* skippers because Python doesn't allow both
205 # We need to define *two* skippers because Python doesn't allow both
206 # return with value and yield inside the same function.
206 # return with value and yield inside the same function.
207 def skipper_func(*args, **kwargs):
207 def skipper_func(*args, **kwargs):
208 """Skipper for normal test functions."""
208 """Skipper for normal test functions."""
209 if skip_val():
209 if skip_val():
210 raise nose.SkipTest(get_msg(f,msg))
210 raise nose.SkipTest(get_msg(f,msg))
211 else:
211 else:
212 return f(*args, **kwargs)
212 return f(*args, **kwargs)
213
213
214 def skipper_gen(*args, **kwargs):
214 def skipper_gen(*args, **kwargs):
215 """Skipper for test generators."""
215 """Skipper for test generators."""
216 if skip_val():
216 if skip_val():
217 raise nose.SkipTest(get_msg(f,msg))
217 raise nose.SkipTest(get_msg(f,msg))
218 else:
218 else:
219 for x in f(*args, **kwargs):
219 for x in f(*args, **kwargs):
220 yield x
220 yield x
221
221
222 # Choose the right skipper to use when building the actual generator.
222 # Choose the right skipper to use when building the actual generator.
223 if nose.util.isgenerator(f):
223 if nose.util.isgenerator(f):
224 skipper = skipper_gen
224 skipper = skipper_gen
225 else:
225 else:
226 skipper = skipper_func
226 skipper = skipper_func
227
227
228 return nose.tools.make_decorator(f)(skipper)
228 return nose.tools.make_decorator(f)(skipper)
229
229
230 return skip_decorator
230 return skip_decorator
231
231
232 # A version with the condition set to true, common case just to attach a message
232 # A version with the condition set to true, common case just to attach a message
233 # to a skip decorator
233 # to a skip decorator
234 def skip(msg=None):
234 def skip(msg=None):
235 """Decorator factory - mark a test function for skipping from test suite.
235 """Decorator factory - mark a test function for skipping from test suite.
236
236
237 Parameters
237 Parameters
238 ----------
238 ----------
239 msg : string
239 msg : string
240 Optional message to be added.
240 Optional message to be added.
241
241
242 Returns
242 Returns
243 -------
243 -------
244 decorator : function
244 decorator : function
245 Decorator, which, when applied to a function, causes SkipTest
245 Decorator, which, when applied to a function, causes SkipTest
246 to be raised, with the optional message added.
246 to be raised, with the optional message added.
247 """
247 """
248
248
249 return skipif(True,msg)
249 return skipif(True,msg)
250
250
251
251
252 def onlyif(condition, msg):
252 def onlyif(condition, msg):
253 """The reverse from skipif, see skipif for details."""
253 """The reverse from skipif, see skipif for details."""
254
254
255 if callable(condition):
255 if callable(condition):
256 skip_condition = lambda : not condition()
256 skip_condition = lambda : not condition()
257 else:
257 else:
258 skip_condition = lambda : not condition
258 skip_condition = lambda : not condition
259
259
260 return skipif(skip_condition, msg)
260 return skipif(skip_condition, msg)
261
261
262 #-----------------------------------------------------------------------------
262 #-----------------------------------------------------------------------------
263 # Utility functions for decorators
263 # Utility functions for decorators
264 def module_not_available(module):
264 def module_not_available(module):
265 """Can module be imported? Returns true if module does NOT import.
265 """Can module be imported? Returns true if module does NOT import.
266
266
267 This is used to make a decorator to skip tests that require module to be
267 This is used to make a decorator to skip tests that require module to be
268 available, but delay the 'import numpy' to test execution time.
268 available, but delay the 'import numpy' to test execution time.
269 """
269 """
270 try:
270 try:
271 mod = __import__(module)
271 mod = __import__(module)
272 mod_not_avail = False
272 mod_not_avail = False
273 except ImportError:
273 except ImportError:
274 mod_not_avail = True
274 mod_not_avail = True
275
275
276 return mod_not_avail
276 return mod_not_avail
277
277
278
278
279 def decorated_dummy(dec, name):
279 def decorated_dummy(dec, name):
280 """Return a dummy function decorated with dec, with the given name.
280 """Return a dummy function decorated with dec, with the given name.
281
281
282 Examples
282 Examples
283 --------
283 --------
284 import IPython.testing.decorators as dec
284 import IPython.testing.decorators as dec
285 setup = dec.decorated_dummy(dec.skip_if_no_x11, __name__)
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 next major version of IPython", DeprecationWarning)
287 warnings.warn("The function `make_label_dec` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
288 dummy = lambda: None
288 dummy = lambda: None
289 dummy.__name__ = name
289 dummy.__name__ = name
290 return dec(dummy)
290 return dec(dummy)
291
291
292 #-----------------------------------------------------------------------------
292 #-----------------------------------------------------------------------------
293 # Decorators for public use
293 # Decorators for public use
294
294
295 # Decorators to skip certain tests on specific platforms.
295 # Decorators to skip certain tests on specific platforms.
296 skip_win32 = skipif(sys.platform == 'win32',
296 skip_win32 = skipif(sys.platform == 'win32',
297 "This test does not run under Windows")
297 "This test does not run under Windows")
298 skip_linux = skipif(sys.platform.startswith('linux'),
298 skip_linux = skipif(sys.platform.startswith('linux'),
299 "This test does not run under Linux")
299 "This test does not run under Linux")
300 skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OS X")
300 skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OS X")
301
301
302
302
303 # Decorators to skip tests if not on specific platforms.
303 # Decorators to skip tests if not on specific platforms.
304 skip_if_not_win32 = skipif(sys.platform != 'win32',
304 skip_if_not_win32 = skipif(sys.platform != 'win32',
305 "This test only runs under Windows")
305 "This test only runs under Windows")
306 skip_if_not_linux = skipif(not sys.platform.startswith('linux'),
306 skip_if_not_linux = skipif(not sys.platform.startswith('linux'),
307 "This test only runs under Linux")
307 "This test only runs under Linux")
308 skip_if_not_osx = skipif(sys.platform != 'darwin',
308 skip_if_not_osx = skipif(sys.platform != 'darwin',
309 "This test only runs under OSX")
309 "This test only runs under OSX")
310
310
311
311
312 _x11_skip_cond = (sys.platform not in ('darwin', 'win32') and
312 _x11_skip_cond = (sys.platform not in ('darwin', 'win32') and
313 os.environ.get('DISPLAY', '') == '')
313 os.environ.get('DISPLAY', '') == '')
314 _x11_skip_msg = "Skipped under *nix when X11/XOrg not available"
314 _x11_skip_msg = "Skipped under *nix when X11/XOrg not available"
315
315
316 skip_if_no_x11 = skipif(_x11_skip_cond, _x11_skip_msg)
316 skip_if_no_x11 = skipif(_x11_skip_cond, _x11_skip_msg)
317
317
318 # not a decorator itself, returns a dummy function to be used as setup
318 # not a decorator itself, returns a dummy function to be used as setup
319 def skip_file_no_x11(name):
319 def skip_file_no_x11(name):
320 warnings.warn("The function `skip_file_no_x11` is deprecated and might be removed in next major version of IPython", DeprecationWarning)
320 warnings.warn("The function `skip_file_no_x11` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
321 return decorated_dummy(skip_if_no_x11, name) if _x11_skip_cond else None
321 return decorated_dummy(skip_if_no_x11, name) if _x11_skip_cond else None
322
322
323 # Other skip decorators
323 # Other skip decorators
324
324
325 # generic skip without module
325 # generic skip without module
326 skip_without = lambda mod: skipif(module_not_available(mod), "This test requires %s" % mod)
326 skip_without = lambda mod: skipif(module_not_available(mod), "This test requires %s" % mod)
327
327
328 skipif_not_numpy = skip_without('numpy')
328 skipif_not_numpy = skip_without('numpy')
329
329
330 skipif_not_matplotlib = skip_without('matplotlib')
330 skipif_not_matplotlib = skip_without('matplotlib')
331
331
332 skipif_not_sympy = skip_without('sympy')
332 skipif_not_sympy = skip_without('sympy')
333
333
334 skip_known_failure = knownfailureif(True,'This test is known to fail')
334 skip_known_failure = knownfailureif(True,'This test is known to fail')
335
335
336 known_failure_py3 = knownfailureif(sys.version_info[0] >= 3,
336 known_failure_py3 = knownfailureif(sys.version_info[0] >= 3,
337 'This test is known to fail on Python 3.')
337 'This test is known to fail on Python 3.')
338
338
339 py2_only = skipif(PY3, "This test only runs on Python 2.")
339 py2_only = skipif(PY3, "This test only runs on Python 2.")
340 py3_only = skipif(PY2, "This test only runs on Python 3.")
340 py3_only = skipif(PY2, "This test only runs on Python 3.")
341
341
342 # A null 'decorator', useful to make more readable code that needs to pick
342 # A null 'decorator', useful to make more readable code that needs to pick
343 # between different decorators based on OS or other conditions
343 # between different decorators based on OS or other conditions
344 null_deco = lambda f: f
344 null_deco = lambda f: f
345
345
346 # Some tests only run where we can use unicode paths. Note that we can't just
346 # Some tests only run where we can use unicode paths. Note that we can't just
347 # check os.path.supports_unicode_filenames, which is always False on Linux.
347 # check os.path.supports_unicode_filenames, which is always False on Linux.
348 try:
348 try:
349 f = tempfile.NamedTemporaryFile(prefix=u"tmp€")
349 f = tempfile.NamedTemporaryFile(prefix=u"tmp€")
350 except UnicodeEncodeError:
350 except UnicodeEncodeError:
351 unicode_paths = False
351 unicode_paths = False
352 else:
352 else:
353 unicode_paths = True
353 unicode_paths = True
354 f.close()
354 f.close()
355
355
356 onlyif_unicode_paths = onlyif(unicode_paths, ("This test is only applicable "
356 onlyif_unicode_paths = onlyif(unicode_paths, ("This test is only applicable "
357 "where we can use unicode in filenames."))
357 "where we can use unicode in filenames."))
358
358
359
359
360 def onlyif_cmds_exist(*commands):
360 def onlyif_cmds_exist(*commands):
361 """
361 """
362 Decorator to skip test when at least one of `commands` is not found.
362 Decorator to skip test when at least one of `commands` is not found.
363 """
363 """
364 for cmd in commands:
364 for cmd in commands:
365 if not which(cmd):
365 if not which(cmd):
366 return skip("This test runs only if command '{0}' "
366 return skip("This test runs only if command '{0}' "
367 "is installed".format(cmd))
367 "is installed".format(cmd))
368 return null_deco
368 return null_deco
369
369
370 def onlyif_any_cmd_exists(*commands):
370 def onlyif_any_cmd_exists(*commands):
371 """
371 """
372 Decorator to skip test unless at least one of `commands` is found.
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 next major version of IPython", DeprecationWarning)
374 warnings.warn("The function `onlyif_any_cmd_exists` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
375 for cmd in commands:
375 for cmd in commands:
376 if which(cmd):
376 if which(cmd):
377 return null_deco
377 return null_deco
378 return skip("This test runs only if one of the commands {0} "
378 return skip("This test runs only if one of the commands {0} "
379 "is installed".format(commands))
379 "is installed".format(commands))
@@ -1,457 +1,441 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Test Suite Runner.
2 """IPython Test Suite Runner.
3
3
4 This module provides a main entry point to a user script to test IPython
4 This module provides a main entry point to a user script to test IPython
5 itself from the command line. There are two ways of running this script:
5 itself from the command line. There are two ways of running this script:
6
6
7 1. With the syntax `iptest all`. This runs our entire test suite by
7 1. With the syntax `iptest all`. This runs our entire test suite by
8 calling this script (with different arguments) recursively. This
8 calling this script (with different arguments) recursively. This
9 causes modules and package to be tested in different processes, using nose
9 causes modules and package to be tested in different processes, using nose
10 or trial where appropriate.
10 or trial where appropriate.
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
12 the script simply calls nose, but with special command line flags and
12 the script simply calls nose, but with special command line flags and
13 plugins loaded.
13 plugins loaded.
14
14
15 """
15 """
16
16
17 # Copyright (c) IPython Development Team.
17 # Copyright (c) IPython Development Team.
18 # Distributed under the terms of the Modified BSD License.
18 # Distributed under the terms of the Modified BSD License.
19
19
20 from __future__ import print_function
20 from __future__ import print_function
21
21
22 import glob
22 import glob
23 from io import BytesIO
23 from io import BytesIO
24 import os
24 import os
25 import os.path as path
25 import os.path as path
26 import sys
26 import sys
27 from threading import Thread, Lock, Event
27 from threading import Thread, Lock, Event
28 import warnings
28 import warnings
29
29
30 import nose.plugins.builtin
30 import nose.plugins.builtin
31 from nose.plugins.xunit import Xunit
31 from nose.plugins.xunit import Xunit
32 from nose import SkipTest
32 from nose import SkipTest
33 from nose.core import TestProgram
33 from nose.core import TestProgram
34 from nose.plugins import Plugin
34 from nose.plugins import Plugin
35 from nose.util import safe_str
35 from nose.util import safe_str
36
36
37 from IPython import version_info
37 from IPython import version_info
38 from IPython.utils.py3compat import bytes_to_str
38 from IPython.utils.py3compat import bytes_to_str
39 from IPython.utils.importstring import import_item
39 from IPython.utils.importstring import import_item
40 from IPython.testing.plugin.ipdoctest import IPythonDoctest
40 from IPython.testing.plugin.ipdoctest import IPythonDoctest
41 from IPython.external.decorators import KnownFailure, knownfailureif
41 from IPython.external.decorators import KnownFailure, knownfailureif
42
42
43 pjoin = path.join
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 # Enable printing all warnings raise by IPython's modules
46 # Enable printing all warnings raise by IPython's modules
63 warnings.filterwarnings('default', message='.*', category=Warning, module='IPy.*')
47 warnings.filterwarnings('default', message='.*', category=Warning, module='IPy.*')
64
48
65
49
66 if version_info < (4,2):
50 if version_info < (4,2):
67 # ignore some warnings from traitlets until 6.0
51 # ignore some warnings from traitlets until 6.0
68 warnings.filterwarnings('ignore', message='.*on_trait_change is deprecated: use observe instead.*')
52 warnings.filterwarnings('ignore', message='.*on_trait_change is deprecated: use observe instead.*')
69 warnings.filterwarnings('ignore', message='.*was set from the constructor.*', category=Warning, module='IPython.*')
53 warnings.filterwarnings('ignore', message='.*was set from the constructor.*', category=Warning, module='IPython.*')
70 else :
54 else :
71 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')
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 if version_info < (6,):
57 if version_info < (6,):
74 # nose.tools renames all things from `camelCase` to `snake_case` which raise an
58 # nose.tools renames all things from `camelCase` to `snake_case` which raise an
75 # warning with the runner they also import from standard import library. (as of Dec 2015)
59 # warning with the runner they also import from standard import library. (as of Dec 2015)
76 # Ignore, let's revisit that in a couple of years for IPython 6.
60 # Ignore, let's revisit that in a couple of years for IPython 6.
77 warnings.filterwarnings('ignore', message='.*Please use assertEqual instead', category=Warning, module='IPython.*')
61 warnings.filterwarnings('ignore', message='.*Please use assertEqual instead', category=Warning, module='IPython.*')
78
62
79
63
80 # ------------------------------------------------------------------------------
64 # ------------------------------------------------------------------------------
81 # Monkeypatch Xunit to count known failures as skipped.
65 # Monkeypatch Xunit to count known failures as skipped.
82 # ------------------------------------------------------------------------------
66 # ------------------------------------------------------------------------------
83 def monkeypatch_xunit():
67 def monkeypatch_xunit():
84 try:
68 try:
85 knownfailureif(True)(lambda: None)()
69 knownfailureif(True)(lambda: None)()
86 except Exception as e:
70 except Exception as e:
87 KnownFailureTest = type(e)
71 KnownFailureTest = type(e)
88
72
89 def addError(self, test, err, capt=None):
73 def addError(self, test, err, capt=None):
90 if issubclass(err[0], KnownFailureTest):
74 if issubclass(err[0], KnownFailureTest):
91 err = (SkipTest,) + err[1:]
75 err = (SkipTest,) + err[1:]
92 return self.orig_addError(test, err, capt)
76 return self.orig_addError(test, err, capt)
93
77
94 Xunit.orig_addError = Xunit.addError
78 Xunit.orig_addError = Xunit.addError
95 Xunit.addError = addError
79 Xunit.addError = addError
96
80
97 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
98 # Check which dependencies are installed and greater than minimum version.
82 # Check which dependencies are installed and greater than minimum version.
99 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
100 def extract_version(mod):
84 def extract_version(mod):
101 return mod.__version__
85 return mod.__version__
102
86
103 def test_for(item, min_version=None, callback=extract_version):
87 def test_for(item, min_version=None, callback=extract_version):
104 """Test to see if item is importable, and optionally check against a minimum
88 """Test to see if item is importable, and optionally check against a minimum
105 version.
89 version.
106
90
107 If min_version is given, the default behavior is to check against the
91 If min_version is given, the default behavior is to check against the
108 `__version__` attribute of the item, but specifying `callback` allows you to
92 `__version__` attribute of the item, but specifying `callback` allows you to
109 extract the value you are interested in. e.g::
93 extract the value you are interested in. e.g::
110
94
111 In [1]: import sys
95 In [1]: import sys
112
96
113 In [2]: from IPython.testing.iptest import test_for
97 In [2]: from IPython.testing.iptest import test_for
114
98
115 In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info)
99 In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info)
116 Out[3]: True
100 Out[3]: True
117
101
118 """
102 """
119 try:
103 try:
120 check = import_item(item)
104 check = import_item(item)
121 except (ImportError, RuntimeError):
105 except (ImportError, RuntimeError):
122 # GTK reports Runtime error if it can't be initialized even if it's
106 # GTK reports Runtime error if it can't be initialized even if it's
123 # importable.
107 # importable.
124 return False
108 return False
125 else:
109 else:
126 if min_version:
110 if min_version:
127 if callback:
111 if callback:
128 # extra processing step to get version to compare
112 # extra processing step to get version to compare
129 check = callback(check)
113 check = callback(check)
130
114
131 return check >= min_version
115 return check >= min_version
132 else:
116 else:
133 return True
117 return True
134
118
135 # Global dict where we can store information on what we have and what we don't
119 # Global dict where we can store information on what we have and what we don't
136 # have available at test run time
120 # have available at test run time
137 have = {'matplotlib': test_for('matplotlib'),
121 have = {'matplotlib': test_for('matplotlib'),
138 'pygments': test_for('pygments'),
122 'pygments': test_for('pygments'),
139 'sqlite3': test_for('sqlite3')}
123 'sqlite3': test_for('sqlite3')}
140
124
141 #-----------------------------------------------------------------------------
125 #-----------------------------------------------------------------------------
142 # Test suite definitions
126 # Test suite definitions
143 #-----------------------------------------------------------------------------
127 #-----------------------------------------------------------------------------
144
128
145 test_group_names = ['core',
129 test_group_names = ['core',
146 'extensions', 'lib', 'terminal', 'testing', 'utils',
130 'extensions', 'lib', 'terminal', 'testing', 'utils',
147 ]
131 ]
148
132
149 class TestSection(object):
133 class TestSection(object):
150 def __init__(self, name, includes):
134 def __init__(self, name, includes):
151 self.name = name
135 self.name = name
152 self.includes = includes
136 self.includes = includes
153 self.excludes = []
137 self.excludes = []
154 self.dependencies = []
138 self.dependencies = []
155 self.enabled = True
139 self.enabled = True
156
140
157 def exclude(self, module):
141 def exclude(self, module):
158 if not module.startswith('IPython'):
142 if not module.startswith('IPython'):
159 module = self.includes[0] + "." + module
143 module = self.includes[0] + "." + module
160 self.excludes.append(module.replace('.', os.sep))
144 self.excludes.append(module.replace('.', os.sep))
161
145
162 def requires(self, *packages):
146 def requires(self, *packages):
163 self.dependencies.extend(packages)
147 self.dependencies.extend(packages)
164
148
165 @property
149 @property
166 def will_run(self):
150 def will_run(self):
167 return self.enabled and all(have[p] for p in self.dependencies)
151 return self.enabled and all(have[p] for p in self.dependencies)
168
152
169 # Name -> (include, exclude, dependencies_met)
153 # Name -> (include, exclude, dependencies_met)
170 test_sections = {n:TestSection(n, ['IPython.%s' % n]) for n in test_group_names}
154 test_sections = {n:TestSection(n, ['IPython.%s' % n]) for n in test_group_names}
171
155
172
156
173 # Exclusions and dependencies
157 # Exclusions and dependencies
174 # ---------------------------
158 # ---------------------------
175
159
176 # core:
160 # core:
177 sec = test_sections['core']
161 sec = test_sections['core']
178 if not have['sqlite3']:
162 if not have['sqlite3']:
179 sec.exclude('tests.test_history')
163 sec.exclude('tests.test_history')
180 sec.exclude('history')
164 sec.exclude('history')
181 if not have['matplotlib']:
165 if not have['matplotlib']:
182 sec.exclude('pylabtools'),
166 sec.exclude('pylabtools'),
183 sec.exclude('tests.test_pylabtools')
167 sec.exclude('tests.test_pylabtools')
184
168
185 # lib:
169 # lib:
186 sec = test_sections['lib']
170 sec = test_sections['lib']
187 sec.exclude('kernel')
171 sec.exclude('kernel')
188 if not have['pygments']:
172 if not have['pygments']:
189 sec.exclude('tests.test_lexers')
173 sec.exclude('tests.test_lexers')
190 # We do this unconditionally, so that the test suite doesn't import
174 # We do this unconditionally, so that the test suite doesn't import
191 # gtk, changing the default encoding and masking some unicode bugs.
175 # gtk, changing the default encoding and masking some unicode bugs.
192 sec.exclude('inputhookgtk')
176 sec.exclude('inputhookgtk')
193 # We also do this unconditionally, because wx can interfere with Unix signals.
177 # We also do this unconditionally, because wx can interfere with Unix signals.
194 # There are currently no tests for it anyway.
178 # There are currently no tests for it anyway.
195 sec.exclude('inputhookwx')
179 sec.exclude('inputhookwx')
196 # Testing inputhook will need a lot of thought, to figure out
180 # Testing inputhook will need a lot of thought, to figure out
197 # how to have tests that don't lock up with the gui event
181 # how to have tests that don't lock up with the gui event
198 # loops in the picture
182 # loops in the picture
199 sec.exclude('inputhook')
183 sec.exclude('inputhook')
200
184
201 # testing:
185 # testing:
202 sec = test_sections['testing']
186 sec = test_sections['testing']
203 # These have to be skipped on win32 because they use echo, rm, cd, etc.
187 # These have to be skipped on win32 because they use echo, rm, cd, etc.
204 # See ticket https://github.com/ipython/ipython/issues/87
188 # See ticket https://github.com/ipython/ipython/issues/87
205 if sys.platform == 'win32':
189 if sys.platform == 'win32':
206 sec.exclude('plugin.test_exampleip')
190 sec.exclude('plugin.test_exampleip')
207 sec.exclude('plugin.dtexample')
191 sec.exclude('plugin.dtexample')
208
192
209 # don't run jupyter_console tests found via shim
193 # don't run jupyter_console tests found via shim
210 test_sections['terminal'].exclude('console')
194 test_sections['terminal'].exclude('console')
211
195
212 # extensions:
196 # extensions:
213 sec = test_sections['extensions']
197 sec = test_sections['extensions']
214 # This is deprecated in favour of rpy2
198 # This is deprecated in favour of rpy2
215 sec.exclude('rmagic')
199 sec.exclude('rmagic')
216 # autoreload does some strange stuff, so move it to its own test section
200 # autoreload does some strange stuff, so move it to its own test section
217 sec.exclude('autoreload')
201 sec.exclude('autoreload')
218 sec.exclude('tests.test_autoreload')
202 sec.exclude('tests.test_autoreload')
219 test_sections['autoreload'] = TestSection('autoreload',
203 test_sections['autoreload'] = TestSection('autoreload',
220 ['IPython.extensions.autoreload', 'IPython.extensions.tests.test_autoreload'])
204 ['IPython.extensions.autoreload', 'IPython.extensions.tests.test_autoreload'])
221 test_group_names.append('autoreload')
205 test_group_names.append('autoreload')
222
206
223
207
224 #-----------------------------------------------------------------------------
208 #-----------------------------------------------------------------------------
225 # Functions and classes
209 # Functions and classes
226 #-----------------------------------------------------------------------------
210 #-----------------------------------------------------------------------------
227
211
228 def check_exclusions_exist():
212 def check_exclusions_exist():
229 from IPython.paths import get_ipython_package_dir
213 from IPython.paths import get_ipython_package_dir
230 from IPython.utils.warn import warn
214 from IPython.utils.warn import warn
231 parent = os.path.dirname(get_ipython_package_dir())
215 parent = os.path.dirname(get_ipython_package_dir())
232 for sec in test_sections:
216 for sec in test_sections:
233 for pattern in sec.exclusions:
217 for pattern in sec.exclusions:
234 fullpath = pjoin(parent, pattern)
218 fullpath = pjoin(parent, pattern)
235 if not os.path.exists(fullpath) and not glob.glob(fullpath + '.*'):
219 if not os.path.exists(fullpath) and not glob.glob(fullpath + '.*'):
236 warn("Excluding nonexistent file: %r" % pattern)
220 warn("Excluding nonexistent file: %r" % pattern)
237
221
238
222
239 class ExclusionPlugin(Plugin):
223 class ExclusionPlugin(Plugin):
240 """A nose plugin to effect our exclusions of files and directories.
224 """A nose plugin to effect our exclusions of files and directories.
241 """
225 """
242 name = 'exclusions'
226 name = 'exclusions'
243 score = 3000 # Should come before any other plugins
227 score = 3000 # Should come before any other plugins
244
228
245 def __init__(self, exclude_patterns=None):
229 def __init__(self, exclude_patterns=None):
246 """
230 """
247 Parameters
231 Parameters
248 ----------
232 ----------
249
233
250 exclude_patterns : sequence of strings, optional
234 exclude_patterns : sequence of strings, optional
251 Filenames containing these patterns (as raw strings, not as regular
235 Filenames containing these patterns (as raw strings, not as regular
252 expressions) are excluded from the tests.
236 expressions) are excluded from the tests.
253 """
237 """
254 self.exclude_patterns = exclude_patterns or []
238 self.exclude_patterns = exclude_patterns or []
255 super(ExclusionPlugin, self).__init__()
239 super(ExclusionPlugin, self).__init__()
256
240
257 def options(self, parser, env=os.environ):
241 def options(self, parser, env=os.environ):
258 Plugin.options(self, parser, env)
242 Plugin.options(self, parser, env)
259
243
260 def configure(self, options, config):
244 def configure(self, options, config):
261 Plugin.configure(self, options, config)
245 Plugin.configure(self, options, config)
262 # Override nose trying to disable plugin.
246 # Override nose trying to disable plugin.
263 self.enabled = True
247 self.enabled = True
264
248
265 def wantFile(self, filename):
249 def wantFile(self, filename):
266 """Return whether the given filename should be scanned for tests.
250 """Return whether the given filename should be scanned for tests.
267 """
251 """
268 if any(pat in filename for pat in self.exclude_patterns):
252 if any(pat in filename for pat in self.exclude_patterns):
269 return False
253 return False
270 return None
254 return None
271
255
272 def wantDirectory(self, directory):
256 def wantDirectory(self, directory):
273 """Return whether the given directory should be scanned for tests.
257 """Return whether the given directory should be scanned for tests.
274 """
258 """
275 if any(pat in directory for pat in self.exclude_patterns):
259 if any(pat in directory for pat in self.exclude_patterns):
276 return False
260 return False
277 return None
261 return None
278
262
279
263
280 class StreamCapturer(Thread):
264 class StreamCapturer(Thread):
281 daemon = True # Don't hang if main thread crashes
265 daemon = True # Don't hang if main thread crashes
282 started = False
266 started = False
283 def __init__(self, echo=False):
267 def __init__(self, echo=False):
284 super(StreamCapturer, self).__init__()
268 super(StreamCapturer, self).__init__()
285 self.echo = echo
269 self.echo = echo
286 self.streams = []
270 self.streams = []
287 self.buffer = BytesIO()
271 self.buffer = BytesIO()
288 self.readfd, self.writefd = os.pipe()
272 self.readfd, self.writefd = os.pipe()
289 self.buffer_lock = Lock()
273 self.buffer_lock = Lock()
290 self.stop = Event()
274 self.stop = Event()
291
275
292 def run(self):
276 def run(self):
293 self.started = True
277 self.started = True
294
278
295 while not self.stop.is_set():
279 while not self.stop.is_set():
296 chunk = os.read(self.readfd, 1024)
280 chunk = os.read(self.readfd, 1024)
297
281
298 with self.buffer_lock:
282 with self.buffer_lock:
299 self.buffer.write(chunk)
283 self.buffer.write(chunk)
300 if self.echo:
284 if self.echo:
301 sys.stdout.write(bytes_to_str(chunk))
285 sys.stdout.write(bytes_to_str(chunk))
302
286
303 os.close(self.readfd)
287 os.close(self.readfd)
304 os.close(self.writefd)
288 os.close(self.writefd)
305
289
306 def reset_buffer(self):
290 def reset_buffer(self):
307 with self.buffer_lock:
291 with self.buffer_lock:
308 self.buffer.truncate(0)
292 self.buffer.truncate(0)
309 self.buffer.seek(0)
293 self.buffer.seek(0)
310
294
311 def get_buffer(self):
295 def get_buffer(self):
312 with self.buffer_lock:
296 with self.buffer_lock:
313 return self.buffer.getvalue()
297 return self.buffer.getvalue()
314
298
315 def ensure_started(self):
299 def ensure_started(self):
316 if not self.started:
300 if not self.started:
317 self.start()
301 self.start()
318
302
319 def halt(self):
303 def halt(self):
320 """Safely stop the thread."""
304 """Safely stop the thread."""
321 if not self.started:
305 if not self.started:
322 return
306 return
323
307
324 self.stop.set()
308 self.stop.set()
325 os.write(self.writefd, b'\0') # Ensure we're not locked in a read()
309 os.write(self.writefd, b'\0') # Ensure we're not locked in a read()
326 self.join()
310 self.join()
327
311
328 class SubprocessStreamCapturePlugin(Plugin):
312 class SubprocessStreamCapturePlugin(Plugin):
329 name='subprocstreams'
313 name='subprocstreams'
330 def __init__(self):
314 def __init__(self):
331 Plugin.__init__(self)
315 Plugin.__init__(self)
332 self.stream_capturer = StreamCapturer()
316 self.stream_capturer = StreamCapturer()
333 self.destination = os.environ.get('IPTEST_SUBPROC_STREAMS', 'capture')
317 self.destination = os.environ.get('IPTEST_SUBPROC_STREAMS', 'capture')
334 # This is ugly, but distant parts of the test machinery need to be able
318 # This is ugly, but distant parts of the test machinery need to be able
335 # to redirect streams, so we make the object globally accessible.
319 # to redirect streams, so we make the object globally accessible.
336 nose.iptest_stdstreams_fileno = self.get_write_fileno
320 nose.iptest_stdstreams_fileno = self.get_write_fileno
337
321
338 def get_write_fileno(self):
322 def get_write_fileno(self):
339 if self.destination == 'capture':
323 if self.destination == 'capture':
340 self.stream_capturer.ensure_started()
324 self.stream_capturer.ensure_started()
341 return self.stream_capturer.writefd
325 return self.stream_capturer.writefd
342 elif self.destination == 'discard':
326 elif self.destination == 'discard':
343 return os.open(os.devnull, os.O_WRONLY)
327 return os.open(os.devnull, os.O_WRONLY)
344 else:
328 else:
345 return sys.__stdout__.fileno()
329 return sys.__stdout__.fileno()
346
330
347 def configure(self, options, config):
331 def configure(self, options, config):
348 Plugin.configure(self, options, config)
332 Plugin.configure(self, options, config)
349 # Override nose trying to disable plugin.
333 # Override nose trying to disable plugin.
350 if self.destination == 'capture':
334 if self.destination == 'capture':
351 self.enabled = True
335 self.enabled = True
352
336
353 def startTest(self, test):
337 def startTest(self, test):
354 # Reset log capture
338 # Reset log capture
355 self.stream_capturer.reset_buffer()
339 self.stream_capturer.reset_buffer()
356
340
357 def formatFailure(self, test, err):
341 def formatFailure(self, test, err):
358 # Show output
342 # Show output
359 ec, ev, tb = err
343 ec, ev, tb = err
360 captured = self.stream_capturer.get_buffer().decode('utf-8', 'replace')
344 captured = self.stream_capturer.get_buffer().decode('utf-8', 'replace')
361 if captured.strip():
345 if captured.strip():
362 ev = safe_str(ev)
346 ev = safe_str(ev)
363 out = [ev, '>> begin captured subprocess output <<',
347 out = [ev, '>> begin captured subprocess output <<',
364 captured,
348 captured,
365 '>> end captured subprocess output <<']
349 '>> end captured subprocess output <<']
366 return ec, '\n'.join(out), tb
350 return ec, '\n'.join(out), tb
367
351
368 return err
352 return err
369
353
370 formatError = formatFailure
354 formatError = formatFailure
371
355
372 def finalize(self, result):
356 def finalize(self, result):
373 self.stream_capturer.halt()
357 self.stream_capturer.halt()
374
358
375
359
376 def run_iptest():
360 def run_iptest():
377 """Run the IPython test suite using nose.
361 """Run the IPython test suite using nose.
378
362
379 This function is called when this script is **not** called with the form
363 This function is called when this script is **not** called with the form
380 `iptest all`. It simply calls nose with appropriate command line flags
364 `iptest all`. It simply calls nose with appropriate command line flags
381 and accepts all of the standard nose arguments.
365 and accepts all of the standard nose arguments.
382 """
366 """
383 # Apply our monkeypatch to Xunit
367 # Apply our monkeypatch to Xunit
384 if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'):
368 if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'):
385 monkeypatch_xunit()
369 monkeypatch_xunit()
386
370
387 warnings.filterwarnings('ignore',
371 warnings.filterwarnings('ignore',
388 'This will be removed soon. Use IPython.testing.util instead')
372 'This will be removed soon. Use IPython.testing.util instead')
389
373
390 arg1 = sys.argv[1]
374 arg1 = sys.argv[1]
391 if arg1 in test_sections:
375 if arg1 in test_sections:
392 section = test_sections[arg1]
376 section = test_sections[arg1]
393 sys.argv[1:2] = section.includes
377 sys.argv[1:2] = section.includes
394 elif arg1.startswith('IPython.') and arg1[8:] in test_sections:
378 elif arg1.startswith('IPython.') and arg1[8:] in test_sections:
395 section = test_sections[arg1[8:]]
379 section = test_sections[arg1[8:]]
396 sys.argv[1:2] = section.includes
380 sys.argv[1:2] = section.includes
397 else:
381 else:
398 section = TestSection(arg1, includes=[arg1])
382 section = TestSection(arg1, includes=[arg1])
399
383
400
384
401 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
385 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
402 # We add --exe because of setuptools' imbecility (it
386 # We add --exe because of setuptools' imbecility (it
403 # blindly does chmod +x on ALL files). Nose does the
387 # blindly does chmod +x on ALL files). Nose does the
404 # right thing and it tries to avoid executables,
388 # right thing and it tries to avoid executables,
405 # setuptools unfortunately forces our hand here. This
389 # setuptools unfortunately forces our hand here. This
406 # has been discussed on the distutils list and the
390 # has been discussed on the distutils list and the
407 # setuptools devs refuse to fix this problem!
391 # setuptools devs refuse to fix this problem!
408 '--exe',
392 '--exe',
409 ]
393 ]
410 if '-a' not in argv and '-A' not in argv:
394 if '-a' not in argv and '-A' not in argv:
411 argv = argv + ['-a', '!crash']
395 argv = argv + ['-a', '!crash']
412
396
413 if nose.__version__ >= '0.11':
397 if nose.__version__ >= '0.11':
414 # I don't fully understand why we need this one, but depending on what
398 # I don't fully understand why we need this one, but depending on what
415 # directory the test suite is run from, if we don't give it, 0 tests
399 # directory the test suite is run from, if we don't give it, 0 tests
416 # get run. Specifically, if the test suite is run from the source dir
400 # get run. Specifically, if the test suite is run from the source dir
417 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
401 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
418 # even if the same call done in this directory works fine). It appears
402 # even if the same call done in this directory works fine). It appears
419 # that if the requested package is in the current dir, nose bails early
403 # that if the requested package is in the current dir, nose bails early
420 # by default. Since it's otherwise harmless, leave it in by default
404 # by default. Since it's otherwise harmless, leave it in by default
421 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
405 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
422 argv.append('--traverse-namespace')
406 argv.append('--traverse-namespace')
423
407
424 plugins = [ ExclusionPlugin(section.excludes), KnownFailure(),
408 plugins = [ ExclusionPlugin(section.excludes), KnownFailure(),
425 SubprocessStreamCapturePlugin() ]
409 SubprocessStreamCapturePlugin() ]
426
410
427 # we still have some vestigial doctests in core
411 # we still have some vestigial doctests in core
428 if (section.name.startswith(('core', 'IPython.core'))):
412 if (section.name.startswith(('core', 'IPython.core'))):
429 plugins.append(IPythonDoctest())
413 plugins.append(IPythonDoctest())
430 argv.extend([
414 argv.extend([
431 '--with-ipdoctest',
415 '--with-ipdoctest',
432 '--ipdoctest-tests',
416 '--ipdoctest-tests',
433 '--ipdoctest-extension=txt',
417 '--ipdoctest-extension=txt',
434 ])
418 ])
435
419
436
420
437 # Use working directory set by parent process (see iptestcontroller)
421 # Use working directory set by parent process (see iptestcontroller)
438 if 'IPTEST_WORKING_DIR' in os.environ:
422 if 'IPTEST_WORKING_DIR' in os.environ:
439 os.chdir(os.environ['IPTEST_WORKING_DIR'])
423 os.chdir(os.environ['IPTEST_WORKING_DIR'])
440
424
441 # We need a global ipython running in this process, but the special
425 # We need a global ipython running in this process, but the special
442 # in-process group spawns its own IPython kernels, so for *that* group we
426 # in-process group spawns its own IPython kernels, so for *that* group we
443 # must avoid also opening the global one (otherwise there's a conflict of
427 # must avoid also opening the global one (otherwise there's a conflict of
444 # singletons). Ultimately the solution to this problem is to refactor our
428 # singletons). Ultimately the solution to this problem is to refactor our
445 # assumptions about what needs to be a singleton and what doesn't (app
429 # assumptions about what needs to be a singleton and what doesn't (app
446 # objects should, individual shells shouldn't). But for now, this
430 # objects should, individual shells shouldn't). But for now, this
447 # workaround allows the test suite for the inprocess module to complete.
431 # workaround allows the test suite for the inprocess module to complete.
448 if 'kernel.inprocess' not in section.name:
432 if 'kernel.inprocess' not in section.name:
449 from IPython.testing import globalipapp
433 from IPython.testing import globalipapp
450 globalipapp.start_ipython()
434 globalipapp.start_ipython()
451
435
452 # Now nose can run
436 # Now nose can run
453 TestProgram(argv=argv, addplugins=plugins)
437 TestProgram(argv=argv, addplugins=plugins)
454
438
455 if __name__ == '__main__':
439 if __name__ == '__main__':
456 run_iptest()
440 run_iptest()
457
441
General Comments 0
You need to be logged in to leave comments. Login now