Show More
@@ -0,0 +1,106 b'' | |||
|
1 | # -*- coding: utf-8 -*- | |
|
2 | """Top-level display functions for displaying object in different formats. | |
|
3 | ||
|
4 | Authors: | |
|
5 | ||
|
6 | * Brian Granger | |
|
7 | """ | |
|
8 | ||
|
9 | #----------------------------------------------------------------------------- | |
|
10 | # Copyright (C) 2008-2010 The IPython Development Team | |
|
11 | # | |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
|
13 | # the file COPYING, distributed as part of this software. | |
|
14 | #----------------------------------------------------------------------------- | |
|
15 | ||
|
16 | #----------------------------------------------------------------------------- | |
|
17 | # Imports | |
|
18 | #----------------------------------------------------------------------------- | |
|
19 | ||
|
20 | #----------------------------------------------------------------------------- | |
|
21 | # Main functions | |
|
22 | #----------------------------------------------------------------------------- | |
|
23 | ||
|
24 | def display(obj, include=None, exclude=None): | |
|
25 | """Display a Python object in all frontends. | |
|
26 | ||
|
27 | By default all representations will be computed and sent to the frontends. | |
|
28 | Frontends can decide which representation is used and how. | |
|
29 | ||
|
30 | Parameters | |
|
31 | ---------- | |
|
32 | obj : object | |
|
33 | The Python object to display. | |
|
34 | include : list or tuple, optional | |
|
35 | A list of format type strings (MIME types) to include in the | |
|
36 | format data dict. If this is set *only* the format types included | |
|
37 | in this list will be computed. | |
|
38 | exclude : list or tuple, optional | |
|
39 | A list of format type string (MIME types) to exclue in the format | |
|
40 | data dict. If this is set all format types will be computed, | |
|
41 | except for those included in this argument. | |
|
42 | """ | |
|
43 | from IPython.core.interactiveshell import InteractiveShell | |
|
44 | format = InteractiveShell.instance().display_formatter.format | |
|
45 | publish = InteractiveShell.instance().display_pub.publish | |
|
46 | ||
|
47 | format_dict = format(obj, include=include, exclude=exclude) | |
|
48 | publish('IPython.core.display.display', format_dict) | |
|
49 | ||
|
50 | ||
|
51 | def display_html(obj): | |
|
52 | """Display the HTML representation of an object. | |
|
53 | ||
|
54 | Parameters | |
|
55 | ---------- | |
|
56 | obj : object | |
|
57 | The Python object to display. | |
|
58 | """ | |
|
59 | display(obj, include=['text/plain','text/html']) | |
|
60 | ||
|
61 | ||
|
62 | def display_svg(obj): | |
|
63 | """Display the SVG representation of an object. | |
|
64 | ||
|
65 | Parameters | |
|
66 | ---------- | |
|
67 | obj : object | |
|
68 | The Python object to display. | |
|
69 | """ | |
|
70 | display(obj, include=['text/plain','image/svg+xml']) | |
|
71 | ||
|
72 | ||
|
73 | def display_png(obj): | |
|
74 | """Display the PNG representation of an object. | |
|
75 | ||
|
76 | Parameters | |
|
77 | ---------- | |
|
78 | obj : object | |
|
79 | The Python object to display. | |
|
80 | """ | |
|
81 | display(obj, include=['text/plain','image/png']) | |
|
82 | ||
|
83 | ||
|
84 | def display_latex(obj): | |
|
85 | """Display the LaTeX representation of an object. | |
|
86 | ||
|
87 | Parameters | |
|
88 | ---------- | |
|
89 | obj : object | |
|
90 | The Python object to display. | |
|
91 | """ | |
|
92 | display(obj, include=['text/plain','text/latex']) | |
|
93 | ||
|
94 | ||
|
95 | def display_json(obj): | |
|
96 | """Display the JSON representation of an object. | |
|
97 | ||
|
98 | Parameters | |
|
99 | ---------- | |
|
100 | obj : object | |
|
101 | The Python object to display. | |
|
102 | """ | |
|
103 | display(obj, include=['text/plain','application/json']) | |
|
104 | ||
|
105 | ||
|
106 |
@@ -0,0 +1,45 b'' | |||
|
1 | """A print function that pretty prints sympy Basic objects. | |
|
2 | ||
|
3 | Authors: | |
|
4 | * Brian Granger | |
|
5 | """ | |
|
6 | #----------------------------------------------------------------------------- | |
|
7 | # Copyright (C) 2008-2011 The IPython Development Team | |
|
8 | # | |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
|
10 | # the file COPYING, distributed as part of this software. | |
|
11 | #----------------------------------------------------------------------------- | |
|
12 | ||
|
13 | #----------------------------------------------------------------------------- | |
|
14 | # Imports | |
|
15 | #----------------------------------------------------------------------------- | |
|
16 | ||
|
17 | from sympy import pretty | |
|
18 | ||
|
19 | #----------------------------------------------------------------------------- | |
|
20 | # Definitions of magic functions for use with IPython | |
|
21 | #----------------------------------------------------------------------------- | |
|
22 | ||
|
23 | def print_basic_unicode(o, p, cycle): | |
|
24 | """A function to pretty print sympy Basic objects.""" | |
|
25 | if cycle: | |
|
26 | return p.text('Basic(...)') | |
|
27 | out = pretty(o, use_unicode=True) | |
|
28 | if '\n' in out: | |
|
29 | p.text(u'\n') | |
|
30 | p.text(out) | |
|
31 | ||
|
32 | ||
|
33 | _loaded = False | |
|
34 | ||
|
35 | ||
|
36 | def load_ipython_extension(ip): | |
|
37 | """Load the extension in IPython.""" | |
|
38 | global _loaded | |
|
39 | if not _loaded: | |
|
40 | plaintext_formatter = ip.display_formatter.formatters['text/plain'] | |
|
41 | plaintext_formatter.for_type_by_name( | |
|
42 | 'sympy.core.basic', 'Basic', print_basic_unicode | |
|
43 | ) | |
|
44 | _loaded = True | |
|
45 |
@@ -1,21 +1,28 b'' | |||
|
1 | 1 | c = get_config() |
|
2 | 2 | |
|
3 | 3 | # This can be used at any point in a config file to load a sub config |
|
4 | 4 | # and merge it into the current one. |
|
5 | 5 | load_subconfig('ipython_config.py') |
|
6 | 6 | |
|
7 | 7 | lines = """ |
|
8 | 8 | from __future__ import division |
|
9 | 9 | from sympy import * |
|
10 | 10 | x, y, z = symbols('xyz') |
|
11 | 11 | k, m, n = symbols('kmn', integer=True) |
|
12 | 12 | f, g, h = map(Function, 'fgh') |
|
13 | 13 | """ |
|
14 | 14 | |
|
15 | 15 | # You have to make sure that attributes that are containers already |
|
16 | 16 | # exist before using them. Simple assigning a new list will override |
|
17 | 17 | # all previous values. |
|
18 | ||
|
18 | 19 | if hasattr(c.Global, 'exec_lines'): |
|
19 | 20 | c.Global.exec_lines.append(lines) |
|
20 | 21 | else: |
|
21 | 22 | c.Global.exec_lines = [lines] |
|
23 | ||
|
24 | if hasattr(c.Global, 'extensions'): | |
|
25 | c.Global.extensions.append('IPython.extensions.sympy_printing') | |
|
26 | else: | |
|
27 | c.Global.extensions = ['IPython.extensions.sympy_printing'] | |
|
28 |
@@ -1,304 +1,322 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Displayhook for IPython. |
|
3 | 3 | |
|
4 | This defines a callable class that IPython uses for `sys.displayhook`. | |
|
5 | ||
|
4 | 6 | Authors: |
|
5 | 7 | |
|
6 | 8 | * Fernando Perez |
|
7 | 9 | * Brian Granger |
|
10 | * Robert Kern | |
|
8 | 11 | """ |
|
9 | 12 | |
|
10 | 13 | #----------------------------------------------------------------------------- |
|
11 | 14 | # Copyright (C) 2008-2010 The IPython Development Team |
|
12 | 15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
13 | 16 | # |
|
14 | 17 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 18 | # the file COPYING, distributed as part of this software. |
|
16 | 19 | #----------------------------------------------------------------------------- |
|
17 | 20 | |
|
18 | 21 | #----------------------------------------------------------------------------- |
|
19 | 22 | # Imports |
|
20 | 23 | #----------------------------------------------------------------------------- |
|
21 | 24 | |
|
22 | 25 | import __builtin__ |
|
23 | 26 | |
|
24 | 27 | from IPython.config.configurable import Configurable |
|
25 | 28 | from IPython.core import prompts |
|
26 | 29 | import IPython.utils.generics |
|
27 | 30 | import IPython.utils.io |
|
28 | 31 | from IPython.utils.traitlets import Instance, List |
|
29 | 32 | from IPython.utils.warn import warn |
|
30 | from IPython.core.formatters import DefaultFormatter | |
|
31 | 33 | |
|
32 | 34 | #----------------------------------------------------------------------------- |
|
33 | 35 | # Main displayhook class |
|
34 | 36 | #----------------------------------------------------------------------------- |
|
35 | 37 | |
|
36 | 38 | # TODO: The DisplayHook class should be split into two classes, one that |
|
37 | 39 | # manages the prompts and their synchronization and another that just does the |
|
38 | 40 | # displayhook logic and calls into the prompt manager. |
|
39 | 41 | |
|
40 | 42 | # TODO: Move the various attributes (cache_size, colors, input_sep, |
|
41 | 43 | # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also |
|
42 | 44 | # attributes of InteractiveShell. They should be on ONE object only and the |
|
43 | 45 | # other objects should ask that one object for their values. |
|
44 | 46 | |
|
45 | 47 | class DisplayHook(Configurable): |
|
46 | 48 | """The custom IPython displayhook to replace sys.displayhook. |
|
47 | 49 | |
|
48 | 50 | This class does many things, but the basic idea is that it is a callable |
|
49 | 51 | that gets called anytime user code returns a value. |
|
50 | 52 | |
|
51 | 53 | Currently this class does more than just the displayhook logic and that |
|
52 | 54 | extra logic should eventually be moved out of here. |
|
53 | 55 | """ |
|
54 | 56 | |
|
55 | 57 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
56 | 58 | |
|
57 | # The default formatter. | |
|
58 | default_formatter = Instance('IPython.core.formatters.FormatterABC') | |
|
59 | def _default_formatter_default(self): | |
|
60 | # FIXME: backwards compatibility for the InteractiveShell.pprint option? | |
|
61 | return DefaultFormatter(config=self.config) | |
|
62 | ||
|
63 | # Any additional FormatterABC instances we use. | |
|
64 | # FIXME: currently unused. | |
|
65 | extra_formatters = List(config=True) | |
|
66 | ||
|
67 | # Each call to the In[] prompt raises it by 1, even the first. | |
|
68 | #prompt_count = Int(0) | |
|
69 | ||
|
70 | 59 | def __init__(self, shell=None, cache_size=1000, |
|
71 | 60 | colors='NoColor', input_sep='\n', |
|
72 | 61 | output_sep='\n', output_sep2='', |
|
73 | 62 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, |
|
74 | 63 | config=None): |
|
75 | 64 | super(DisplayHook, self).__init__(shell=shell, config=config) |
|
76 | 65 | |
|
77 | 66 | cache_size_min = 3 |
|
78 | 67 | if cache_size <= 0: |
|
79 | 68 | self.do_full_cache = 0 |
|
80 | 69 | cache_size = 0 |
|
81 | 70 | elif cache_size < cache_size_min: |
|
82 | 71 | self.do_full_cache = 0 |
|
83 | 72 | cache_size = 0 |
|
84 | 73 | warn('caching was disabled (min value for cache size is %s).' % |
|
85 | 74 | cache_size_min,level=3) |
|
86 | 75 | else: |
|
87 | 76 | self.do_full_cache = 1 |
|
88 | 77 | |
|
89 | 78 | self.cache_size = cache_size |
|
90 | 79 | self.input_sep = input_sep |
|
91 | 80 | |
|
92 | 81 | # we need a reference to the user-level namespace |
|
93 | 82 | self.shell = shell |
|
94 | 83 | |
|
95 | 84 | # Set input prompt strings and colors |
|
96 | 85 | if cache_size == 0: |
|
97 | 86 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ |
|
98 | 87 | or ps1.find(r'\N') > -1: |
|
99 | 88 | ps1 = '>>> ' |
|
100 | 89 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ |
|
101 | 90 | or ps2.find(r'\N') > -1: |
|
102 | 91 | ps2 = '... ' |
|
103 | 92 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') |
|
104 | 93 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') |
|
105 | 94 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') |
|
106 | 95 | |
|
107 | 96 | self.color_table = prompts.PromptColors |
|
108 | 97 | self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str, |
|
109 | 98 | pad_left=pad_left) |
|
110 | 99 | self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) |
|
111 | 100 | self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str, |
|
112 | 101 | pad_left=pad_left) |
|
113 | 102 | self.set_colors(colors) |
|
114 | 103 | |
|
115 | 104 | # Store the last prompt string each time, we need it for aligning |
|
116 | 105 | # continuation and auto-rewrite prompts |
|
117 | 106 | self.last_prompt = '' |
|
118 | 107 | self.output_sep = output_sep |
|
119 | 108 | self.output_sep2 = output_sep2 |
|
120 | 109 | self._,self.__,self.___ = '','','' |
|
121 | 110 | |
|
122 | 111 | # these are deliberately global: |
|
123 | 112 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
124 | 113 | self.shell.user_ns.update(to_user_ns) |
|
125 | 114 | |
|
126 | 115 | @property |
|
127 | 116 | def prompt_count(self): |
|
128 | 117 | return self.shell.execution_count |
|
129 | 118 | |
|
130 | 119 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): |
|
131 | 120 | if p_str is None: |
|
132 | 121 | if self.do_full_cache: |
|
133 | 122 | return cache_def |
|
134 | 123 | else: |
|
135 | 124 | return no_cache_def |
|
136 | 125 | else: |
|
137 | 126 | return p_str |
|
138 | 127 | |
|
139 | 128 | def set_colors(self, colors): |
|
140 | 129 | """Set the active color scheme and configure colors for the three |
|
141 | 130 | prompt subsystems.""" |
|
142 | 131 | |
|
143 | 132 | # FIXME: This modifying of the global prompts.prompt_specials needs |
|
144 | 133 | # to be fixed. We need to refactor all of the prompts stuff to use |
|
145 | 134 | # proper configuration and traits notifications. |
|
146 | 135 | if colors.lower()=='nocolor': |
|
147 | 136 | prompts.prompt_specials = prompts.prompt_specials_nocolor |
|
148 | 137 | else: |
|
149 | 138 | prompts.prompt_specials = prompts.prompt_specials_color |
|
150 | 139 | |
|
151 | 140 | self.color_table.set_active_scheme(colors) |
|
152 | 141 | self.prompt1.set_colors() |
|
153 | 142 | self.prompt2.set_colors() |
|
154 | 143 | self.prompt_out.set_colors() |
|
155 | 144 | |
|
156 | 145 | #------------------------------------------------------------------------- |
|
157 | 146 | # Methods used in __call__. Override these methods to modify the behavior |
|
158 | 147 | # of the displayhook. |
|
159 | 148 | #------------------------------------------------------------------------- |
|
160 | 149 | |
|
161 | 150 | def check_for_underscore(self): |
|
162 | 151 | """Check if the user has set the '_' variable by hand.""" |
|
163 | 152 | # If something injected a '_' variable in __builtin__, delete |
|
164 | 153 | # ipython's automatic one so we don't clobber that. gettext() in |
|
165 | 154 | # particular uses _, so we need to stay away from it. |
|
166 | 155 | if '_' in __builtin__.__dict__: |
|
167 | 156 | try: |
|
168 | 157 | del self.shell.user_ns['_'] |
|
169 | 158 | except KeyError: |
|
170 | 159 | pass |
|
171 | 160 | |
|
172 | 161 | def quiet(self): |
|
173 | 162 | """Should we silence the display hook because of ';'?""" |
|
174 | 163 | # do not print output if input ends in ';' |
|
175 | 164 | try: |
|
176 | 165 | if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'): |
|
177 | 166 | return True |
|
178 | 167 | except IndexError: |
|
179 | 168 | # some uses of ipshellembed may fail here |
|
180 | 169 | pass |
|
181 | 170 | return False |
|
182 | 171 | |
|
183 | 172 | def start_displayhook(self): |
|
184 | 173 | """Start the displayhook, initializing resources.""" |
|
185 | 174 | pass |
|
186 | 175 | |
|
187 | 176 | def write_output_prompt(self): |
|
188 |
"""Write the output prompt. |
|
|
177 | """Write the output prompt. | |
|
178 | ||
|
179 | The default implementation simply writes the prompt to | |
|
180 | ``io.Term.cout``. | |
|
181 | """ | |
|
189 | 182 | # Use write, not print which adds an extra space. |
|
190 | 183 | IPython.utils.io.Term.cout.write(self.output_sep) |
|
191 | 184 | outprompt = str(self.prompt_out) |
|
192 | 185 | if self.do_full_cache: |
|
193 | 186 | IPython.utils.io.Term.cout.write(outprompt) |
|
194 | 187 | |
|
195 |
def compute_ |
|
|
196 |
"""Compute |
|
|
188 | def compute_format_data(self, result): | |
|
189 | """Compute format data of the object to be displayed. | |
|
197 | 190 | |
|
198 | This method only compute the string form of the repr and should NOT | |
|
191 | The format data is a generalization of the :func:`repr` of an object. | |
|
192 | In the default implementation the format data is a :class:`dict` of | |
|
193 | key value pair where the keys are valid MIME types and the values | |
|
194 | are JSON'able data structure containing the raw data for that MIME | |
|
195 | type. It is up to frontends to determine pick a MIME to to use and | |
|
196 | display that data in an appropriate manner. | |
|
197 | ||
|
198 | This method only compute the format data for the object and should NOT | |
|
199 | 199 | actually print or write that to a stream. |
|
200 | ||
|
201 | Parameters | |
|
202 | ---------- | |
|
203 | result : object | |
|
204 | The Python object passed to the display hook, whose forat will be | |
|
205 | computed. | |
|
206 | ||
|
207 | Returns | |
|
208 | ------- | |
|
209 | format_data : dict | |
|
210 | A :class:`dict` whose keys are valid MIME types and values are | |
|
211 | JSON'able raw data for that MIME type. It is recommended that | |
|
212 | all return values of this should always include the "text/plain" | |
|
213 | MIME type representation of the object. | |
|
200 | 214 | """ |
|
201 |
|
|
|
202 |
|
|
|
203 | for f in self.extra_formatters: | |
|
204 | try: | |
|
205 | data = f(result) | |
|
206 | except Exception: | |
|
207 | # FIXME: log the exception. | |
|
208 | continue | |
|
209 | if data is not None: | |
|
210 | extra_formats.append((f.id, f.format, data)) | |
|
215 | format_dict = self.shell.display_formatter.format(result) | |
|
216 | return format_dict | |
|
211 | 217 | |
|
212 | return result_repr, extra_formats | |
|
218 | def write_format_data(self, format_dict): | |
|
219 | """Write the format data dict to the frontend. | |
|
213 | 220 |
|
|
214 | def write_result_repr(self, result_repr, extra_formats): | |
|
221 | This default version of this method simply writes the plain text | |
|
222 | representation of the object to ``io.Term.cout``. Subclasses should | |
|
223 | override this method to send the entire `format_dict` to the | |
|
224 | frontends. | |
|
225 | ||
|
226 | Parameters | |
|
227 | ---------- | |
|
228 | format_dict : dict | |
|
229 | The format dict for the object passed to `sys.displayhook`. | |
|
230 | """ | |
|
215 | 231 | # We want to print because we want to always make sure we have a |
|
216 | 232 | # newline, even if all the prompt separators are ''. This is the |
|
217 | 233 | # standard IPython behavior. |
|
234 | result_repr = format_dict['text/plain'] | |
|
218 | 235 | if '\n' in result_repr: |
|
219 | 236 | # So that multi-line strings line up with the left column of |
|
220 | 237 | # the screen, instead of having the output prompt mess up |
|
221 | 238 | # their first line. |
|
222 | 239 | # We use the ps_out_str template instead of the expanded prompt |
|
223 | 240 | # because the expansion may add ANSI escapes that will interfere |
|
224 | 241 | # with our ability to determine whether or not we should add |
|
225 | 242 | # a newline. |
|
226 | 243 | if self.ps_out_str and not self.ps_out_str.endswith('\n'): |
|
227 | 244 | # But avoid extraneous empty lines. |
|
228 | 245 | result_repr = '\n' + result_repr |
|
229 | 246 | |
|
230 | 247 | print >>IPython.utils.io.Term.cout, result_repr |
|
231 | 248 | |
|
232 | 249 | def update_user_ns(self, result): |
|
233 | 250 | """Update user_ns with various things like _, __, _1, etc.""" |
|
234 | 251 | |
|
235 | 252 | # Avoid recursive reference when displaying _oh/Out |
|
236 | 253 | if result is not self.shell.user_ns['_oh']: |
|
237 | 254 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
238 | 255 | warn('Output cache limit (currently '+ |
|
239 | 256 | `self.cache_size`+' entries) hit.\n' |
|
240 | 257 | 'Flushing cache and resetting history counter...\n' |
|
241 | 258 | 'The only history variables available will be _,__,___ and _1\n' |
|
242 | 259 | 'with the current result.') |
|
243 | 260 | |
|
244 | 261 | self.flush() |
|
245 | 262 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
246 | 263 | # we cause buggy behavior for things like gettext). |
|
247 | 264 | if '_' not in __builtin__.__dict__: |
|
248 | 265 | self.___ = self.__ |
|
249 | 266 | self.__ = self._ |
|
250 | 267 | self._ = result |
|
251 | 268 | self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) |
|
252 | 269 | |
|
253 | 270 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
254 | 271 | to_main = {} |
|
255 | 272 | if self.do_full_cache: |
|
256 | 273 | new_result = '_'+`self.prompt_count` |
|
257 | 274 | to_main[new_result] = result |
|
258 | 275 | self.shell.user_ns.update(to_main) |
|
259 | 276 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
260 | 277 | |
|
261 | 278 | def log_output(self, result): |
|
262 | 279 | """Log the output.""" |
|
263 | 280 | if self.shell.logger.log_output: |
|
264 | 281 | self.shell.logger.log_write(repr(result), 'output') |
|
265 | 282 | |
|
266 | 283 | def finish_displayhook(self): |
|
267 | 284 | """Finish up all displayhook activities.""" |
|
268 | 285 | IPython.utils.io.Term.cout.write(self.output_sep2) |
|
269 | 286 | IPython.utils.io.Term.cout.flush() |
|
270 | 287 | |
|
271 | 288 | def __call__(self, result=None): |
|
272 | 289 | """Printing with history cache management. |
|
273 | 290 | |
|
274 | 291 | This is invoked everytime the interpreter needs to print, and is |
|
275 | 292 | activated by setting the variable sys.displayhook to it. |
|
276 | 293 | """ |
|
277 | 294 | self.check_for_underscore() |
|
278 | 295 | if result is not None and not self.quiet(): |
|
279 | 296 | self.start_displayhook() |
|
280 | 297 | self.write_output_prompt() |
|
281 |
|
|
|
282 | self.write_result_repr(result_repr, extra_formats) | |
|
298 | format_dict = self.compute_format_data(result) | |
|
299 | self.write_format_data(format_dict) | |
|
283 | 300 | self.update_user_ns(result) |
|
284 | 301 | self.log_output(result) |
|
285 | 302 | self.finish_displayhook() |
|
286 | 303 | |
|
287 | 304 | def flush(self): |
|
288 | 305 | if not self.do_full_cache: |
|
289 | 306 | raise ValueError,"You shouldn't have reached the cache flush "\ |
|
290 | 307 | "if full caching is not enabled!" |
|
291 | 308 | # delete auto-generated vars from global namespace |
|
292 | 309 | |
|
293 | 310 | for n in range(1,self.prompt_count + 1): |
|
294 | 311 | key = '_'+`n` |
|
295 | 312 | try: |
|
296 | 313 | del self.shell.user_ns[key] |
|
297 | 314 | except: pass |
|
298 | 315 | self.shell.user_ns['_oh'].clear() |
|
299 | 316 | |
|
300 | 317 | if '_' not in __builtin__.__dict__: |
|
301 | 318 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
302 | 319 | import gc |
|
303 | gc.collect() # xxx needed? | |
|
320 | # TODO: Is this really needed? | |
|
321 | gc.collect() | |
|
304 | 322 |
@@ -1,103 +1,143 b'' | |||
|
1 | # -*- coding: utf-8 -*- | |
|
2 | 1 |
|
|
3 | 2 | |
|
3 | There are two components of the display system: | |
|
4 | ||
|
5 | * Display formatters, which take a Python object and compute the | |
|
6 | representation of the object in various formats (text, HTML, SVg, etc.). | |
|
7 | * The display publisher that is used to send the representation data to the | |
|
8 | various frontends. | |
|
9 | ||
|
10 | This module defines the logic display publishing. The display publisher uses | |
|
11 | the ``display_data`` message type that is defined in the IPython messaging | |
|
12 | spec. | |
|
13 | ||
|
4 | 14 | Authors: |
|
5 | 15 | |
|
6 | 16 | * Brian Granger |
|
7 | 17 | """ |
|
8 | 18 | |
|
9 | 19 | #----------------------------------------------------------------------------- |
|
10 | 20 | # Copyright (C) 2008-2010 The IPython Development Team |
|
11 | 21 | # |
|
12 | 22 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | 23 | # the file COPYING, distributed as part of this software. |
|
14 | 24 | #----------------------------------------------------------------------------- |
|
15 | 25 | |
|
16 | 26 | #----------------------------------------------------------------------------- |
|
17 | 27 | # Imports |
|
18 | 28 | #----------------------------------------------------------------------------- |
|
19 | 29 | |
|
20 | 30 | from IPython.config.configurable import Configurable |
|
21 | 31 | |
|
22 | 32 | #----------------------------------------------------------------------------- |
|
23 | 33 | # Main payload class |
|
24 | 34 | #----------------------------------------------------------------------------- |
|
25 | 35 | |
|
26 | 36 | class DisplayPublisher(Configurable): |
|
37 | """A traited class that publishes display data to frontends. | |
|
38 | ||
|
39 | Instances of this class are created by the main IPython object and should | |
|
40 | be accessed there. | |
|
41 | """ | |
|
27 | 42 | |
|
28 | 43 | def _validate_data(self, source, data, metadata=None): |
|
44 | """Validate the display data. | |
|
45 | ||
|
46 | Parameters | |
|
47 | ---------- | |
|
48 | source : str | |
|
49 | The fully dotted name of the callable that created the data, like | |
|
50 | :func:`foo.bar.my_formatter`. | |
|
51 | data : dict | |
|
52 | The formata data dictionary. | |
|
53 | metadata : dict | |
|
54 | Any metadata for the data. | |
|
55 | """ | |
|
56 | ||
|
29 | 57 | if not isinstance(source, str): |
|
30 | 58 | raise TypeError('source must be a str, got: %r' % source) |
|
31 | 59 | if not isinstance(data, dict): |
|
32 | 60 | raise TypeError('data must be a dict, got: %r' % data) |
|
33 | 61 | if metadata is not None: |
|
34 | 62 | if not isinstance(metadata, dict): |
|
35 | 63 | raise TypeError('metadata must be a dict, got: %r' % data) |
|
36 | 64 | |
|
37 | 65 | def publish(self, source, data, metadata=None): |
|
38 | 66 | """Publish data and metadata to all frontends. |
|
39 | 67 | |
|
40 | 68 | See the ``display_data`` message in the messaging documentation for |
|
41 | 69 | more details about this message type. |
|
42 | 70 | |
|
71 | The following MIME types are currently implemented: | |
|
72 | ||
|
73 | * text/plain | |
|
74 | * text/html | |
|
75 | * text/latex | |
|
76 | * application/json | |
|
77 | * image/png | |
|
78 | * immage/svg+xml | |
|
79 | ||
|
43 | 80 | Parameters |
|
44 | 81 | ---------- |
|
45 | 82 | source : str |
|
46 | 83 | A string that give the function or method that created the data, |
|
47 | 84 | such as 'IPython.core.page'. |
|
48 | 85 | data : dict |
|
49 | 86 | A dictionary having keys that are valid MIME types (like |
|
50 | 87 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
51 | 88 | that MIME type. The data itself must be a JSON'able data |
|
52 | 89 | structure. Minimally all data should have the 'text/plain' data, |
|
53 | 90 | which can be displayed by all frontends. If more than the plain |
|
54 | 91 | text is given, it is up to the frontend to decide which |
|
55 | 92 | representation to use. |
|
56 | 93 | metadata : dict |
|
57 | 94 | A dictionary for metadata related to the data. This can contain |
|
58 | 95 | arbitrary key, value pairs that frontends can use to interpret |
|
59 | 96 | the data. |
|
60 | 97 | """ |
|
61 | 98 | from IPython.utils import io |
|
62 | 99 | # The default is to simply write the plain text data using io.Term. |
|
63 | 100 | if data.has_key('text/plain'): |
|
64 | 101 | print >>io.Term.cout, data['text/plain'] |
|
65 | 102 | |
|
66 | 103 | |
|
67 |
def publish_display_data(source, |
|
|
68 | html=None, metadata=None): | |
|
69 | """Publish a display data to the frontends. | |
|
104 | def publish_display_data(self, source, data, metadata=None): | |
|
105 | """Publish data and metadata to all frontends. | |
|
70 | 106 | |
|
71 | This function is a high level helper for the publishing of display data. | |
|
72 | It handle a number of common MIME types in a clean API. For other MIME | |
|
73 | types, use ``get_ipython().display_pub.publish`` directly. | |
|
107 | See the ``display_data`` message in the messaging documentation for | |
|
108 | more details about this message type. | |
|
74 | 109 | |
|
75 | Parameters | |
|
76 | ---------- | |
|
77 | text : str/unicode | |
|
78 | The string representation of the plot. | |
|
110 | The following MIME types are currently implemented: | |
|
79 | 111 | |
|
80 | svn : str/unicode | |
|
81 | The raw svg data of the plot. | |
|
112 | * text/plain | |
|
113 | * text/html | |
|
114 | * text/latex | |
|
115 | * application/json | |
|
116 | * image/png | |
|
117 | * immage/svg+xml | |
|
82 | 118 | |
|
83 | png : ??? | |
|
84 | The raw png data of the plot. | |
|
85 | ||
|
86 | metadata : dict, optional [default empty] | |
|
87 | Allows for specification of additional information about the plot data. | |
|
119 | Parameters | |
|
120 | ---------- | |
|
121 | source : str | |
|
122 | A string that give the function or method that created the data, | |
|
123 | such as 'IPython.core.page'. | |
|
124 | data : dict | |
|
125 | A dictionary having keys that are valid MIME types (like | |
|
126 | 'text/plain' or 'image/svg+xml') and values that are the data for | |
|
127 | that MIME type. The data itself must be a JSON'able data | |
|
128 | structure. Minimally all data should have the 'text/plain' data, | |
|
129 | which can be displayed by all frontends. If more than the plain | |
|
130 | text is given, it is up to the frontend to decide which | |
|
131 | representation to use. | |
|
132 | metadata : dict | |
|
133 | A dictionary for metadata related to the data. This can contain | |
|
134 | arbitrary key, value pairs that frontends can use to interpret | |
|
135 | the data. | |
|
88 | 136 | """ |
|
89 | 137 | from IPython.core.interactiveshell import InteractiveShell |
|
90 | ||
|
91 | data_dict = {} | |
|
92 | data_dict['text/plain'] = text | |
|
93 | if svg is not None: | |
|
94 | data_dict['image/svg+xml'] = svg | |
|
95 | if png is not None: | |
|
96 | data_dict['image/png'] = png | |
|
97 | if html is not None: | |
|
98 | data_dict['text/html'] = html | |
|
99 | 138 | InteractiveShell.instance().display_pub.publish( |
|
100 | 139 | source, |
|
101 |
data |
|
|
140 | data, | |
|
102 | 141 | metadata |
|
103 | 142 | ) |
|
143 |
@@ -1,169 +1,453 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 |
"""Display |
|
|
3 | ||
|
4 | The DefaultFormatter is always present and may be configured from the | |
|
5 | ipython_config.py file. For example, to add a pretty-printer for a numpy.dtype | |
|
6 | object:: | |
|
7 | ||
|
8 | def dtype_pprinter(obj, p, cycle): | |
|
9 | if cycle: | |
|
10 | return p.text('dtype(...)') | |
|
11 | if hasattr(obj, 'fields'): | |
|
12 | if obj.fields is None: | |
|
13 | p.text(repr(obj)) | |
|
14 | else: | |
|
15 | p.begin_group(7, 'dtype([') | |
|
16 | for i, field in enumerate(obj.descr): | |
|
17 | if i > 0: | |
|
18 | p.text(',') | |
|
19 | p.breakable() | |
|
20 | p.pretty(field) | |
|
21 | p.end_group(7, '])') | |
|
22 | ||
|
23 | c.DefaultFormatter.deferred_pprinters = { | |
|
24 | ('numpy', 'dtype'): dtype_pprinter, | |
|
25 | } | |
|
26 | ||
|
27 | The deferred_pprinters dictionary is the preferred way to configure these | |
|
28 | pretty-printers. This allows you to define the pretty-printer without needing to | |
|
29 | import the type itself. The dictionary maps (modulename, typename) pairs to | |
|
30 | a function. | |
|
31 | ||
|
32 | See the `IPython.external.pretty` documentation for how to write | |
|
33 | pretty-printer functions. | |
|
2 | """Display formatters. | |
|
3 | ||
|
4 | ||
|
5 | Authors: | |
|
6 | ||
|
7 | * Robert Kern | |
|
8 | * Brian Granger | |
|
34 | 9 | """ |
|
35 | 10 | #----------------------------------------------------------------------------- |
|
36 | 11 | # Copyright (c) 2010, IPython Development Team. |
|
37 | 12 | # |
|
38 | 13 | # Distributed under the terms of the Modified BSD License. |
|
39 | 14 | # |
|
40 | 15 | # The full license is in the file COPYING.txt, distributed with this software. |
|
41 | 16 | #----------------------------------------------------------------------------- |
|
42 | 17 | |
|
43 | 18 | # Stdlib imports |
|
44 | 19 | import abc |
|
45 | from cStringIO import StringIO | |
|
20 | # We must use StringIO, as cStringIO doesn't handle unicode properly. | |
|
21 | from StringIO import StringIO | |
|
46 | 22 | |
|
47 | 23 | # Our own imports |
|
48 | 24 | from IPython.config.configurable import Configurable |
|
49 | 25 | from IPython.external import pretty |
|
50 | 26 | from IPython.utils.traitlets import Bool, Dict, Int, Str |
|
51 | 27 | |
|
52 | 28 | |
|
53 | 29 | #----------------------------------------------------------------------------- |
|
54 | # Classes and functions | |
|
30 | # The main DisplayFormatter class | |
|
55 | 31 | #----------------------------------------------------------------------------- |
|
56 | 32 | |
|
57 | class DefaultFormatter(Configurable): | |
|
58 | """ The default pretty-printer. | |
|
33 | ||
|
34 | class DisplayFormatter(Configurable): | |
|
35 | ||
|
36 | # A dict of formatter whose keys are format types (MIME types) and whose | |
|
37 | # values are subclasses of BaseFormatter. | |
|
38 | formatters = Dict(config=True) | |
|
39 | def _formatters_default(self): | |
|
40 | """Activate the default formatters.""" | |
|
41 | formatter_classes = [ | |
|
42 | PlainTextFormatter, | |
|
43 | HTMLFormatter, | |
|
44 | SVGFormatter, | |
|
45 | PNGFormatter, | |
|
46 | LatexFormatter, | |
|
47 | JSONFormatter | |
|
48 | ] | |
|
49 | d = {} | |
|
50 | for cls in formatter_classes: | |
|
51 | f = cls(config=self.config) | |
|
52 | d[f.format_type] = f | |
|
53 | return d | |
|
54 | ||
|
55 | def format(self, obj, include=None, exclude=None): | |
|
56 | """Return a format data dict for an object. | |
|
57 | ||
|
58 | By default all format types will be computed. | |
|
59 | ||
|
60 | The following MIME types are currently implemented: | |
|
61 | ||
|
62 | * text/plain | |
|
63 | * text/html | |
|
64 | * text/latex | |
|
65 | * application/json | |
|
66 | * image/png | |
|
67 | * immage/svg+xml | |
|
68 | ||
|
69 | Parameters | |
|
70 | ---------- | |
|
71 | obj : object | |
|
72 | The Python object whose format data will be computed. | |
|
73 | ||
|
74 | Returns | |
|
75 | ------- | |
|
76 | format_dict : dict | |
|
77 | A dictionary of key/value pairs, one or each format that was | |
|
78 | generated for the object. The keys are the format types, which | |
|
79 | will usually be MIME type strings and the values and JSON'able | |
|
80 | data structure containing the raw data for the representation in | |
|
81 | that format. | |
|
82 | include : list or tuple, optional | |
|
83 | A list of format type strings (MIME types) to include in the | |
|
84 | format data dict. If this is set *only* the format types included | |
|
85 | in this list will be computed. | |
|
86 | exclude : list or tuple, optional | |
|
87 | A list of format type string (MIME types) to exclue in the format | |
|
88 | data dict. If this is set all format types will be computed, | |
|
89 | except for those included in this argument. | |
|
90 | """ | |
|
91 | format_dict = {} | |
|
92 | for format_type, formatter in self.formatters.items(): | |
|
93 | if include is not None: | |
|
94 | if format_type not in include: | |
|
95 | continue | |
|
96 | if exclude is not None: | |
|
97 | if format_type in exclude: | |
|
98 | continue | |
|
99 | try: | |
|
100 | data = formatter(obj) | |
|
101 | except: | |
|
102 | # FIXME: log the exception | |
|
103 | raise | |
|
104 | if data is not None: | |
|
105 | format_dict[format_type] = data | |
|
106 | return format_dict | |
|
107 | ||
|
108 | @property | |
|
109 | def format_types(self): | |
|
110 | """Return the format types (MIME types) of the active formatters.""" | |
|
111 | return self.formatters.keys() | |
|
112 | ||
|
113 | ||
|
114 | #----------------------------------------------------------------------------- | |
|
115 | # Formatters for specific format types (text, html, svg, etc.) | |
|
116 | #----------------------------------------------------------------------------- | |
|
117 | ||
|
118 | ||
|
119 | class FormatterABC(object): | |
|
120 | """ Abstract base class for Formatters. | |
|
121 | ||
|
122 | A formatter is a callable class that is responsible for computing the | |
|
123 | raw format data for a particular format type (MIME type). For example, | |
|
124 | an HTML formatter would have a format type of `text/html` and would return | |
|
125 | the HTML representation of the object when called. | |
|
59 | 126 | """ |
|
127 | __metaclass__ = abc.ABCMeta | |
|
60 | 128 | |
|
61 | # The ID of the formatter. | |
|
62 | id = Str('default') | |
|
129 | # The format type of the data returned, usually a MIME type. | |
|
130 | format_type = 'text/plain' | |
|
63 | 131 | |
|
64 | # The kind of data returned. | |
|
65 | # This is often, but not always a MIME type. | |
|
66 | format = Str('text/plain') | |
|
132 | @abc.abstractmethod | |
|
133 | def __call__(self, obj): | |
|
134 | """Return a JSON'able representation of the object. | |
|
135 | ||
|
136 | If the object cannot be formatted by this formatter, then return None | |
|
137 | """ | |
|
138 | try: | |
|
139 | return repr(obj) | |
|
140 | except TypeError: | |
|
141 | return None | |
|
142 | ||
|
143 | ||
|
144 | class BaseFormatter(Configurable): | |
|
145 | """A base formatter class that is configurable. | |
|
146 | ||
|
147 | This formatter should usually be used as the base class of all formatters. | |
|
148 | It is a traited :class:`Configurable` class and includes an extensible | |
|
149 | API for users to determine how their objects are formatted. The following | |
|
150 | logic is used to find a function to format an given object. | |
|
151 | ||
|
152 | 1. The object is introspected to see if it has a method with the name | |
|
153 | :attr:`print_method`. If is does, that object is passed to that method | |
|
154 | for formatting. | |
|
155 | 2. If no print method is found, three internal dictionaries are consulted | |
|
156 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
|
157 | and :attr:`deferred_printers`. | |
|
158 | ||
|
159 | Users should use these dictionarie to register functions that will be used | |
|
160 | to compute the format data for their objects (if those objects don't have | |
|
161 | the special print methods). The easiest way of using these dictionaries | |
|
162 | is through the :meth:`for_type` and :meth:`for_type_by_name` methods. | |
|
163 | ||
|
164 | If no function/callable is found to compute the format data, ``None`` is | |
|
165 | returned and this format type is not used. | |
|
166 | """ | |
|
167 | ||
|
168 | format_type = Str('text/plain') | |
|
169 | ||
|
170 | print_method = Str('__repr__') | |
|
171 | ||
|
172 | # The singleton printers. | |
|
173 | # Maps the IDs of the builtin singleton objects to the format functions. | |
|
174 | singleton_printers = Dict(config=True) | |
|
175 | def _singleton_printers_default(self): | |
|
176 | return {} | |
|
177 | ||
|
178 | # The type-specific printers. | |
|
179 | # Map type objects to the format functions. | |
|
180 | type_printers = Dict(config=True) | |
|
181 | def _type_printers_default(self): | |
|
182 | return {} | |
|
183 | ||
|
184 | # The deferred-import type-specific printers. | |
|
185 | # Map (modulename, classname) pairs to the format functions. | |
|
186 | deferred_printers = Dict(config=True) | |
|
187 | def _deferred_printers_default(self): | |
|
188 | return {} | |
|
189 | ||
|
190 | def __call__(self, obj): | |
|
191 | """Compute the format for an object.""" | |
|
192 | obj_id = id(obj) | |
|
193 | try: | |
|
194 | obj_class = getattr(obj, '__class__', None) or type(obj) | |
|
195 | if hasattr(obj_class, self.print_method): | |
|
196 | printer = getattr(obj_class, self.print_method) | |
|
197 | return printer(obj) | |
|
198 | try: | |
|
199 | printer = self.singleton_printers[obj_id] | |
|
200 | except (TypeError, KeyError): | |
|
201 | pass | |
|
202 | else: | |
|
203 | return printer(obj) | |
|
204 | for cls in pretty._get_mro(obj_class): | |
|
205 | if cls in self.type_printers: | |
|
206 | return self.type_printers[cls](obj) | |
|
207 | else: | |
|
208 | printer = self._in_deferred_types(cls) | |
|
209 | if printer is not None: | |
|
210 | return printer(obj) | |
|
211 | return None | |
|
212 | except Exception: | |
|
213 | pass | |
|
214 | ||
|
215 | def for_type(self, typ, func): | |
|
216 | """Add a format function for a given type. | |
|
217 | ||
|
218 | Parameteres | |
|
219 | ----------- | |
|
220 | typ : class | |
|
221 | The class of the object that will be formatted using `func`. | |
|
222 | func : callable | |
|
223 | The callable that will be called to compute the format data. The | |
|
224 | call signature of this function is simple, it must take the | |
|
225 | object to be formatted and return the raw data for the given | |
|
226 | format. Subclasses may use a different call signature for the | |
|
227 | `func` argument. | |
|
228 | """ | |
|
229 | oldfunc = self.type_printers.get(typ, None) | |
|
230 | if func is not None: | |
|
231 | # To support easy restoration of old printers, we need to ignore | |
|
232 | # Nones. | |
|
233 | self.type_printers[typ] = func | |
|
234 | return oldfunc | |
|
235 | ||
|
236 | def for_type_by_name(self, type_module, type_name, func): | |
|
237 | """Add a format function for a type specified by the full dotted | |
|
238 | module and name of the type, rather than the type of the object. | |
|
239 | ||
|
240 | Parameters | |
|
241 | ---------- | |
|
242 | type_module : str | |
|
243 | The full dotted name of the module the type is defined in, like | |
|
244 | ``numpy``. | |
|
245 | type_name : str | |
|
246 | The name of the type (the class name), like ``dtype`` | |
|
247 | func : callable | |
|
248 | The callable that will be called to compute the format data. The | |
|
249 | call signature of this function is simple, it must take the | |
|
250 | object to be formatted and return the raw data for the given | |
|
251 | format. Subclasses may use a different call signature for the | |
|
252 | `func` argument. | |
|
253 | """ | |
|
254 | key = (type_module, type_name) | |
|
255 | oldfunc = self.deferred_printers.get(key, None) | |
|
256 | if func is not None: | |
|
257 | # To support easy restoration of old printers, we need to ignore | |
|
258 | # Nones. | |
|
259 | self.deferred_printers[key] = func | |
|
260 | return oldfunc | |
|
261 | ||
|
262 | ||
|
263 | class PlainTextFormatter(BaseFormatter): | |
|
264 | """The default pretty-printer. | |
|
265 | ||
|
266 | This uses :mod:`IPython.external.pretty` to compute the format data of | |
|
267 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
|
268 | See the documentation of :mod:`IPython.external.pretty` for details on | |
|
269 | how to write pretty printers. Here is a simple example:: | |
|
270 | ||
|
271 | def dtype_pprinter(obj, p, cycle): | |
|
272 | if cycle: | |
|
273 | return p.text('dtype(...)') | |
|
274 | if hasattr(obj, 'fields'): | |
|
275 | if obj.fields is None: | |
|
276 | p.text(repr(obj)) | |
|
277 | else: | |
|
278 | p.begin_group(7, 'dtype([') | |
|
279 | for i, field in enumerate(obj.descr): | |
|
280 | if i > 0: | |
|
281 | p.text(',') | |
|
282 | p.breakable() | |
|
283 | p.pretty(field) | |
|
284 | p.end_group(7, '])') | |
|
285 | """ | |
|
286 | ||
|
287 | # The format type of data returned. | |
|
288 | format_type = Str('text/plain') | |
|
289 | ||
|
290 | # Look for a __pretty__ methods to use for pretty printing. | |
|
291 | print_method = Str('__pretty__') | |
|
67 | 292 | |
|
68 | 293 | # Whether to pretty-print or not. |
|
69 | 294 | pprint = Bool(True, config=True) |
|
70 | 295 | |
|
71 | 296 | # Whether to be verbose or not. |
|
72 | 297 | verbose = Bool(False, config=True) |
|
73 | 298 | |
|
74 | 299 | # The maximum width. |
|
75 | 300 | max_width = Int(79, config=True) |
|
76 | 301 | |
|
77 | 302 | # The newline character. |
|
78 | 303 | newline = Str('\n', config=True) |
|
79 | 304 | |
|
80 | # The singleton prettyprinters. | |
|
81 | # Maps the IDs of the builtin singleton objects to the format functions. | |
|
82 | singleton_pprinters = Dict(config=True) | |
|
83 | def _singleton_pprinters_default(self): | |
|
305 | # Use the default pretty printers from IPython.external.pretty. | |
|
306 | def _singleton_printers_default(self): | |
|
84 | 307 | return pretty._singleton_pprinters.copy() |
|
85 | 308 | |
|
86 | # The type-specific prettyprinters. | |
|
87 | # Map type objects to the format functions. | |
|
88 | type_pprinters = Dict(config=True) | |
|
89 | def _type_pprinters_default(self): | |
|
309 | def _type_printers_default(self): | |
|
90 | 310 | return pretty._type_pprinters.copy() |
|
91 | 311 | |
|
92 | # The deferred-import type-specific prettyprinters. | |
|
93 | # Map (modulename, classname) pairs to the format functions. | |
|
94 | deferred_pprinters = Dict(config=True) | |
|
95 | def _deferred_pprinters_default(self): | |
|
312 | def _deferred_printers_default(self): | |
|
96 | 313 | return pretty._deferred_type_pprinters.copy() |
|
97 | 314 | |
|
98 | 315 | #### FormatterABC interface #### |
|
99 | 316 | |
|
100 | 317 | def __call__(self, obj): |
|
101 | """ Format the object. | |
|
102 | """ | |
|
318 | """Compute the pretty representation of the object.""" | |
|
103 | 319 | if not self.pprint: |
|
104 | 320 | try: |
|
105 | 321 | return repr(obj) |
|
106 | 322 | except TypeError: |
|
107 | 323 | return '' |
|
108 | 324 | else: |
|
325 | # This uses use StringIO, as cStringIO doesn't handle unicode. | |
|
109 | 326 | stream = StringIO() |
|
110 | 327 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
111 | 328 | self.max_width, self.newline, |
|
112 |
singleton_pprinters=self.singleton_p |
|
|
113 |
type_pprinters=self.type_p |
|
|
114 |
deferred_pprinters=self.deferred_p |
|
|
329 | singleton_pprinters=self.singleton_printers, | |
|
330 | type_pprinters=self.type_printers, | |
|
331 | deferred_pprinters=self.deferred_printers) | |
|
115 | 332 | printer.pretty(obj) |
|
116 | 333 | printer.flush() |
|
117 | 334 | return stream.getvalue() |
|
118 | 335 | |
|
119 | 336 | |
|
120 | #### DefaultFormatter interface #### | |
|
337 | class HTMLFormatter(BaseFormatter): | |
|
338 | """An HTML formatter. | |
|
121 | 339 |
|
|
122 | def for_type(self, typ, func): | |
|
123 | """ | |
|
124 | Add a pretty printer for a given type. | |
|
125 | """ | |
|
126 | oldfunc = self.type_pprinters.get(typ, None) | |
|
127 | if func is not None: | |
|
128 | # To support easy restoration of old pprinters, we need to ignore | |
|
129 | # Nones. | |
|
130 | self.type_pprinters[typ] = func | |
|
131 | return oldfunc | |
|
340 | To define the callables that compute the HTML representation of your | |
|
341 | objects, define a :meth:`__html__` method or use the :meth:`for_type` | |
|
342 | or :meth:`for_type_by_name` methods to register functions that handle | |
|
343 | this. | |
|
344 | """ | |
|
345 | format_type = Str('text/html') | |
|
132 | 346 | |
|
133 | def for_type_by_name(self, type_module, type_name, func): | |
|
134 | """ | |
|
135 | Add a pretty printer for a type specified by the module and name of | |
|
136 | a type rather than the type object itself. | |
|
137 | """ | |
|
138 | key = (type_module, type_name) | |
|
139 | oldfunc = self.deferred_pprinters.get(key, None) | |
|
140 | if func is not None: | |
|
141 | # To support easy restoration of old pprinters, we need to ignore | |
|
142 | # Nones. | |
|
143 | self.deferred_pprinters[key] = func | |
|
144 | return oldfunc | |
|
347 | print_method = Str('__html__') | |
|
145 | 348 | |
|
146 | 349 | |
|
147 |
class Formatter |
|
|
148 | """ Abstract base class for Formatters. | |
|
350 | class SVGFormatter(BaseFormatter): | |
|
351 | """An SVG formatter. | |
|
352 | ||
|
353 | To define the callables that compute the SVG representation of your | |
|
354 | objects, define a :meth:`__svg__` method or use the :meth:`for_type` | |
|
355 | or :meth:`for_type_by_name` methods to register functions that handle | |
|
356 | this. | |
|
149 | 357 | """ |
|
150 | __metaclass__ = abc.ABCMeta | |
|
358 | format_type = Str('image/svg+xml') | |
|
151 | 359 | |
|
152 | # The ID of the formatter. | |
|
153 | id = 'abstract' | |
|
360 | print_method = Str('__svg__') | |
|
154 | 361 | |
|
155 | # The kind of data returned. | |
|
156 | format = 'text/plain' | |
|
157 | 362 | |
|
158 | @abc.abstractmethod | |
|
159 | def __call__(self, obj): | |
|
160 | """ Return a JSONable representation of the object. | |
|
363 | class PNGFormatter(BaseFormatter): | |
|
364 | """A PNG formatter. | |
|
161 | 365 | |
|
162 | If the object cannot be formatted by this formatter, then return None | |
|
163 | """ | |
|
164 | try: | |
|
165 | return repr(obj) | |
|
166 | except TypeError: | |
|
167 | return None | |
|
366 | To define the callables that compute the PNG representation of your | |
|
367 | objects, define a :meth:`__svg__` method or use the :meth:`for_type` | |
|
368 | or :meth:`for_type_by_name` methods to register functions that handle | |
|
369 | this. The raw data should be the base64 encoded raw png data. | |
|
370 | """ | |
|
371 | format_type = Str('image/png') | |
|
372 | ||
|
373 | print_method = Str('__png__') | |
|
374 | ||
|
375 | ||
|
376 | class LatexFormatter(BaseFormatter): | |
|
377 | """A LaTeX formatter. | |
|
378 | ||
|
379 | To define the callables that compute the LaTeX representation of your | |
|
380 | objects, define a :meth:`__latex__` method or use the :meth:`for_type` | |
|
381 | or :meth:`for_type_by_name` methods to register functions that handle | |
|
382 | this. | |
|
383 | """ | |
|
384 | format_type = Str('text/latex') | |
|
385 | ||
|
386 | print_method = Str('__latex__') | |
|
387 | ||
|
388 | ||
|
389 | class JSONFormatter(BaseFormatter): | |
|
390 | """A JSON string formatter. | |
|
391 | ||
|
392 | To define the callables that compute the JSON string representation of | |
|
393 | your objects, define a :meth:`__json__` method or use the :meth:`for_type` | |
|
394 | or :meth:`for_type_by_name` methods to register functions that handle | |
|
395 | this. | |
|
396 | """ | |
|
397 | format_type = Str('application/json') | |
|
398 | ||
|
399 | print_method = Str('__json__') | |
|
400 | ||
|
401 | ||
|
402 | FormatterABC.register(BaseFormatter) | |
|
403 | FormatterABC.register(PlainTextFormatter) | |
|
404 | FormatterABC.register(HTMLFormatter) | |
|
405 | FormatterABC.register(SVGFormatter) | |
|
406 | FormatterABC.register(PNGFormatter) | |
|
407 | FormatterABC.register(LatexFormatter) | |
|
408 | FormatterABC.register(JSONFormatter) | |
|
409 | ||
|
410 | ||
|
411 | def format_display_data(obj, include=None, exclude=None): | |
|
412 | """Return a format data dict for an object. | |
|
413 | ||
|
414 | By default all format types will be computed. | |
|
415 | ||
|
416 | The following MIME types are currently implemented: | |
|
417 | ||
|
418 | * text/plain | |
|
419 | * text/html | |
|
420 | * text/latex | |
|
421 | * application/json | |
|
422 | * image/png | |
|
423 | * immage/svg+xml | |
|
424 | ||
|
425 | Parameters | |
|
426 | ---------- | |
|
427 | obj : object | |
|
428 | The Python object whose format data will be computed. | |
|
429 | ||
|
430 | Returns | |
|
431 | ------- | |
|
432 | format_dict : dict | |
|
433 | A dictionary of key/value pairs, one or each format that was | |
|
434 | generated for the object. The keys are the format types, which | |
|
435 | will usually be MIME type strings and the values and JSON'able | |
|
436 | data structure containing the raw data for the representation in | |
|
437 | that format. | |
|
438 | include : list or tuple, optional | |
|
439 | A list of format type strings (MIME types) to include in the | |
|
440 | format data dict. If this is set *only* the format types included | |
|
441 | in this list will be computed. | |
|
442 | exclude : list or tuple, optional | |
|
443 | A list of format type string (MIME types) to exclue in the format | |
|
444 | data dict. If this is set all format types will be computed, | |
|
445 | except for those included in this argument. | |
|
446 | """ | |
|
447 | from IPython.core.interactiveshell import InteractiveShell | |
|
168 | 448 | |
|
169 | FormatterABC.register(DefaultFormatter) | |
|
449 | InteractiveShell.instance().display_formatter.format( | |
|
450 | obj, | |
|
451 | include, | |
|
452 | exclude | |
|
453 | ) |
@@ -1,2550 +1,2556 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Main IPython class.""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
6 | 6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
7 | 7 | # Copyright (C) 2008-2010 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | from __future__ import with_statement |
|
18 | 18 | from __future__ import absolute_import |
|
19 | 19 | |
|
20 | 20 | import __builtin__ |
|
21 | 21 | import __future__ |
|
22 | 22 | import abc |
|
23 | 23 | import atexit |
|
24 | 24 | import codeop |
|
25 | 25 | import os |
|
26 | 26 | import re |
|
27 | 27 | import sys |
|
28 | 28 | import tempfile |
|
29 | 29 | import types |
|
30 | 30 | from contextlib import nested |
|
31 | 31 | |
|
32 | 32 | from IPython.config.configurable import Configurable |
|
33 | 33 | from IPython.core import debugger, oinspect |
|
34 | 34 | from IPython.core import history as ipcorehist |
|
35 | 35 | from IPython.core import page |
|
36 | 36 | from IPython.core import prefilter |
|
37 | 37 | from IPython.core import shadowns |
|
38 | 38 | from IPython.core import ultratb |
|
39 | 39 | from IPython.core.alias import AliasManager |
|
40 | 40 | from IPython.core.builtin_trap import BuiltinTrap |
|
41 | 41 | from IPython.core.compilerop import CachingCompiler |
|
42 | 42 | from IPython.core.display_trap import DisplayTrap |
|
43 | 43 | from IPython.core.displayhook import DisplayHook |
|
44 | 44 | from IPython.core.displaypub import DisplayPublisher |
|
45 | 45 | from IPython.core.error import TryNext, UsageError |
|
46 | 46 | from IPython.core.extensions import ExtensionManager |
|
47 | 47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
48 | from IPython.core.formatters import DisplayFormatter | |
|
48 | 49 | from IPython.core.history import HistoryManager |
|
49 | 50 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
50 | 51 | from IPython.core.logger import Logger |
|
51 | 52 | from IPython.core.magic import Magic |
|
52 | 53 | from IPython.core.payload import PayloadManager |
|
53 | 54 | from IPython.core.plugin import PluginManager |
|
54 | 55 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
55 | 56 | from IPython.external.Itpl import ItplNS |
|
56 | 57 | from IPython.utils import PyColorize |
|
57 | 58 | from IPython.utils import io |
|
58 | 59 | from IPython.utils import pickleshare |
|
59 | 60 | from IPython.utils.doctestreload import doctest_reload |
|
60 | 61 | from IPython.utils.io import ask_yes_no, rprint |
|
61 | 62 | from IPython.utils.ipstruct import Struct |
|
62 | 63 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
63 | 64 | from IPython.utils.process import system, getoutput |
|
64 | 65 | from IPython.utils.strdispatch import StrDispatch |
|
65 | 66 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
66 | 67 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
67 | 68 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
68 | 69 | List, Unicode, Instance, Type) |
|
69 | 70 | from IPython.utils.warn import warn, error, fatal |
|
70 | 71 | import IPython.core.hooks |
|
71 | 72 | |
|
72 | 73 | #----------------------------------------------------------------------------- |
|
73 | 74 | # Globals |
|
74 | 75 | #----------------------------------------------------------------------------- |
|
75 | 76 | |
|
76 | 77 | # compiled regexps for autoindent management |
|
77 | 78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | 79 | |
|
79 | 80 | #----------------------------------------------------------------------------- |
|
80 | 81 | # Utilities |
|
81 | 82 | #----------------------------------------------------------------------------- |
|
82 | 83 | |
|
83 | 84 | # store the builtin raw_input globally, and use this always, in case user code |
|
84 | 85 | # overwrites it (like wx.py.PyShell does) |
|
85 | 86 | raw_input_original = raw_input |
|
86 | 87 | |
|
87 | 88 | def softspace(file, newvalue): |
|
88 | 89 | """Copied from code.py, to remove the dependency""" |
|
89 | 90 | |
|
90 | 91 | oldvalue = 0 |
|
91 | 92 | try: |
|
92 | 93 | oldvalue = file.softspace |
|
93 | 94 | except AttributeError: |
|
94 | 95 | pass |
|
95 | 96 | try: |
|
96 | 97 | file.softspace = newvalue |
|
97 | 98 | except (AttributeError, TypeError): |
|
98 | 99 | # "attribute-less object" or "read-only attributes" |
|
99 | 100 | pass |
|
100 | 101 | return oldvalue |
|
101 | 102 | |
|
102 | 103 | |
|
103 | 104 | def no_op(*a, **kw): pass |
|
104 | 105 | |
|
105 | 106 | class SpaceInInput(Exception): pass |
|
106 | 107 | |
|
107 | 108 | class Bunch: pass |
|
108 | 109 | |
|
109 | 110 | |
|
110 | 111 | def get_default_colors(): |
|
111 | 112 | if sys.platform=='darwin': |
|
112 | 113 | return "LightBG" |
|
113 | 114 | elif os.name=='nt': |
|
114 | 115 | return 'Linux' |
|
115 | 116 | else: |
|
116 | 117 | return 'Linux' |
|
117 | 118 | |
|
118 | 119 | |
|
119 | 120 | class SeparateStr(Str): |
|
120 | 121 | """A Str subclass to validate separate_in, separate_out, etc. |
|
121 | 122 | |
|
122 | 123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
123 | 124 | """ |
|
124 | 125 | |
|
125 | 126 | def validate(self, obj, value): |
|
126 | 127 | if value == '0': value = '' |
|
127 | 128 | value = value.replace('\\n','\n') |
|
128 | 129 | return super(SeparateStr, self).validate(obj, value) |
|
129 | 130 | |
|
130 | 131 | class MultipleInstanceError(Exception): |
|
131 | 132 | pass |
|
132 | 133 | |
|
133 | 134 | |
|
134 | 135 | #----------------------------------------------------------------------------- |
|
135 | 136 | # Main IPython class |
|
136 | 137 | #----------------------------------------------------------------------------- |
|
137 | 138 | |
|
138 | 139 | class InteractiveShell(Configurable, Magic): |
|
139 | 140 | """An enhanced, interactive shell for Python.""" |
|
140 | 141 | |
|
141 | 142 | _instance = None |
|
142 | 143 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
143 | 144 | # TODO: remove all autoindent logic and put into frontends. |
|
144 | 145 | # We can't do this yet because even runlines uses the autoindent. |
|
145 | 146 | autoindent = CBool(True, config=True) |
|
146 | 147 | automagic = CBool(True, config=True) |
|
147 | 148 | cache_size = Int(1000, config=True) |
|
148 | 149 | color_info = CBool(True, config=True) |
|
149 | 150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
150 | 151 | default_value=get_default_colors(), config=True) |
|
151 | 152 | debug = CBool(False, config=True) |
|
152 | 153 | deep_reload = CBool(False, config=True) |
|
154 | display_formatter = Instance(DisplayFormatter) | |
|
153 | 155 | displayhook_class = Type(DisplayHook) |
|
154 | 156 | display_pub_class = Type(DisplayPublisher) |
|
155 | 157 | |
|
156 | 158 | exit_now = CBool(False) |
|
157 | 159 | # Monotonically increasing execution counter |
|
158 | 160 | execution_count = Int(1) |
|
159 | 161 | filename = Str("<ipython console>") |
|
160 | 162 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
161 | 163 | |
|
162 | 164 | # Input splitter, to split entire cells of input into either individual |
|
163 | 165 | # interactive statements or whole blocks. |
|
164 | 166 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
165 | 167 | (), {}) |
|
166 | 168 | logstart = CBool(False, config=True) |
|
167 | 169 | logfile = Str('', config=True) |
|
168 | 170 | logappend = Str('', config=True) |
|
169 | 171 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
170 | 172 | config=True) |
|
171 | 173 | pdb = CBool(False, config=True) |
|
172 | 174 | |
|
173 | 175 | pprint = CBool(True, config=True) |
|
174 | 176 | profile = Str('', config=True) |
|
175 | 177 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
176 | 178 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
177 | 179 | prompt_out = Str('Out[\\#]: ', config=True) |
|
178 | 180 | prompts_pad_left = CBool(True, config=True) |
|
179 | 181 | quiet = CBool(False, config=True) |
|
180 | 182 | |
|
181 | 183 | history_length = Int(10000, config=True) |
|
182 | 184 | |
|
183 | 185 | # The readline stuff will eventually be moved to the terminal subclass |
|
184 | 186 | # but for now, we can't do that as readline is welded in everywhere. |
|
185 | 187 | readline_use = CBool(True, config=True) |
|
186 | 188 | readline_merge_completions = CBool(True, config=True) |
|
187 | 189 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
188 | 190 | readline_remove_delims = Str('-/~', config=True) |
|
189 | 191 | readline_parse_and_bind = List([ |
|
190 | 192 | 'tab: complete', |
|
191 | 193 | '"\C-l": clear-screen', |
|
192 | 194 | 'set show-all-if-ambiguous on', |
|
193 | 195 | '"\C-o": tab-insert', |
|
194 | 196 | '"\M-i": " "', |
|
195 | 197 | '"\M-o": "\d\d\d\d"', |
|
196 | 198 | '"\M-I": "\d\d\d\d"', |
|
197 | 199 | '"\C-r": reverse-search-history', |
|
198 | 200 | '"\C-s": forward-search-history', |
|
199 | 201 | '"\C-p": history-search-backward', |
|
200 | 202 | '"\C-n": history-search-forward', |
|
201 | 203 | '"\e[A": history-search-backward', |
|
202 | 204 | '"\e[B": history-search-forward', |
|
203 | 205 | '"\C-k": kill-line', |
|
204 | 206 | '"\C-u": unix-line-discard', |
|
205 | 207 | ], allow_none=False, config=True) |
|
206 | 208 | |
|
207 | 209 | # TODO: this part of prompt management should be moved to the frontends. |
|
208 | 210 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
209 | 211 | separate_in = SeparateStr('\n', config=True) |
|
210 | 212 | separate_out = SeparateStr('', config=True) |
|
211 | 213 | separate_out2 = SeparateStr('', config=True) |
|
212 | 214 | wildcards_case_sensitive = CBool(True, config=True) |
|
213 | 215 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
214 | 216 | default_value='Context', config=True) |
|
215 | 217 | |
|
216 | 218 | # Subcomponents of InteractiveShell |
|
217 | 219 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
218 | 220 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
219 | 221 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
220 | 222 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
221 | 223 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
222 | 224 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
223 | 225 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
224 | 226 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
225 | 227 | |
|
226 | 228 | # Private interface |
|
227 | 229 | _post_execute = set() |
|
228 | 230 | |
|
229 | 231 | def __init__(self, config=None, ipython_dir=None, |
|
230 | 232 | user_ns=None, user_global_ns=None, |
|
231 | 233 | custom_exceptions=((), None)): |
|
232 | 234 | |
|
233 | 235 | # This is where traits with a config_key argument are updated |
|
234 | 236 | # from the values on config. |
|
235 | 237 | super(InteractiveShell, self).__init__(config=config) |
|
236 | 238 | |
|
237 | 239 | # These are relatively independent and stateless |
|
238 | 240 | self.init_ipython_dir(ipython_dir) |
|
239 | 241 | self.init_instance_attrs() |
|
240 | 242 | self.init_environment() |
|
241 | 243 | |
|
242 | 244 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
243 | 245 | self.init_create_namespaces(user_ns, user_global_ns) |
|
244 | 246 | # This has to be done after init_create_namespaces because it uses |
|
245 | 247 | # something in self.user_ns, but before init_sys_modules, which |
|
246 | 248 | # is the first thing to modify sys. |
|
247 | 249 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
248 | 250 | # is created, we are saving the overridden ones here. Not sure if this |
|
249 | 251 | # is what we want to do. |
|
250 | 252 | self.save_sys_module_state() |
|
251 | 253 | self.init_sys_modules() |
|
252 | 254 | |
|
253 | 255 | self.init_history() |
|
254 | 256 | self.init_encoding() |
|
255 | 257 | self.init_prefilter() |
|
256 | 258 | |
|
257 | 259 | Magic.__init__(self, self) |
|
258 | 260 | |
|
259 | 261 | self.init_syntax_highlighting() |
|
260 | 262 | self.init_hooks() |
|
261 | 263 | self.init_pushd_popd_magic() |
|
262 | 264 | # self.init_traceback_handlers use to be here, but we moved it below |
|
263 | 265 | # because it and init_io have to come after init_readline. |
|
264 | 266 | self.init_user_ns() |
|
265 | 267 | self.init_logger() |
|
266 | 268 | self.init_alias() |
|
267 | 269 | self.init_builtins() |
|
268 | 270 | |
|
269 | 271 | # pre_config_initialization |
|
270 | 272 | |
|
271 | 273 | # The next section should contain everything that was in ipmaker. |
|
272 | 274 | self.init_logstart() |
|
273 | 275 | |
|
274 | 276 | # The following was in post_config_initialization |
|
275 | 277 | self.init_inspector() |
|
276 | 278 | # init_readline() must come before init_io(), because init_io uses |
|
277 | 279 | # readline related things. |
|
278 | 280 | self.init_readline() |
|
279 | 281 | # init_completer must come after init_readline, because it needs to |
|
280 | 282 | # know whether readline is present or not system-wide to configure the |
|
281 | 283 | # completers, since the completion machinery can now operate |
|
282 | 284 | # independently of readline (e.g. over the network) |
|
283 | 285 | self.init_completer() |
|
284 | 286 | # TODO: init_io() needs to happen before init_traceback handlers |
|
285 | 287 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
286 | 288 | # This logic in in debugger.Pdb and should eventually be changed. |
|
287 | 289 | self.init_io() |
|
288 | 290 | self.init_traceback_handlers(custom_exceptions) |
|
289 | 291 | self.init_prompts() |
|
292 | self.init_display_formatter() | |
|
290 | 293 | self.init_display_pub() |
|
291 | 294 | self.init_displayhook() |
|
292 | 295 | self.init_reload_doctest() |
|
293 | 296 | self.init_magics() |
|
294 | 297 | self.init_pdb() |
|
295 | 298 | self.init_extension_manager() |
|
296 | 299 | self.init_plugin_manager() |
|
297 | 300 | self.init_payload() |
|
298 | 301 | self.hooks.late_startup_hook() |
|
299 | 302 | atexit.register(self.atexit_operations) |
|
300 | 303 | |
|
301 | 304 | # While we're trying to have each part of the code directly access what it |
|
302 | 305 | # needs without keeping redundant references to objects, we have too much |
|
303 | 306 | # legacy code that expects ip.db to exist, so let's make it a property that |
|
304 | 307 | # retrieves the underlying object from our new history manager. |
|
305 | 308 | @property |
|
306 | 309 | def db(self): |
|
307 | 310 | return self.history_manager.shadow_db |
|
308 | 311 | |
|
309 | 312 | @classmethod |
|
310 | 313 | def instance(cls, *args, **kwargs): |
|
311 | 314 | """Returns a global InteractiveShell instance.""" |
|
312 | 315 | if cls._instance is None: |
|
313 | 316 | inst = cls(*args, **kwargs) |
|
314 | 317 | # Now make sure that the instance will also be returned by |
|
315 | 318 | # the subclasses instance attribute. |
|
316 | 319 | for subclass in cls.mro(): |
|
317 | 320 | if issubclass(cls, subclass) and \ |
|
318 | 321 | issubclass(subclass, InteractiveShell): |
|
319 | 322 | subclass._instance = inst |
|
320 | 323 | else: |
|
321 | 324 | break |
|
322 | 325 | if isinstance(cls._instance, cls): |
|
323 | 326 | return cls._instance |
|
324 | 327 | else: |
|
325 | 328 | raise MultipleInstanceError( |
|
326 | 329 | 'Multiple incompatible subclass instances of ' |
|
327 | 330 | 'InteractiveShell are being created.' |
|
328 | 331 | ) |
|
329 | 332 | |
|
330 | 333 | @classmethod |
|
331 | 334 | def initialized(cls): |
|
332 | 335 | return hasattr(cls, "_instance") |
|
333 | 336 | |
|
334 | 337 | def get_ipython(self): |
|
335 | 338 | """Return the currently running IPython instance.""" |
|
336 | 339 | return self |
|
337 | 340 | |
|
338 | 341 | #------------------------------------------------------------------------- |
|
339 | 342 | # Trait changed handlers |
|
340 | 343 | #------------------------------------------------------------------------- |
|
341 | 344 | |
|
342 | 345 | def _ipython_dir_changed(self, name, new): |
|
343 | 346 | if not os.path.isdir(new): |
|
344 | 347 | os.makedirs(new, mode = 0777) |
|
345 | 348 | |
|
346 | 349 | def set_autoindent(self,value=None): |
|
347 | 350 | """Set the autoindent flag, checking for readline support. |
|
348 | 351 | |
|
349 | 352 | If called with no arguments, it acts as a toggle.""" |
|
350 | 353 | |
|
351 | 354 | if not self.has_readline: |
|
352 | 355 | if os.name == 'posix': |
|
353 | 356 | warn("The auto-indent feature requires the readline library") |
|
354 | 357 | self.autoindent = 0 |
|
355 | 358 | return |
|
356 | 359 | if value is None: |
|
357 | 360 | self.autoindent = not self.autoindent |
|
358 | 361 | else: |
|
359 | 362 | self.autoindent = value |
|
360 | 363 | |
|
361 | 364 | #------------------------------------------------------------------------- |
|
362 | 365 | # init_* methods called by __init__ |
|
363 | 366 | #------------------------------------------------------------------------- |
|
364 | 367 | |
|
365 | 368 | def init_ipython_dir(self, ipython_dir): |
|
366 | 369 | if ipython_dir is not None: |
|
367 | 370 | self.ipython_dir = ipython_dir |
|
368 | 371 | self.config.Global.ipython_dir = self.ipython_dir |
|
369 | 372 | return |
|
370 | 373 | |
|
371 | 374 | if hasattr(self.config.Global, 'ipython_dir'): |
|
372 | 375 | self.ipython_dir = self.config.Global.ipython_dir |
|
373 | 376 | else: |
|
374 | 377 | self.ipython_dir = get_ipython_dir() |
|
375 | 378 | |
|
376 | 379 | # All children can just read this |
|
377 | 380 | self.config.Global.ipython_dir = self.ipython_dir |
|
378 | 381 | |
|
379 | 382 | def init_instance_attrs(self): |
|
380 | 383 | self.more = False |
|
381 | 384 | |
|
382 | 385 | # command compiler |
|
383 | 386 | self.compile = CachingCompiler() |
|
384 | 387 | |
|
385 | 388 | # User input buffers |
|
386 | 389 | # NOTE: these variables are slated for full removal, once we are 100% |
|
387 | 390 | # sure that the new execution logic is solid. We will delte runlines, |
|
388 | 391 | # push_line and these buffers, as all input will be managed by the |
|
389 | 392 | # frontends via an inputsplitter instance. |
|
390 | 393 | self.buffer = [] |
|
391 | 394 | self.buffer_raw = [] |
|
392 | 395 | |
|
393 | 396 | # Make an empty namespace, which extension writers can rely on both |
|
394 | 397 | # existing and NEVER being used by ipython itself. This gives them a |
|
395 | 398 | # convenient location for storing additional information and state |
|
396 | 399 | # their extensions may require, without fear of collisions with other |
|
397 | 400 | # ipython names that may develop later. |
|
398 | 401 | self.meta = Struct() |
|
399 | 402 | |
|
400 | 403 | # Object variable to store code object waiting execution. This is |
|
401 | 404 | # used mainly by the multithreaded shells, but it can come in handy in |
|
402 | 405 | # other situations. No need to use a Queue here, since it's a single |
|
403 | 406 | # item which gets cleared once run. |
|
404 | 407 | self.code_to_run = None |
|
405 | 408 | |
|
406 | 409 | # Temporary files used for various purposes. Deleted at exit. |
|
407 | 410 | self.tempfiles = [] |
|
408 | 411 | |
|
409 | 412 | # Keep track of readline usage (later set by init_readline) |
|
410 | 413 | self.has_readline = False |
|
411 | 414 | |
|
412 | 415 | # keep track of where we started running (mainly for crash post-mortem) |
|
413 | 416 | # This is not being used anywhere currently. |
|
414 | 417 | self.starting_dir = os.getcwd() |
|
415 | 418 | |
|
416 | 419 | # Indentation management |
|
417 | 420 | self.indent_current_nsp = 0 |
|
418 | 421 | |
|
419 | 422 | def init_environment(self): |
|
420 | 423 | """Any changes we need to make to the user's environment.""" |
|
421 | 424 | pass |
|
422 | 425 | |
|
423 | 426 | def init_encoding(self): |
|
424 | 427 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
425 | 428 | # under Win32 have it set to None, and we need to have a known valid |
|
426 | 429 | # encoding to use in the raw_input() method |
|
427 | 430 | try: |
|
428 | 431 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
429 | 432 | except AttributeError: |
|
430 | 433 | self.stdin_encoding = 'ascii' |
|
431 | 434 | |
|
432 | 435 | def init_syntax_highlighting(self): |
|
433 | 436 | # Python source parser/formatter for syntax highlighting |
|
434 | 437 | pyformat = PyColorize.Parser().format |
|
435 | 438 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
436 | 439 | |
|
437 | 440 | def init_pushd_popd_magic(self): |
|
438 | 441 | # for pushd/popd management |
|
439 | 442 | try: |
|
440 | 443 | self.home_dir = get_home_dir() |
|
441 | 444 | except HomeDirError, msg: |
|
442 | 445 | fatal(msg) |
|
443 | 446 | |
|
444 | 447 | self.dir_stack = [] |
|
445 | 448 | |
|
446 | 449 | def init_logger(self): |
|
447 | 450 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
448 | 451 | logmode='rotate') |
|
449 | 452 | |
|
450 | 453 | def init_logstart(self): |
|
451 | 454 | """Initialize logging in case it was requested at the command line. |
|
452 | 455 | """ |
|
453 | 456 | if self.logappend: |
|
454 | 457 | self.magic_logstart(self.logappend + ' append') |
|
455 | 458 | elif self.logfile: |
|
456 | 459 | self.magic_logstart(self.logfile) |
|
457 | 460 | elif self.logstart: |
|
458 | 461 | self.magic_logstart() |
|
459 | 462 | |
|
460 | 463 | def init_builtins(self): |
|
461 | 464 | self.builtin_trap = BuiltinTrap(shell=self) |
|
462 | 465 | |
|
463 | 466 | def init_inspector(self): |
|
464 | 467 | # Object inspector |
|
465 | 468 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
466 | 469 | PyColorize.ANSICodeColors, |
|
467 | 470 | 'NoColor', |
|
468 | 471 | self.object_info_string_level) |
|
469 | 472 | |
|
470 | 473 | def init_io(self): |
|
471 | 474 | # This will just use sys.stdout and sys.stderr. If you want to |
|
472 | 475 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
473 | 476 | # *before* instantiating this class, because Term holds onto |
|
474 | 477 | # references to the underlying streams. |
|
475 | 478 | if sys.platform == 'win32' and self.has_readline: |
|
476 | 479 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
477 | 480 | cerr=self.readline._outputfile) |
|
478 | 481 | else: |
|
479 | 482 | Term = io.IOTerm() |
|
480 | 483 | io.Term = Term |
|
481 | 484 | |
|
482 | 485 | def init_prompts(self): |
|
483 | 486 | # TODO: This is a pass for now because the prompts are managed inside |
|
484 | 487 | # the DisplayHook. Once there is a separate prompt manager, this |
|
485 | 488 | # will initialize that object and all prompt related information. |
|
486 | 489 | pass |
|
487 | 490 | |
|
491 | def init_display_formatter(self): | |
|
492 | self.display_formatter = DisplayFormatter(config=self.config) | |
|
493 | ||
|
488 | 494 | def init_display_pub(self): |
|
489 | 495 | self.display_pub = self.display_pub_class(config=self.config) |
|
490 | 496 | |
|
491 | 497 | def init_displayhook(self): |
|
492 | 498 | # Initialize displayhook, set in/out prompts and printing system |
|
493 | 499 | self.displayhook = self.displayhook_class( |
|
494 | 500 | config=self.config, |
|
495 | 501 | shell=self, |
|
496 | 502 | cache_size=self.cache_size, |
|
497 | 503 | input_sep = self.separate_in, |
|
498 | 504 | output_sep = self.separate_out, |
|
499 | 505 | output_sep2 = self.separate_out2, |
|
500 | 506 | ps1 = self.prompt_in1, |
|
501 | 507 | ps2 = self.prompt_in2, |
|
502 | 508 | ps_out = self.prompt_out, |
|
503 | 509 | pad_left = self.prompts_pad_left |
|
504 | 510 | ) |
|
505 | 511 | # This is a context manager that installs/revmoes the displayhook at |
|
506 | 512 | # the appropriate time. |
|
507 | 513 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
508 | 514 | |
|
509 | 515 | def init_reload_doctest(self): |
|
510 | 516 | # Do a proper resetting of doctest, including the necessary displayhook |
|
511 | 517 | # monkeypatching |
|
512 | 518 | try: |
|
513 | 519 | doctest_reload() |
|
514 | 520 | except ImportError: |
|
515 | 521 | warn("doctest module does not exist.") |
|
516 | 522 | |
|
517 | 523 | #------------------------------------------------------------------------- |
|
518 | 524 | # Things related to injections into the sys module |
|
519 | 525 | #------------------------------------------------------------------------- |
|
520 | 526 | |
|
521 | 527 | def save_sys_module_state(self): |
|
522 | 528 | """Save the state of hooks in the sys module. |
|
523 | 529 | |
|
524 | 530 | This has to be called after self.user_ns is created. |
|
525 | 531 | """ |
|
526 | 532 | self._orig_sys_module_state = {} |
|
527 | 533 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
528 | 534 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
529 | 535 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
530 | 536 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
531 | 537 | try: |
|
532 | 538 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
533 | 539 | except KeyError: |
|
534 | 540 | pass |
|
535 | 541 | |
|
536 | 542 | def restore_sys_module_state(self): |
|
537 | 543 | """Restore the state of the sys module.""" |
|
538 | 544 | try: |
|
539 | 545 | for k, v in self._orig_sys_module_state.iteritems(): |
|
540 | 546 | setattr(sys, k, v) |
|
541 | 547 | except AttributeError: |
|
542 | 548 | pass |
|
543 | 549 | # Reset what what done in self.init_sys_modules |
|
544 | 550 | try: |
|
545 | 551 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
546 | 552 | except (AttributeError, KeyError): |
|
547 | 553 | pass |
|
548 | 554 | |
|
549 | 555 | #------------------------------------------------------------------------- |
|
550 | 556 | # Things related to hooks |
|
551 | 557 | #------------------------------------------------------------------------- |
|
552 | 558 | |
|
553 | 559 | def init_hooks(self): |
|
554 | 560 | # hooks holds pointers used for user-side customizations |
|
555 | 561 | self.hooks = Struct() |
|
556 | 562 | |
|
557 | 563 | self.strdispatchers = {} |
|
558 | 564 | |
|
559 | 565 | # Set all default hooks, defined in the IPython.hooks module. |
|
560 | 566 | hooks = IPython.core.hooks |
|
561 | 567 | for hook_name in hooks.__all__: |
|
562 | 568 | # default hooks have priority 100, i.e. low; user hooks should have |
|
563 | 569 | # 0-100 priority |
|
564 | 570 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
565 | 571 | |
|
566 | 572 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
567 | 573 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
568 | 574 | |
|
569 | 575 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
570 | 576 | adding your function to one of these hooks, you can modify IPython's |
|
571 | 577 | behavior to call at runtime your own routines.""" |
|
572 | 578 | |
|
573 | 579 | # At some point in the future, this should validate the hook before it |
|
574 | 580 | # accepts it. Probably at least check that the hook takes the number |
|
575 | 581 | # of args it's supposed to. |
|
576 | 582 | |
|
577 | 583 | f = types.MethodType(hook,self) |
|
578 | 584 | |
|
579 | 585 | # check if the hook is for strdispatcher first |
|
580 | 586 | if str_key is not None: |
|
581 | 587 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
582 | 588 | sdp.add_s(str_key, f, priority ) |
|
583 | 589 | self.strdispatchers[name] = sdp |
|
584 | 590 | return |
|
585 | 591 | if re_key is not None: |
|
586 | 592 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
587 | 593 | sdp.add_re(re.compile(re_key), f, priority ) |
|
588 | 594 | self.strdispatchers[name] = sdp |
|
589 | 595 | return |
|
590 | 596 | |
|
591 | 597 | dp = getattr(self.hooks, name, None) |
|
592 | 598 | if name not in IPython.core.hooks.__all__: |
|
593 | 599 | print "Warning! Hook '%s' is not one of %s" % \ |
|
594 | 600 | (name, IPython.core.hooks.__all__ ) |
|
595 | 601 | if not dp: |
|
596 | 602 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
597 | 603 | |
|
598 | 604 | try: |
|
599 | 605 | dp.add(f,priority) |
|
600 | 606 | except AttributeError: |
|
601 | 607 | # it was not commandchain, plain old func - replace |
|
602 | 608 | dp = f |
|
603 | 609 | |
|
604 | 610 | setattr(self.hooks,name, dp) |
|
605 | 611 | |
|
606 | 612 | def register_post_execute(self, func): |
|
607 | 613 | """Register a function for calling after code execution. |
|
608 | 614 | """ |
|
609 | 615 | if not callable(func): |
|
610 | 616 | raise ValueError('argument %s must be callable' % func) |
|
611 | 617 | self._post_execute.add(func) |
|
612 | 618 | |
|
613 | 619 | #------------------------------------------------------------------------- |
|
614 | 620 | # Things related to the "main" module |
|
615 | 621 | #------------------------------------------------------------------------- |
|
616 | 622 | |
|
617 | 623 | def new_main_mod(self,ns=None): |
|
618 | 624 | """Return a new 'main' module object for user code execution. |
|
619 | 625 | """ |
|
620 | 626 | main_mod = self._user_main_module |
|
621 | 627 | init_fakemod_dict(main_mod,ns) |
|
622 | 628 | return main_mod |
|
623 | 629 | |
|
624 | 630 | def cache_main_mod(self,ns,fname): |
|
625 | 631 | """Cache a main module's namespace. |
|
626 | 632 | |
|
627 | 633 | When scripts are executed via %run, we must keep a reference to the |
|
628 | 634 | namespace of their __main__ module (a FakeModule instance) around so |
|
629 | 635 | that Python doesn't clear it, rendering objects defined therein |
|
630 | 636 | useless. |
|
631 | 637 | |
|
632 | 638 | This method keeps said reference in a private dict, keyed by the |
|
633 | 639 | absolute path of the module object (which corresponds to the script |
|
634 | 640 | path). This way, for multiple executions of the same script we only |
|
635 | 641 | keep one copy of the namespace (the last one), thus preventing memory |
|
636 | 642 | leaks from old references while allowing the objects from the last |
|
637 | 643 | execution to be accessible. |
|
638 | 644 | |
|
639 | 645 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
640 | 646 | because of how Python tears down modules (it hard-sets all their |
|
641 | 647 | references to None without regard for reference counts). This method |
|
642 | 648 | must therefore make a *copy* of the given namespace, to allow the |
|
643 | 649 | original module's __dict__ to be cleared and reused. |
|
644 | 650 | |
|
645 | 651 | |
|
646 | 652 | Parameters |
|
647 | 653 | ---------- |
|
648 | 654 | ns : a namespace (a dict, typically) |
|
649 | 655 | |
|
650 | 656 | fname : str |
|
651 | 657 | Filename associated with the namespace. |
|
652 | 658 | |
|
653 | 659 | Examples |
|
654 | 660 | -------- |
|
655 | 661 | |
|
656 | 662 | In [10]: import IPython |
|
657 | 663 | |
|
658 | 664 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
659 | 665 | |
|
660 | 666 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
661 | 667 | Out[12]: True |
|
662 | 668 | """ |
|
663 | 669 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
664 | 670 | |
|
665 | 671 | def clear_main_mod_cache(self): |
|
666 | 672 | """Clear the cache of main modules. |
|
667 | 673 | |
|
668 | 674 | Mainly for use by utilities like %reset. |
|
669 | 675 | |
|
670 | 676 | Examples |
|
671 | 677 | -------- |
|
672 | 678 | |
|
673 | 679 | In [15]: import IPython |
|
674 | 680 | |
|
675 | 681 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
676 | 682 | |
|
677 | 683 | In [17]: len(_ip._main_ns_cache) > 0 |
|
678 | 684 | Out[17]: True |
|
679 | 685 | |
|
680 | 686 | In [18]: _ip.clear_main_mod_cache() |
|
681 | 687 | |
|
682 | 688 | In [19]: len(_ip._main_ns_cache) == 0 |
|
683 | 689 | Out[19]: True |
|
684 | 690 | """ |
|
685 | 691 | self._main_ns_cache.clear() |
|
686 | 692 | |
|
687 | 693 | #------------------------------------------------------------------------- |
|
688 | 694 | # Things related to debugging |
|
689 | 695 | #------------------------------------------------------------------------- |
|
690 | 696 | |
|
691 | 697 | def init_pdb(self): |
|
692 | 698 | # Set calling of pdb on exceptions |
|
693 | 699 | # self.call_pdb is a property |
|
694 | 700 | self.call_pdb = self.pdb |
|
695 | 701 | |
|
696 | 702 | def _get_call_pdb(self): |
|
697 | 703 | return self._call_pdb |
|
698 | 704 | |
|
699 | 705 | def _set_call_pdb(self,val): |
|
700 | 706 | |
|
701 | 707 | if val not in (0,1,False,True): |
|
702 | 708 | raise ValueError,'new call_pdb value must be boolean' |
|
703 | 709 | |
|
704 | 710 | # store value in instance |
|
705 | 711 | self._call_pdb = val |
|
706 | 712 | |
|
707 | 713 | # notify the actual exception handlers |
|
708 | 714 | self.InteractiveTB.call_pdb = val |
|
709 | 715 | |
|
710 | 716 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
711 | 717 | 'Control auto-activation of pdb at exceptions') |
|
712 | 718 | |
|
713 | 719 | def debugger(self,force=False): |
|
714 | 720 | """Call the pydb/pdb debugger. |
|
715 | 721 | |
|
716 | 722 | Keywords: |
|
717 | 723 | |
|
718 | 724 | - force(False): by default, this routine checks the instance call_pdb |
|
719 | 725 | flag and does not actually invoke the debugger if the flag is false. |
|
720 | 726 | The 'force' option forces the debugger to activate even if the flag |
|
721 | 727 | is false. |
|
722 | 728 | """ |
|
723 | 729 | |
|
724 | 730 | if not (force or self.call_pdb): |
|
725 | 731 | return |
|
726 | 732 | |
|
727 | 733 | if not hasattr(sys,'last_traceback'): |
|
728 | 734 | error('No traceback has been produced, nothing to debug.') |
|
729 | 735 | return |
|
730 | 736 | |
|
731 | 737 | # use pydb if available |
|
732 | 738 | if debugger.has_pydb: |
|
733 | 739 | from pydb import pm |
|
734 | 740 | else: |
|
735 | 741 | # fallback to our internal debugger |
|
736 | 742 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
737 | 743 | self.history_saving_wrapper(pm)() |
|
738 | 744 | |
|
739 | 745 | #------------------------------------------------------------------------- |
|
740 | 746 | # Things related to IPython's various namespaces |
|
741 | 747 | #------------------------------------------------------------------------- |
|
742 | 748 | |
|
743 | 749 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
744 | 750 | # Create the namespace where the user will operate. user_ns is |
|
745 | 751 | # normally the only one used, and it is passed to the exec calls as |
|
746 | 752 | # the locals argument. But we do carry a user_global_ns namespace |
|
747 | 753 | # given as the exec 'globals' argument, This is useful in embedding |
|
748 | 754 | # situations where the ipython shell opens in a context where the |
|
749 | 755 | # distinction between locals and globals is meaningful. For |
|
750 | 756 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
751 | 757 | |
|
752 | 758 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
753 | 759 | # level as a dict instead of a module. This is a manual fix, but I |
|
754 | 760 | # should really track down where the problem is coming from. Alex |
|
755 | 761 | # Schmolck reported this problem first. |
|
756 | 762 | |
|
757 | 763 | # A useful post by Alex Martelli on this topic: |
|
758 | 764 | # Re: inconsistent value from __builtins__ |
|
759 | 765 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
760 | 766 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
761 | 767 | # Gruppen: comp.lang.python |
|
762 | 768 | |
|
763 | 769 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
764 | 770 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
765 | 771 | # > <type 'dict'> |
|
766 | 772 | # > >>> print type(__builtins__) |
|
767 | 773 | # > <type 'module'> |
|
768 | 774 | # > Is this difference in return value intentional? |
|
769 | 775 | |
|
770 | 776 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
771 | 777 | # or a module, and it's been that way for a long time. Whether it's |
|
772 | 778 | # intentional (or sensible), I don't know. In any case, the idea is |
|
773 | 779 | # that if you need to access the built-in namespace directly, you |
|
774 | 780 | # should start with "import __builtin__" (note, no 's') which will |
|
775 | 781 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
776 | 782 | |
|
777 | 783 | # These routines return properly built dicts as needed by the rest of |
|
778 | 784 | # the code, and can also be used by extension writers to generate |
|
779 | 785 | # properly initialized namespaces. |
|
780 | 786 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
781 | 787 | user_global_ns) |
|
782 | 788 | |
|
783 | 789 | # Assign namespaces |
|
784 | 790 | # This is the namespace where all normal user variables live |
|
785 | 791 | self.user_ns = user_ns |
|
786 | 792 | self.user_global_ns = user_global_ns |
|
787 | 793 | |
|
788 | 794 | # An auxiliary namespace that checks what parts of the user_ns were |
|
789 | 795 | # loaded at startup, so we can list later only variables defined in |
|
790 | 796 | # actual interactive use. Since it is always a subset of user_ns, it |
|
791 | 797 | # doesn't need to be separately tracked in the ns_table. |
|
792 | 798 | self.user_ns_hidden = {} |
|
793 | 799 | |
|
794 | 800 | # A namespace to keep track of internal data structures to prevent |
|
795 | 801 | # them from cluttering user-visible stuff. Will be updated later |
|
796 | 802 | self.internal_ns = {} |
|
797 | 803 | |
|
798 | 804 | # Now that FakeModule produces a real module, we've run into a nasty |
|
799 | 805 | # problem: after script execution (via %run), the module where the user |
|
800 | 806 | # code ran is deleted. Now that this object is a true module (needed |
|
801 | 807 | # so docetst and other tools work correctly), the Python module |
|
802 | 808 | # teardown mechanism runs over it, and sets to None every variable |
|
803 | 809 | # present in that module. Top-level references to objects from the |
|
804 | 810 | # script survive, because the user_ns is updated with them. However, |
|
805 | 811 | # calling functions defined in the script that use other things from |
|
806 | 812 | # the script will fail, because the function's closure had references |
|
807 | 813 | # to the original objects, which are now all None. So we must protect |
|
808 | 814 | # these modules from deletion by keeping a cache. |
|
809 | 815 | # |
|
810 | 816 | # To avoid keeping stale modules around (we only need the one from the |
|
811 | 817 | # last run), we use a dict keyed with the full path to the script, so |
|
812 | 818 | # only the last version of the module is held in the cache. Note, |
|
813 | 819 | # however, that we must cache the module *namespace contents* (their |
|
814 | 820 | # __dict__). Because if we try to cache the actual modules, old ones |
|
815 | 821 | # (uncached) could be destroyed while still holding references (such as |
|
816 | 822 | # those held by GUI objects that tend to be long-lived)> |
|
817 | 823 | # |
|
818 | 824 | # The %reset command will flush this cache. See the cache_main_mod() |
|
819 | 825 | # and clear_main_mod_cache() methods for details on use. |
|
820 | 826 | |
|
821 | 827 | # This is the cache used for 'main' namespaces |
|
822 | 828 | self._main_ns_cache = {} |
|
823 | 829 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
824 | 830 | # copying and clearing for reuse on each %run |
|
825 | 831 | self._user_main_module = FakeModule() |
|
826 | 832 | |
|
827 | 833 | # A table holding all the namespaces IPython deals with, so that |
|
828 | 834 | # introspection facilities can search easily. |
|
829 | 835 | self.ns_table = {'user':user_ns, |
|
830 | 836 | 'user_global':user_global_ns, |
|
831 | 837 | 'internal':self.internal_ns, |
|
832 | 838 | 'builtin':__builtin__.__dict__ |
|
833 | 839 | } |
|
834 | 840 | |
|
835 | 841 | # Similarly, track all namespaces where references can be held and that |
|
836 | 842 | # we can safely clear (so it can NOT include builtin). This one can be |
|
837 | 843 | # a simple list. Note that the main execution namespaces, user_ns and |
|
838 | 844 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
839 | 845 | # causes errors in object __del__ methods. Instead, the reset() method |
|
840 | 846 | # clears them manually and carefully. |
|
841 | 847 | self.ns_refs_table = [ self.user_ns_hidden, |
|
842 | 848 | self.internal_ns, self._main_ns_cache ] |
|
843 | 849 | |
|
844 | 850 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
845 | 851 | """Return a valid local and global user interactive namespaces. |
|
846 | 852 | |
|
847 | 853 | This builds a dict with the minimal information needed to operate as a |
|
848 | 854 | valid IPython user namespace, which you can pass to the various |
|
849 | 855 | embedding classes in ipython. The default implementation returns the |
|
850 | 856 | same dict for both the locals and the globals to allow functions to |
|
851 | 857 | refer to variables in the namespace. Customized implementations can |
|
852 | 858 | return different dicts. The locals dictionary can actually be anything |
|
853 | 859 | following the basic mapping protocol of a dict, but the globals dict |
|
854 | 860 | must be a true dict, not even a subclass. It is recommended that any |
|
855 | 861 | custom object for the locals namespace synchronize with the globals |
|
856 | 862 | dict somehow. |
|
857 | 863 | |
|
858 | 864 | Raises TypeError if the provided globals namespace is not a true dict. |
|
859 | 865 | |
|
860 | 866 | Parameters |
|
861 | 867 | ---------- |
|
862 | 868 | user_ns : dict-like, optional |
|
863 | 869 | The current user namespace. The items in this namespace should |
|
864 | 870 | be included in the output. If None, an appropriate blank |
|
865 | 871 | namespace should be created. |
|
866 | 872 | user_global_ns : dict, optional |
|
867 | 873 | The current user global namespace. The items in this namespace |
|
868 | 874 | should be included in the output. If None, an appropriate |
|
869 | 875 | blank namespace should be created. |
|
870 | 876 | |
|
871 | 877 | Returns |
|
872 | 878 | ------- |
|
873 | 879 | A pair of dictionary-like object to be used as the local namespace |
|
874 | 880 | of the interpreter and a dict to be used as the global namespace. |
|
875 | 881 | """ |
|
876 | 882 | |
|
877 | 883 | |
|
878 | 884 | # We must ensure that __builtin__ (without the final 's') is always |
|
879 | 885 | # available and pointing to the __builtin__ *module*. For more details: |
|
880 | 886 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
881 | 887 | |
|
882 | 888 | if user_ns is None: |
|
883 | 889 | # Set __name__ to __main__ to better match the behavior of the |
|
884 | 890 | # normal interpreter. |
|
885 | 891 | user_ns = {'__name__' :'__main__', |
|
886 | 892 | '__builtin__' : __builtin__, |
|
887 | 893 | '__builtins__' : __builtin__, |
|
888 | 894 | } |
|
889 | 895 | else: |
|
890 | 896 | user_ns.setdefault('__name__','__main__') |
|
891 | 897 | user_ns.setdefault('__builtin__',__builtin__) |
|
892 | 898 | user_ns.setdefault('__builtins__',__builtin__) |
|
893 | 899 | |
|
894 | 900 | if user_global_ns is None: |
|
895 | 901 | user_global_ns = user_ns |
|
896 | 902 | if type(user_global_ns) is not dict: |
|
897 | 903 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
898 | 904 | % type(user_global_ns)) |
|
899 | 905 | |
|
900 | 906 | return user_ns, user_global_ns |
|
901 | 907 | |
|
902 | 908 | def init_sys_modules(self): |
|
903 | 909 | # We need to insert into sys.modules something that looks like a |
|
904 | 910 | # module but which accesses the IPython namespace, for shelve and |
|
905 | 911 | # pickle to work interactively. Normally they rely on getting |
|
906 | 912 | # everything out of __main__, but for embedding purposes each IPython |
|
907 | 913 | # instance has its own private namespace, so we can't go shoving |
|
908 | 914 | # everything into __main__. |
|
909 | 915 | |
|
910 | 916 | # note, however, that we should only do this for non-embedded |
|
911 | 917 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
912 | 918 | # namespace. Embedded instances, on the other hand, should not do |
|
913 | 919 | # this because they need to manage the user local/global namespaces |
|
914 | 920 | # only, but they live within a 'normal' __main__ (meaning, they |
|
915 | 921 | # shouldn't overtake the execution environment of the script they're |
|
916 | 922 | # embedded in). |
|
917 | 923 | |
|
918 | 924 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
919 | 925 | |
|
920 | 926 | try: |
|
921 | 927 | main_name = self.user_ns['__name__'] |
|
922 | 928 | except KeyError: |
|
923 | 929 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
924 | 930 | else: |
|
925 | 931 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
926 | 932 | |
|
927 | 933 | def init_user_ns(self): |
|
928 | 934 | """Initialize all user-visible namespaces to their minimum defaults. |
|
929 | 935 | |
|
930 | 936 | Certain history lists are also initialized here, as they effectively |
|
931 | 937 | act as user namespaces. |
|
932 | 938 | |
|
933 | 939 | Notes |
|
934 | 940 | ----- |
|
935 | 941 | All data structures here are only filled in, they are NOT reset by this |
|
936 | 942 | method. If they were not empty before, data will simply be added to |
|
937 | 943 | therm. |
|
938 | 944 | """ |
|
939 | 945 | # This function works in two parts: first we put a few things in |
|
940 | 946 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
941 | 947 | # initial variables aren't shown by %who. After the sync, we add the |
|
942 | 948 | # rest of what we *do* want the user to see with %who even on a new |
|
943 | 949 | # session (probably nothing, so theye really only see their own stuff) |
|
944 | 950 | |
|
945 | 951 | # The user dict must *always* have a __builtin__ reference to the |
|
946 | 952 | # Python standard __builtin__ namespace, which must be imported. |
|
947 | 953 | # This is so that certain operations in prompt evaluation can be |
|
948 | 954 | # reliably executed with builtins. Note that we can NOT use |
|
949 | 955 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
950 | 956 | # module, and can even mutate at runtime, depending on the context |
|
951 | 957 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
952 | 958 | # always a module object, though it must be explicitly imported. |
|
953 | 959 | |
|
954 | 960 | # For more details: |
|
955 | 961 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
956 | 962 | ns = dict(__builtin__ = __builtin__) |
|
957 | 963 | |
|
958 | 964 | # Put 'help' in the user namespace |
|
959 | 965 | try: |
|
960 | 966 | from site import _Helper |
|
961 | 967 | ns['help'] = _Helper() |
|
962 | 968 | except ImportError: |
|
963 | 969 | warn('help() not available - check site.py') |
|
964 | 970 | |
|
965 | 971 | # make global variables for user access to the histories |
|
966 | 972 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
967 | 973 | ns['_oh'] = self.history_manager.output_hist |
|
968 | 974 | ns['_dh'] = self.history_manager.dir_hist |
|
969 | 975 | |
|
970 | 976 | ns['_sh'] = shadowns |
|
971 | 977 | |
|
972 | 978 | # user aliases to input and output histories. These shouldn't show up |
|
973 | 979 | # in %who, as they can have very large reprs. |
|
974 | 980 | ns['In'] = self.history_manager.input_hist_parsed |
|
975 | 981 | ns['Out'] = self.history_manager.output_hist |
|
976 | 982 | |
|
977 | 983 | # Store myself as the public api!!! |
|
978 | 984 | ns['get_ipython'] = self.get_ipython |
|
979 | 985 | |
|
980 | 986 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
981 | 987 | # by %who |
|
982 | 988 | self.user_ns_hidden.update(ns) |
|
983 | 989 | |
|
984 | 990 | # Anything put into ns now would show up in %who. Think twice before |
|
985 | 991 | # putting anything here, as we really want %who to show the user their |
|
986 | 992 | # stuff, not our variables. |
|
987 | 993 | |
|
988 | 994 | # Finally, update the real user's namespace |
|
989 | 995 | self.user_ns.update(ns) |
|
990 | 996 | |
|
991 | 997 | def reset(self): |
|
992 | 998 | """Clear all internal namespaces. |
|
993 | 999 | |
|
994 | 1000 | Note that this is much more aggressive than %reset, since it clears |
|
995 | 1001 | fully all namespaces, as well as all input/output lists. |
|
996 | 1002 | """ |
|
997 | 1003 | # Clear histories |
|
998 | 1004 | self.history_manager.reset() |
|
999 | 1005 | |
|
1000 | 1006 | # Reset counter used to index all histories |
|
1001 | 1007 | self.execution_count = 0 |
|
1002 | 1008 | |
|
1003 | 1009 | # Restore the user namespaces to minimal usability |
|
1004 | 1010 | for ns in self.ns_refs_table: |
|
1005 | 1011 | ns.clear() |
|
1006 | 1012 | |
|
1007 | 1013 | # The main execution namespaces must be cleared very carefully, |
|
1008 | 1014 | # skipping the deletion of the builtin-related keys, because doing so |
|
1009 | 1015 | # would cause errors in many object's __del__ methods. |
|
1010 | 1016 | for ns in [self.user_ns, self.user_global_ns]: |
|
1011 | 1017 | drop_keys = set(ns.keys()) |
|
1012 | 1018 | drop_keys.discard('__builtin__') |
|
1013 | 1019 | drop_keys.discard('__builtins__') |
|
1014 | 1020 | for k in drop_keys: |
|
1015 | 1021 | del ns[k] |
|
1016 | 1022 | |
|
1017 | 1023 | # Restore the user namespaces to minimal usability |
|
1018 | 1024 | self.init_user_ns() |
|
1019 | 1025 | |
|
1020 | 1026 | # Restore the default and user aliases |
|
1021 | 1027 | self.alias_manager.clear_aliases() |
|
1022 | 1028 | self.alias_manager.init_aliases() |
|
1023 | 1029 | |
|
1024 | 1030 | def reset_selective(self, regex=None): |
|
1025 | 1031 | """Clear selective variables from internal namespaces based on a |
|
1026 | 1032 | specified regular expression. |
|
1027 | 1033 | |
|
1028 | 1034 | Parameters |
|
1029 | 1035 | ---------- |
|
1030 | 1036 | regex : string or compiled pattern, optional |
|
1031 | 1037 | A regular expression pattern that will be used in searching |
|
1032 | 1038 | variable names in the users namespaces. |
|
1033 | 1039 | """ |
|
1034 | 1040 | if regex is not None: |
|
1035 | 1041 | try: |
|
1036 | 1042 | m = re.compile(regex) |
|
1037 | 1043 | except TypeError: |
|
1038 | 1044 | raise TypeError('regex must be a string or compiled pattern') |
|
1039 | 1045 | # Search for keys in each namespace that match the given regex |
|
1040 | 1046 | # If a match is found, delete the key/value pair. |
|
1041 | 1047 | for ns in self.ns_refs_table: |
|
1042 | 1048 | for var in ns: |
|
1043 | 1049 | if m.search(var): |
|
1044 | 1050 | del ns[var] |
|
1045 | 1051 | |
|
1046 | 1052 | def push(self, variables, interactive=True): |
|
1047 | 1053 | """Inject a group of variables into the IPython user namespace. |
|
1048 | 1054 | |
|
1049 | 1055 | Parameters |
|
1050 | 1056 | ---------- |
|
1051 | 1057 | variables : dict, str or list/tuple of str |
|
1052 | 1058 | The variables to inject into the user's namespace. If a dict, a |
|
1053 | 1059 | simple update is done. If a str, the string is assumed to have |
|
1054 | 1060 | variable names separated by spaces. A list/tuple of str can also |
|
1055 | 1061 | be used to give the variable names. If just the variable names are |
|
1056 | 1062 | give (list/tuple/str) then the variable values looked up in the |
|
1057 | 1063 | callers frame. |
|
1058 | 1064 | interactive : bool |
|
1059 | 1065 | If True (default), the variables will be listed with the ``who`` |
|
1060 | 1066 | magic. |
|
1061 | 1067 | """ |
|
1062 | 1068 | vdict = None |
|
1063 | 1069 | |
|
1064 | 1070 | # We need a dict of name/value pairs to do namespace updates. |
|
1065 | 1071 | if isinstance(variables, dict): |
|
1066 | 1072 | vdict = variables |
|
1067 | 1073 | elif isinstance(variables, (basestring, list, tuple)): |
|
1068 | 1074 | if isinstance(variables, basestring): |
|
1069 | 1075 | vlist = variables.split() |
|
1070 | 1076 | else: |
|
1071 | 1077 | vlist = variables |
|
1072 | 1078 | vdict = {} |
|
1073 | 1079 | cf = sys._getframe(1) |
|
1074 | 1080 | for name in vlist: |
|
1075 | 1081 | try: |
|
1076 | 1082 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1077 | 1083 | except: |
|
1078 | 1084 | print ('Could not get variable %s from %s' % |
|
1079 | 1085 | (name,cf.f_code.co_name)) |
|
1080 | 1086 | else: |
|
1081 | 1087 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1082 | 1088 | |
|
1083 | 1089 | # Propagate variables to user namespace |
|
1084 | 1090 | self.user_ns.update(vdict) |
|
1085 | 1091 | |
|
1086 | 1092 | # And configure interactive visibility |
|
1087 | 1093 | config_ns = self.user_ns_hidden |
|
1088 | 1094 | if interactive: |
|
1089 | 1095 | for name, val in vdict.iteritems(): |
|
1090 | 1096 | config_ns.pop(name, None) |
|
1091 | 1097 | else: |
|
1092 | 1098 | for name,val in vdict.iteritems(): |
|
1093 | 1099 | config_ns[name] = val |
|
1094 | 1100 | |
|
1095 | 1101 | #------------------------------------------------------------------------- |
|
1096 | 1102 | # Things related to object introspection |
|
1097 | 1103 | #------------------------------------------------------------------------- |
|
1098 | 1104 | |
|
1099 | 1105 | def _ofind(self, oname, namespaces=None): |
|
1100 | 1106 | """Find an object in the available namespaces. |
|
1101 | 1107 | |
|
1102 | 1108 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1103 | 1109 | |
|
1104 | 1110 | Has special code to detect magic functions. |
|
1105 | 1111 | """ |
|
1106 | 1112 | #oname = oname.strip() |
|
1107 | 1113 | #print '1- oname: <%r>' % oname # dbg |
|
1108 | 1114 | try: |
|
1109 | 1115 | oname = oname.strip().encode('ascii') |
|
1110 | 1116 | #print '2- oname: <%r>' % oname # dbg |
|
1111 | 1117 | except UnicodeEncodeError: |
|
1112 | 1118 | print 'Python identifiers can only contain ascii characters.' |
|
1113 | 1119 | return dict(found=False) |
|
1114 | 1120 | |
|
1115 | 1121 | alias_ns = None |
|
1116 | 1122 | if namespaces is None: |
|
1117 | 1123 | # Namespaces to search in: |
|
1118 | 1124 | # Put them in a list. The order is important so that we |
|
1119 | 1125 | # find things in the same order that Python finds them. |
|
1120 | 1126 | namespaces = [ ('Interactive', self.user_ns), |
|
1121 | 1127 | ('IPython internal', self.internal_ns), |
|
1122 | 1128 | ('Python builtin', __builtin__.__dict__), |
|
1123 | 1129 | ('Alias', self.alias_manager.alias_table), |
|
1124 | 1130 | ] |
|
1125 | 1131 | alias_ns = self.alias_manager.alias_table |
|
1126 | 1132 | |
|
1127 | 1133 | # initialize results to 'null' |
|
1128 | 1134 | found = False; obj = None; ospace = None; ds = None; |
|
1129 | 1135 | ismagic = False; isalias = False; parent = None |
|
1130 | 1136 | |
|
1131 | 1137 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1132 | 1138 | # function but should only be treated as one if print_function was |
|
1133 | 1139 | # loaded with a future import. In this case, just bail. |
|
1134 | 1140 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1135 | 1141 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1136 | 1142 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1137 | 1143 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1138 | 1144 | |
|
1139 | 1145 | # Look for the given name by splitting it in parts. If the head is |
|
1140 | 1146 | # found, then we look for all the remaining parts as members, and only |
|
1141 | 1147 | # declare success if we can find them all. |
|
1142 | 1148 | oname_parts = oname.split('.') |
|
1143 | 1149 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1144 | 1150 | for nsname,ns in namespaces: |
|
1145 | 1151 | try: |
|
1146 | 1152 | obj = ns[oname_head] |
|
1147 | 1153 | except KeyError: |
|
1148 | 1154 | continue |
|
1149 | 1155 | else: |
|
1150 | 1156 | #print 'oname_rest:', oname_rest # dbg |
|
1151 | 1157 | for part in oname_rest: |
|
1152 | 1158 | try: |
|
1153 | 1159 | parent = obj |
|
1154 | 1160 | obj = getattr(obj,part) |
|
1155 | 1161 | except: |
|
1156 | 1162 | # Blanket except b/c some badly implemented objects |
|
1157 | 1163 | # allow __getattr__ to raise exceptions other than |
|
1158 | 1164 | # AttributeError, which then crashes IPython. |
|
1159 | 1165 | break |
|
1160 | 1166 | else: |
|
1161 | 1167 | # If we finish the for loop (no break), we got all members |
|
1162 | 1168 | found = True |
|
1163 | 1169 | ospace = nsname |
|
1164 | 1170 | if ns == alias_ns: |
|
1165 | 1171 | isalias = True |
|
1166 | 1172 | break # namespace loop |
|
1167 | 1173 | |
|
1168 | 1174 | # Try to see if it's magic |
|
1169 | 1175 | if not found: |
|
1170 | 1176 | if oname.startswith(ESC_MAGIC): |
|
1171 | 1177 | oname = oname[1:] |
|
1172 | 1178 | obj = getattr(self,'magic_'+oname,None) |
|
1173 | 1179 | if obj is not None: |
|
1174 | 1180 | found = True |
|
1175 | 1181 | ospace = 'IPython internal' |
|
1176 | 1182 | ismagic = True |
|
1177 | 1183 | |
|
1178 | 1184 | # Last try: special-case some literals like '', [], {}, etc: |
|
1179 | 1185 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1180 | 1186 | obj = eval(oname_head) |
|
1181 | 1187 | found = True |
|
1182 | 1188 | ospace = 'Interactive' |
|
1183 | 1189 | |
|
1184 | 1190 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1185 | 1191 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1186 | 1192 | |
|
1187 | 1193 | def _ofind_property(self, oname, info): |
|
1188 | 1194 | """Second part of object finding, to look for property details.""" |
|
1189 | 1195 | if info.found: |
|
1190 | 1196 | # Get the docstring of the class property if it exists. |
|
1191 | 1197 | path = oname.split('.') |
|
1192 | 1198 | root = '.'.join(path[:-1]) |
|
1193 | 1199 | if info.parent is not None: |
|
1194 | 1200 | try: |
|
1195 | 1201 | target = getattr(info.parent, '__class__') |
|
1196 | 1202 | # The object belongs to a class instance. |
|
1197 | 1203 | try: |
|
1198 | 1204 | target = getattr(target, path[-1]) |
|
1199 | 1205 | # The class defines the object. |
|
1200 | 1206 | if isinstance(target, property): |
|
1201 | 1207 | oname = root + '.__class__.' + path[-1] |
|
1202 | 1208 | info = Struct(self._ofind(oname)) |
|
1203 | 1209 | except AttributeError: pass |
|
1204 | 1210 | except AttributeError: pass |
|
1205 | 1211 | |
|
1206 | 1212 | # We return either the new info or the unmodified input if the object |
|
1207 | 1213 | # hadn't been found |
|
1208 | 1214 | return info |
|
1209 | 1215 | |
|
1210 | 1216 | def _object_find(self, oname, namespaces=None): |
|
1211 | 1217 | """Find an object and return a struct with info about it.""" |
|
1212 | 1218 | inf = Struct(self._ofind(oname, namespaces)) |
|
1213 | 1219 | return Struct(self._ofind_property(oname, inf)) |
|
1214 | 1220 | |
|
1215 | 1221 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1216 | 1222 | """Generic interface to the inspector system. |
|
1217 | 1223 | |
|
1218 | 1224 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1219 | 1225 | info = self._object_find(oname) |
|
1220 | 1226 | if info.found: |
|
1221 | 1227 | pmethod = getattr(self.inspector, meth) |
|
1222 | 1228 | formatter = format_screen if info.ismagic else None |
|
1223 | 1229 | if meth == 'pdoc': |
|
1224 | 1230 | pmethod(info.obj, oname, formatter) |
|
1225 | 1231 | elif meth == 'pinfo': |
|
1226 | 1232 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1227 | 1233 | else: |
|
1228 | 1234 | pmethod(info.obj, oname) |
|
1229 | 1235 | else: |
|
1230 | 1236 | print 'Object `%s` not found.' % oname |
|
1231 | 1237 | return 'not found' # so callers can take other action |
|
1232 | 1238 | |
|
1233 | 1239 | def object_inspect(self, oname): |
|
1234 | 1240 | info = self._object_find(oname) |
|
1235 | 1241 | if info.found: |
|
1236 | 1242 | return self.inspector.info(info.obj, oname, info=info) |
|
1237 | 1243 | else: |
|
1238 | 1244 | return oinspect.object_info(name=oname, found=False) |
|
1239 | 1245 | |
|
1240 | 1246 | #------------------------------------------------------------------------- |
|
1241 | 1247 | # Things related to history management |
|
1242 | 1248 | #------------------------------------------------------------------------- |
|
1243 | 1249 | |
|
1244 | 1250 | def init_history(self): |
|
1245 | 1251 | """Sets up the command history, and starts regular autosaves.""" |
|
1246 | 1252 | self.history_manager = HistoryManager(shell=self) |
|
1247 | 1253 | |
|
1248 | 1254 | def save_history(self): |
|
1249 | 1255 | """Save input history to a file (via readline library).""" |
|
1250 | 1256 | self.history_manager.save_history() |
|
1251 | 1257 | |
|
1252 | 1258 | def reload_history(self): |
|
1253 | 1259 | """Reload the input history from disk file.""" |
|
1254 | 1260 | self.history_manager.reload_history() |
|
1255 | 1261 | |
|
1256 | 1262 | def history_saving_wrapper(self, func): |
|
1257 | 1263 | """ Wrap func for readline history saving |
|
1258 | 1264 | |
|
1259 | 1265 | Convert func into callable that saves & restores |
|
1260 | 1266 | history around the call """ |
|
1261 | 1267 | |
|
1262 | 1268 | if self.has_readline: |
|
1263 | 1269 | from IPython.utils import rlineimpl as readline |
|
1264 | 1270 | else: |
|
1265 | 1271 | return func |
|
1266 | 1272 | |
|
1267 | 1273 | def wrapper(): |
|
1268 | 1274 | self.save_history() |
|
1269 | 1275 | try: |
|
1270 | 1276 | func() |
|
1271 | 1277 | finally: |
|
1272 | 1278 | self.reload_history() |
|
1273 | 1279 | return wrapper |
|
1274 | 1280 | |
|
1275 | 1281 | def get_history(self, index=None, raw=False, output=True): |
|
1276 | 1282 | return self.history_manager.get_history(index, raw, output) |
|
1277 | 1283 | |
|
1278 | 1284 | |
|
1279 | 1285 | #------------------------------------------------------------------------- |
|
1280 | 1286 | # Things related to exception handling and tracebacks (not debugging) |
|
1281 | 1287 | #------------------------------------------------------------------------- |
|
1282 | 1288 | |
|
1283 | 1289 | def init_traceback_handlers(self, custom_exceptions): |
|
1284 | 1290 | # Syntax error handler. |
|
1285 | 1291 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1286 | 1292 | |
|
1287 | 1293 | # The interactive one is initialized with an offset, meaning we always |
|
1288 | 1294 | # want to remove the topmost item in the traceback, which is our own |
|
1289 | 1295 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1290 | 1296 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1291 | 1297 | color_scheme='NoColor', |
|
1292 | 1298 | tb_offset = 1, |
|
1293 | 1299 | check_cache=self.compile.check_cache) |
|
1294 | 1300 | |
|
1295 | 1301 | # The instance will store a pointer to the system-wide exception hook, |
|
1296 | 1302 | # so that runtime code (such as magics) can access it. This is because |
|
1297 | 1303 | # during the read-eval loop, it may get temporarily overwritten. |
|
1298 | 1304 | self.sys_excepthook = sys.excepthook |
|
1299 | 1305 | |
|
1300 | 1306 | # and add any custom exception handlers the user may have specified |
|
1301 | 1307 | self.set_custom_exc(*custom_exceptions) |
|
1302 | 1308 | |
|
1303 | 1309 | # Set the exception mode |
|
1304 | 1310 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1305 | 1311 | |
|
1306 | 1312 | def set_custom_exc(self, exc_tuple, handler): |
|
1307 | 1313 | """set_custom_exc(exc_tuple,handler) |
|
1308 | 1314 | |
|
1309 | 1315 | Set a custom exception handler, which will be called if any of the |
|
1310 | 1316 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1311 | 1317 | run_code() method. |
|
1312 | 1318 | |
|
1313 | 1319 | Inputs: |
|
1314 | 1320 | |
|
1315 | 1321 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1316 | 1322 | handler for. It is very important that you use a tuple, and NOT A |
|
1317 | 1323 | LIST here, because of the way Python's except statement works. If |
|
1318 | 1324 | you only want to trap a single exception, use a singleton tuple: |
|
1319 | 1325 | |
|
1320 | 1326 | exc_tuple == (MyCustomException,) |
|
1321 | 1327 | |
|
1322 | 1328 | - handler: this must be defined as a function with the following |
|
1323 | 1329 | basic interface:: |
|
1324 | 1330 | |
|
1325 | 1331 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1326 | 1332 | ... |
|
1327 | 1333 | # The return value must be |
|
1328 | 1334 | return structured_traceback |
|
1329 | 1335 | |
|
1330 | 1336 | This will be made into an instance method (via types.MethodType) |
|
1331 | 1337 | of IPython itself, and it will be called if any of the exceptions |
|
1332 | 1338 | listed in the exc_tuple are caught. If the handler is None, an |
|
1333 | 1339 | internal basic one is used, which just prints basic info. |
|
1334 | 1340 | |
|
1335 | 1341 | WARNING: by putting in your own exception handler into IPython's main |
|
1336 | 1342 | execution loop, you run a very good chance of nasty crashes. This |
|
1337 | 1343 | facility should only be used if you really know what you are doing.""" |
|
1338 | 1344 | |
|
1339 | 1345 | assert type(exc_tuple)==type(()) , \ |
|
1340 | 1346 | "The custom exceptions must be given AS A TUPLE." |
|
1341 | 1347 | |
|
1342 | 1348 | def dummy_handler(self,etype,value,tb): |
|
1343 | 1349 | print '*** Simple custom exception handler ***' |
|
1344 | 1350 | print 'Exception type :',etype |
|
1345 | 1351 | print 'Exception value:',value |
|
1346 | 1352 | print 'Traceback :',tb |
|
1347 | 1353 | print 'Source code :','\n'.join(self.buffer) |
|
1348 | 1354 | |
|
1349 | 1355 | if handler is None: handler = dummy_handler |
|
1350 | 1356 | |
|
1351 | 1357 | self.CustomTB = types.MethodType(handler,self) |
|
1352 | 1358 | self.custom_exceptions = exc_tuple |
|
1353 | 1359 | |
|
1354 | 1360 | def excepthook(self, etype, value, tb): |
|
1355 | 1361 | """One more defense for GUI apps that call sys.excepthook. |
|
1356 | 1362 | |
|
1357 | 1363 | GUI frameworks like wxPython trap exceptions and call |
|
1358 | 1364 | sys.excepthook themselves. I guess this is a feature that |
|
1359 | 1365 | enables them to keep running after exceptions that would |
|
1360 | 1366 | otherwise kill their mainloop. This is a bother for IPython |
|
1361 | 1367 | which excepts to catch all of the program exceptions with a try: |
|
1362 | 1368 | except: statement. |
|
1363 | 1369 | |
|
1364 | 1370 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1365 | 1371 | any app directly invokes sys.excepthook, it will look to the user like |
|
1366 | 1372 | IPython crashed. In order to work around this, we can disable the |
|
1367 | 1373 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1368 | 1374 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1369 | 1375 | call sys.excepthook will generate a regular-looking exception from |
|
1370 | 1376 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1371 | 1377 | crashes. |
|
1372 | 1378 | |
|
1373 | 1379 | This hook should be used sparingly, only in places which are not likely |
|
1374 | 1380 | to be true IPython errors. |
|
1375 | 1381 | """ |
|
1376 | 1382 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1377 | 1383 | |
|
1378 | 1384 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1379 | 1385 | exception_only=False): |
|
1380 | 1386 | """Display the exception that just occurred. |
|
1381 | 1387 | |
|
1382 | 1388 | If nothing is known about the exception, this is the method which |
|
1383 | 1389 | should be used throughout the code for presenting user tracebacks, |
|
1384 | 1390 | rather than directly invoking the InteractiveTB object. |
|
1385 | 1391 | |
|
1386 | 1392 | A specific showsyntaxerror() also exists, but this method can take |
|
1387 | 1393 | care of calling it if needed, so unless you are explicitly catching a |
|
1388 | 1394 | SyntaxError exception, don't try to analyze the stack manually and |
|
1389 | 1395 | simply call this method.""" |
|
1390 | 1396 | |
|
1391 | 1397 | try: |
|
1392 | 1398 | if exc_tuple is None: |
|
1393 | 1399 | etype, value, tb = sys.exc_info() |
|
1394 | 1400 | else: |
|
1395 | 1401 | etype, value, tb = exc_tuple |
|
1396 | 1402 | |
|
1397 | 1403 | if etype is None: |
|
1398 | 1404 | if hasattr(sys, 'last_type'): |
|
1399 | 1405 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1400 | 1406 | sys.last_traceback |
|
1401 | 1407 | else: |
|
1402 | 1408 | self.write_err('No traceback available to show.\n') |
|
1403 | 1409 | return |
|
1404 | 1410 | |
|
1405 | 1411 | if etype is SyntaxError: |
|
1406 | 1412 | # Though this won't be called by syntax errors in the input |
|
1407 | 1413 | # line, there may be SyntaxError cases whith imported code. |
|
1408 | 1414 | self.showsyntaxerror(filename) |
|
1409 | 1415 | elif etype is UsageError: |
|
1410 | 1416 | print "UsageError:", value |
|
1411 | 1417 | else: |
|
1412 | 1418 | # WARNING: these variables are somewhat deprecated and not |
|
1413 | 1419 | # necessarily safe to use in a threaded environment, but tools |
|
1414 | 1420 | # like pdb depend on their existence, so let's set them. If we |
|
1415 | 1421 | # find problems in the field, we'll need to revisit their use. |
|
1416 | 1422 | sys.last_type = etype |
|
1417 | 1423 | sys.last_value = value |
|
1418 | 1424 | sys.last_traceback = tb |
|
1419 | 1425 | |
|
1420 | 1426 | if etype in self.custom_exceptions: |
|
1421 | 1427 | # FIXME: Old custom traceback objects may just return a |
|
1422 | 1428 | # string, in that case we just put it into a list |
|
1423 | 1429 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1424 | 1430 | if isinstance(ctb, basestring): |
|
1425 | 1431 | stb = [stb] |
|
1426 | 1432 | else: |
|
1427 | 1433 | if exception_only: |
|
1428 | 1434 | stb = ['An exception has occurred, use %tb to see ' |
|
1429 | 1435 | 'the full traceback.\n'] |
|
1430 | 1436 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1431 | 1437 | value)) |
|
1432 | 1438 | else: |
|
1433 | 1439 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1434 | 1440 | value, tb, tb_offset=tb_offset) |
|
1435 | 1441 | # FIXME: the pdb calling should be done by us, not by |
|
1436 | 1442 | # the code computing the traceback. |
|
1437 | 1443 | if self.InteractiveTB.call_pdb: |
|
1438 | 1444 | # pdb mucks up readline, fix it back |
|
1439 | 1445 | self.set_readline_completer() |
|
1440 | 1446 | |
|
1441 | 1447 | # Actually show the traceback |
|
1442 | 1448 | self._showtraceback(etype, value, stb) |
|
1443 | 1449 | |
|
1444 | 1450 | except KeyboardInterrupt: |
|
1445 | 1451 | self.write_err("\nKeyboardInterrupt\n") |
|
1446 | 1452 | |
|
1447 | 1453 | def _showtraceback(self, etype, evalue, stb): |
|
1448 | 1454 | """Actually show a traceback. |
|
1449 | 1455 | |
|
1450 | 1456 | Subclasses may override this method to put the traceback on a different |
|
1451 | 1457 | place, like a side channel. |
|
1452 | 1458 | """ |
|
1453 | 1459 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1454 | 1460 | |
|
1455 | 1461 | def showsyntaxerror(self, filename=None): |
|
1456 | 1462 | """Display the syntax error that just occurred. |
|
1457 | 1463 | |
|
1458 | 1464 | This doesn't display a stack trace because there isn't one. |
|
1459 | 1465 | |
|
1460 | 1466 | If a filename is given, it is stuffed in the exception instead |
|
1461 | 1467 | of what was there before (because Python's parser always uses |
|
1462 | 1468 | "<string>" when reading from a string). |
|
1463 | 1469 | """ |
|
1464 | 1470 | etype, value, last_traceback = sys.exc_info() |
|
1465 | 1471 | |
|
1466 | 1472 | # See note about these variables in showtraceback() above |
|
1467 | 1473 | sys.last_type = etype |
|
1468 | 1474 | sys.last_value = value |
|
1469 | 1475 | sys.last_traceback = last_traceback |
|
1470 | 1476 | |
|
1471 | 1477 | if filename and etype is SyntaxError: |
|
1472 | 1478 | # Work hard to stuff the correct filename in the exception |
|
1473 | 1479 | try: |
|
1474 | 1480 | msg, (dummy_filename, lineno, offset, line) = value |
|
1475 | 1481 | except: |
|
1476 | 1482 | # Not the format we expect; leave it alone |
|
1477 | 1483 | pass |
|
1478 | 1484 | else: |
|
1479 | 1485 | # Stuff in the right filename |
|
1480 | 1486 | try: |
|
1481 | 1487 | # Assume SyntaxError is a class exception |
|
1482 | 1488 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1483 | 1489 | except: |
|
1484 | 1490 | # If that failed, assume SyntaxError is a string |
|
1485 | 1491 | value = msg, (filename, lineno, offset, line) |
|
1486 | 1492 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1487 | 1493 | self._showtraceback(etype, value, stb) |
|
1488 | 1494 | |
|
1489 | 1495 | #------------------------------------------------------------------------- |
|
1490 | 1496 | # Things related to readline |
|
1491 | 1497 | #------------------------------------------------------------------------- |
|
1492 | 1498 | |
|
1493 | 1499 | def init_readline(self): |
|
1494 | 1500 | """Command history completion/saving/reloading.""" |
|
1495 | 1501 | |
|
1496 | 1502 | if self.readline_use: |
|
1497 | 1503 | import IPython.utils.rlineimpl as readline |
|
1498 | 1504 | |
|
1499 | 1505 | self.rl_next_input = None |
|
1500 | 1506 | self.rl_do_indent = False |
|
1501 | 1507 | |
|
1502 | 1508 | if not self.readline_use or not readline.have_readline: |
|
1503 | 1509 | self.has_readline = False |
|
1504 | 1510 | self.readline = None |
|
1505 | 1511 | # Set a number of methods that depend on readline to be no-op |
|
1506 | 1512 | self.set_readline_completer = no_op |
|
1507 | 1513 | self.set_custom_completer = no_op |
|
1508 | 1514 | self.set_completer_frame = no_op |
|
1509 | 1515 | warn('Readline services not available or not loaded.') |
|
1510 | 1516 | else: |
|
1511 | 1517 | self.has_readline = True |
|
1512 | 1518 | self.readline = readline |
|
1513 | 1519 | sys.modules['readline'] = readline |
|
1514 | 1520 | |
|
1515 | 1521 | # Platform-specific configuration |
|
1516 | 1522 | if os.name == 'nt': |
|
1517 | 1523 | # FIXME - check with Frederick to see if we can harmonize |
|
1518 | 1524 | # naming conventions with pyreadline to avoid this |
|
1519 | 1525 | # platform-dependent check |
|
1520 | 1526 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1521 | 1527 | else: |
|
1522 | 1528 | self.readline_startup_hook = readline.set_startup_hook |
|
1523 | 1529 | |
|
1524 | 1530 | # Load user's initrc file (readline config) |
|
1525 | 1531 | # Or if libedit is used, load editrc. |
|
1526 | 1532 | inputrc_name = os.environ.get('INPUTRC') |
|
1527 | 1533 | if inputrc_name is None: |
|
1528 | 1534 | home_dir = get_home_dir() |
|
1529 | 1535 | if home_dir is not None: |
|
1530 | 1536 | inputrc_name = '.inputrc' |
|
1531 | 1537 | if readline.uses_libedit: |
|
1532 | 1538 | inputrc_name = '.editrc' |
|
1533 | 1539 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1534 | 1540 | if os.path.isfile(inputrc_name): |
|
1535 | 1541 | try: |
|
1536 | 1542 | readline.read_init_file(inputrc_name) |
|
1537 | 1543 | except: |
|
1538 | 1544 | warn('Problems reading readline initialization file <%s>' |
|
1539 | 1545 | % inputrc_name) |
|
1540 | 1546 | |
|
1541 | 1547 | # Configure readline according to user's prefs |
|
1542 | 1548 | # This is only done if GNU readline is being used. If libedit |
|
1543 | 1549 | # is being used (as on Leopard) the readline config is |
|
1544 | 1550 | # not run as the syntax for libedit is different. |
|
1545 | 1551 | if not readline.uses_libedit: |
|
1546 | 1552 | for rlcommand in self.readline_parse_and_bind: |
|
1547 | 1553 | #print "loading rl:",rlcommand # dbg |
|
1548 | 1554 | readline.parse_and_bind(rlcommand) |
|
1549 | 1555 | |
|
1550 | 1556 | # Remove some chars from the delimiters list. If we encounter |
|
1551 | 1557 | # unicode chars, discard them. |
|
1552 | 1558 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1553 | 1559 | delims = delims.translate(None, self.readline_remove_delims) |
|
1554 | 1560 | delims = delims.replace(ESC_MAGIC, '') |
|
1555 | 1561 | readline.set_completer_delims(delims) |
|
1556 | 1562 | # otherwise we end up with a monster history after a while: |
|
1557 | 1563 | readline.set_history_length(self.history_length) |
|
1558 | 1564 | try: |
|
1559 | 1565 | #print '*** Reading readline history' # dbg |
|
1560 | 1566 | self.reload_history() |
|
1561 | 1567 | except IOError: |
|
1562 | 1568 | pass # It doesn't exist yet. |
|
1563 | 1569 | |
|
1564 | 1570 | # Configure auto-indent for all platforms |
|
1565 | 1571 | self.set_autoindent(self.autoindent) |
|
1566 | 1572 | |
|
1567 | 1573 | def set_next_input(self, s): |
|
1568 | 1574 | """ Sets the 'default' input string for the next command line. |
|
1569 | 1575 | |
|
1570 | 1576 | Requires readline. |
|
1571 | 1577 | |
|
1572 | 1578 | Example: |
|
1573 | 1579 | |
|
1574 | 1580 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1575 | 1581 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1576 | 1582 | """ |
|
1577 | 1583 | |
|
1578 | 1584 | self.rl_next_input = s |
|
1579 | 1585 | |
|
1580 | 1586 | # Maybe move this to the terminal subclass? |
|
1581 | 1587 | def pre_readline(self): |
|
1582 | 1588 | """readline hook to be used at the start of each line. |
|
1583 | 1589 | |
|
1584 | 1590 | Currently it handles auto-indent only.""" |
|
1585 | 1591 | |
|
1586 | 1592 | if self.rl_do_indent: |
|
1587 | 1593 | self.readline.insert_text(self._indent_current_str()) |
|
1588 | 1594 | if self.rl_next_input is not None: |
|
1589 | 1595 | self.readline.insert_text(self.rl_next_input) |
|
1590 | 1596 | self.rl_next_input = None |
|
1591 | 1597 | |
|
1592 | 1598 | def _indent_current_str(self): |
|
1593 | 1599 | """return the current level of indentation as a string""" |
|
1594 | 1600 | return self.input_splitter.indent_spaces * ' ' |
|
1595 | 1601 | |
|
1596 | 1602 | #------------------------------------------------------------------------- |
|
1597 | 1603 | # Things related to text completion |
|
1598 | 1604 | #------------------------------------------------------------------------- |
|
1599 | 1605 | |
|
1600 | 1606 | def init_completer(self): |
|
1601 | 1607 | """Initialize the completion machinery. |
|
1602 | 1608 | |
|
1603 | 1609 | This creates completion machinery that can be used by client code, |
|
1604 | 1610 | either interactively in-process (typically triggered by the readline |
|
1605 | 1611 | library), programatically (such as in test suites) or out-of-prcess |
|
1606 | 1612 | (typically over the network by remote frontends). |
|
1607 | 1613 | """ |
|
1608 | 1614 | from IPython.core.completer import IPCompleter |
|
1609 | 1615 | from IPython.core.completerlib import (module_completer, |
|
1610 | 1616 | magic_run_completer, cd_completer) |
|
1611 | 1617 | |
|
1612 | 1618 | self.Completer = IPCompleter(self, |
|
1613 | 1619 | self.user_ns, |
|
1614 | 1620 | self.user_global_ns, |
|
1615 | 1621 | self.readline_omit__names, |
|
1616 | 1622 | self.alias_manager.alias_table, |
|
1617 | 1623 | self.has_readline) |
|
1618 | 1624 | |
|
1619 | 1625 | # Add custom completers to the basic ones built into IPCompleter |
|
1620 | 1626 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1621 | 1627 | self.strdispatchers['complete_command'] = sdisp |
|
1622 | 1628 | self.Completer.custom_completers = sdisp |
|
1623 | 1629 | |
|
1624 | 1630 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1625 | 1631 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1626 | 1632 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1627 | 1633 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1628 | 1634 | |
|
1629 | 1635 | # Only configure readline if we truly are using readline. IPython can |
|
1630 | 1636 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1631 | 1637 | # itself may be absent |
|
1632 | 1638 | if self.has_readline: |
|
1633 | 1639 | self.set_readline_completer() |
|
1634 | 1640 | |
|
1635 | 1641 | def complete(self, text, line=None, cursor_pos=None): |
|
1636 | 1642 | """Return the completed text and a list of completions. |
|
1637 | 1643 | |
|
1638 | 1644 | Parameters |
|
1639 | 1645 | ---------- |
|
1640 | 1646 | |
|
1641 | 1647 | text : string |
|
1642 | 1648 | A string of text to be completed on. It can be given as empty and |
|
1643 | 1649 | instead a line/position pair are given. In this case, the |
|
1644 | 1650 | completer itself will split the line like readline does. |
|
1645 | 1651 | |
|
1646 | 1652 | line : string, optional |
|
1647 | 1653 | The complete line that text is part of. |
|
1648 | 1654 | |
|
1649 | 1655 | cursor_pos : int, optional |
|
1650 | 1656 | The position of the cursor on the input line. |
|
1651 | 1657 | |
|
1652 | 1658 | Returns |
|
1653 | 1659 | ------- |
|
1654 | 1660 | text : string |
|
1655 | 1661 | The actual text that was completed. |
|
1656 | 1662 | |
|
1657 | 1663 | matches : list |
|
1658 | 1664 | A sorted list with all possible completions. |
|
1659 | 1665 | |
|
1660 | 1666 | The optional arguments allow the completion to take more context into |
|
1661 | 1667 | account, and are part of the low-level completion API. |
|
1662 | 1668 | |
|
1663 | 1669 | This is a wrapper around the completion mechanism, similar to what |
|
1664 | 1670 | readline does at the command line when the TAB key is hit. By |
|
1665 | 1671 | exposing it as a method, it can be used by other non-readline |
|
1666 | 1672 | environments (such as GUIs) for text completion. |
|
1667 | 1673 | |
|
1668 | 1674 | Simple usage example: |
|
1669 | 1675 | |
|
1670 | 1676 | In [1]: x = 'hello' |
|
1671 | 1677 | |
|
1672 | 1678 | In [2]: _ip.complete('x.l') |
|
1673 | 1679 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1674 | 1680 | """ |
|
1675 | 1681 | |
|
1676 | 1682 | # Inject names into __builtin__ so we can complete on the added names. |
|
1677 | 1683 | with self.builtin_trap: |
|
1678 | 1684 | return self.Completer.complete(text, line, cursor_pos) |
|
1679 | 1685 | |
|
1680 | 1686 | def set_custom_completer(self, completer, pos=0): |
|
1681 | 1687 | """Adds a new custom completer function. |
|
1682 | 1688 | |
|
1683 | 1689 | The position argument (defaults to 0) is the index in the completers |
|
1684 | 1690 | list where you want the completer to be inserted.""" |
|
1685 | 1691 | |
|
1686 | 1692 | newcomp = types.MethodType(completer,self.Completer) |
|
1687 | 1693 | self.Completer.matchers.insert(pos,newcomp) |
|
1688 | 1694 | |
|
1689 | 1695 | def set_readline_completer(self): |
|
1690 | 1696 | """Reset readline's completer to be our own.""" |
|
1691 | 1697 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1692 | 1698 | |
|
1693 | 1699 | def set_completer_frame(self, frame=None): |
|
1694 | 1700 | """Set the frame of the completer.""" |
|
1695 | 1701 | if frame: |
|
1696 | 1702 | self.Completer.namespace = frame.f_locals |
|
1697 | 1703 | self.Completer.global_namespace = frame.f_globals |
|
1698 | 1704 | else: |
|
1699 | 1705 | self.Completer.namespace = self.user_ns |
|
1700 | 1706 | self.Completer.global_namespace = self.user_global_ns |
|
1701 | 1707 | |
|
1702 | 1708 | #------------------------------------------------------------------------- |
|
1703 | 1709 | # Things related to magics |
|
1704 | 1710 | #------------------------------------------------------------------------- |
|
1705 | 1711 | |
|
1706 | 1712 | def init_magics(self): |
|
1707 | 1713 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1708 | 1714 | # should be split into a prompt manager and displayhook. We probably |
|
1709 | 1715 | # even need a centralize colors management object. |
|
1710 | 1716 | self.magic_colors(self.colors) |
|
1711 | 1717 | # History was moved to a separate module |
|
1712 | 1718 | from . import history |
|
1713 | 1719 | history.init_ipython(self) |
|
1714 | 1720 | |
|
1715 | 1721 | def magic(self,arg_s): |
|
1716 | 1722 | """Call a magic function by name. |
|
1717 | 1723 | |
|
1718 | 1724 | Input: a string containing the name of the magic function to call and |
|
1719 | 1725 | any additional arguments to be passed to the magic. |
|
1720 | 1726 | |
|
1721 | 1727 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1722 | 1728 | prompt: |
|
1723 | 1729 | |
|
1724 | 1730 | In[1]: %name -opt foo bar |
|
1725 | 1731 | |
|
1726 | 1732 | To call a magic without arguments, simply use magic('name'). |
|
1727 | 1733 | |
|
1728 | 1734 | This provides a proper Python function to call IPython's magics in any |
|
1729 | 1735 | valid Python code you can type at the interpreter, including loops and |
|
1730 | 1736 | compound statements. |
|
1731 | 1737 | """ |
|
1732 | 1738 | args = arg_s.split(' ',1) |
|
1733 | 1739 | magic_name = args[0] |
|
1734 | 1740 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1735 | 1741 | |
|
1736 | 1742 | try: |
|
1737 | 1743 | magic_args = args[1] |
|
1738 | 1744 | except IndexError: |
|
1739 | 1745 | magic_args = '' |
|
1740 | 1746 | fn = getattr(self,'magic_'+magic_name,None) |
|
1741 | 1747 | if fn is None: |
|
1742 | 1748 | error("Magic function `%s` not found." % magic_name) |
|
1743 | 1749 | else: |
|
1744 | 1750 | magic_args = self.var_expand(magic_args,1) |
|
1745 | 1751 | with nested(self.builtin_trap,): |
|
1746 | 1752 | result = fn(magic_args) |
|
1747 | 1753 | return result |
|
1748 | 1754 | |
|
1749 | 1755 | def define_magic(self, magicname, func): |
|
1750 | 1756 | """Expose own function as magic function for ipython |
|
1751 | 1757 | |
|
1752 | 1758 | def foo_impl(self,parameter_s=''): |
|
1753 | 1759 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1754 | 1760 | print 'Magic function. Passed parameter is between < >:' |
|
1755 | 1761 | print '<%s>' % parameter_s |
|
1756 | 1762 | print 'The self object is:',self |
|
1757 | 1763 | |
|
1758 | 1764 | self.define_magic('foo',foo_impl) |
|
1759 | 1765 | """ |
|
1760 | 1766 | |
|
1761 | 1767 | import new |
|
1762 | 1768 | im = types.MethodType(func,self) |
|
1763 | 1769 | old = getattr(self, "magic_" + magicname, None) |
|
1764 | 1770 | setattr(self, "magic_" + magicname, im) |
|
1765 | 1771 | return old |
|
1766 | 1772 | |
|
1767 | 1773 | #------------------------------------------------------------------------- |
|
1768 | 1774 | # Things related to macros |
|
1769 | 1775 | #------------------------------------------------------------------------- |
|
1770 | 1776 | |
|
1771 | 1777 | def define_macro(self, name, themacro): |
|
1772 | 1778 | """Define a new macro |
|
1773 | 1779 | |
|
1774 | 1780 | Parameters |
|
1775 | 1781 | ---------- |
|
1776 | 1782 | name : str |
|
1777 | 1783 | The name of the macro. |
|
1778 | 1784 | themacro : str or Macro |
|
1779 | 1785 | The action to do upon invoking the macro. If a string, a new |
|
1780 | 1786 | Macro object is created by passing the string to it. |
|
1781 | 1787 | """ |
|
1782 | 1788 | |
|
1783 | 1789 | from IPython.core import macro |
|
1784 | 1790 | |
|
1785 | 1791 | if isinstance(themacro, basestring): |
|
1786 | 1792 | themacro = macro.Macro(themacro) |
|
1787 | 1793 | if not isinstance(themacro, macro.Macro): |
|
1788 | 1794 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1789 | 1795 | self.user_ns[name] = themacro |
|
1790 | 1796 | |
|
1791 | 1797 | #------------------------------------------------------------------------- |
|
1792 | 1798 | # Things related to the running of system commands |
|
1793 | 1799 | #------------------------------------------------------------------------- |
|
1794 | 1800 | |
|
1795 | 1801 | def system(self, cmd): |
|
1796 | 1802 | """Call the given cmd in a subprocess. |
|
1797 | 1803 | |
|
1798 | 1804 | Parameters |
|
1799 | 1805 | ---------- |
|
1800 | 1806 | cmd : str |
|
1801 | 1807 | Command to execute (can not end in '&', as bacground processes are |
|
1802 | 1808 | not supported. |
|
1803 | 1809 | """ |
|
1804 | 1810 | # We do not support backgrounding processes because we either use |
|
1805 | 1811 | # pexpect or pipes to read from. Users can always just call |
|
1806 | 1812 | # os.system() if they really want a background process. |
|
1807 | 1813 | if cmd.endswith('&'): |
|
1808 | 1814 | raise OSError("Background processes not supported.") |
|
1809 | 1815 | |
|
1810 | 1816 | return system(self.var_expand(cmd, depth=2)) |
|
1811 | 1817 | |
|
1812 | 1818 | def getoutput(self, cmd, split=True): |
|
1813 | 1819 | """Get output (possibly including stderr) from a subprocess. |
|
1814 | 1820 | |
|
1815 | 1821 | Parameters |
|
1816 | 1822 | ---------- |
|
1817 | 1823 | cmd : str |
|
1818 | 1824 | Command to execute (can not end in '&', as background processes are |
|
1819 | 1825 | not supported. |
|
1820 | 1826 | split : bool, optional |
|
1821 | 1827 | |
|
1822 | 1828 | If True, split the output into an IPython SList. Otherwise, an |
|
1823 | 1829 | IPython LSString is returned. These are objects similar to normal |
|
1824 | 1830 | lists and strings, with a few convenience attributes for easier |
|
1825 | 1831 | manipulation of line-based output. You can use '?' on them for |
|
1826 | 1832 | details. |
|
1827 | 1833 | """ |
|
1828 | 1834 | if cmd.endswith('&'): |
|
1829 | 1835 | raise OSError("Background processes not supported.") |
|
1830 | 1836 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1831 | 1837 | if split: |
|
1832 | 1838 | out = SList(out.splitlines()) |
|
1833 | 1839 | else: |
|
1834 | 1840 | out = LSString(out) |
|
1835 | 1841 | return out |
|
1836 | 1842 | |
|
1837 | 1843 | #------------------------------------------------------------------------- |
|
1838 | 1844 | # Things related to aliases |
|
1839 | 1845 | #------------------------------------------------------------------------- |
|
1840 | 1846 | |
|
1841 | 1847 | def init_alias(self): |
|
1842 | 1848 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1843 | 1849 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1844 | 1850 | |
|
1845 | 1851 | #------------------------------------------------------------------------- |
|
1846 | 1852 | # Things related to extensions and plugins |
|
1847 | 1853 | #------------------------------------------------------------------------- |
|
1848 | 1854 | |
|
1849 | 1855 | def init_extension_manager(self): |
|
1850 | 1856 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1851 | 1857 | |
|
1852 | 1858 | def init_plugin_manager(self): |
|
1853 | 1859 | self.plugin_manager = PluginManager(config=self.config) |
|
1854 | 1860 | |
|
1855 | 1861 | #------------------------------------------------------------------------- |
|
1856 | 1862 | # Things related to payloads |
|
1857 | 1863 | #------------------------------------------------------------------------- |
|
1858 | 1864 | |
|
1859 | 1865 | def init_payload(self): |
|
1860 | 1866 | self.payload_manager = PayloadManager(config=self.config) |
|
1861 | 1867 | |
|
1862 | 1868 | #------------------------------------------------------------------------- |
|
1863 | 1869 | # Things related to the prefilter |
|
1864 | 1870 | #------------------------------------------------------------------------- |
|
1865 | 1871 | |
|
1866 | 1872 | def init_prefilter(self): |
|
1867 | 1873 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1868 | 1874 | # Ultimately this will be refactored in the new interpreter code, but |
|
1869 | 1875 | # for now, we should expose the main prefilter method (there's legacy |
|
1870 | 1876 | # code out there that may rely on this). |
|
1871 | 1877 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1872 | 1878 | |
|
1873 | 1879 | def auto_rewrite_input(self, cmd): |
|
1874 | 1880 | """Print to the screen the rewritten form of the user's command. |
|
1875 | 1881 | |
|
1876 | 1882 | This shows visual feedback by rewriting input lines that cause |
|
1877 | 1883 | automatic calling to kick in, like:: |
|
1878 | 1884 | |
|
1879 | 1885 | /f x |
|
1880 | 1886 | |
|
1881 | 1887 | into:: |
|
1882 | 1888 | |
|
1883 | 1889 | ------> f(x) |
|
1884 | 1890 | |
|
1885 | 1891 | after the user's input prompt. This helps the user understand that the |
|
1886 | 1892 | input line was transformed automatically by IPython. |
|
1887 | 1893 | """ |
|
1888 | 1894 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1889 | 1895 | |
|
1890 | 1896 | try: |
|
1891 | 1897 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1892 | 1898 | # we use it and only print uncolored rewrite if we have unicode |
|
1893 | 1899 | rw = str(rw) |
|
1894 | 1900 | print >> IPython.utils.io.Term.cout, rw |
|
1895 | 1901 | except UnicodeEncodeError: |
|
1896 | 1902 | print "------> " + cmd |
|
1897 | 1903 | |
|
1898 | 1904 | #------------------------------------------------------------------------- |
|
1899 | 1905 | # Things related to extracting values/expressions from kernel and user_ns |
|
1900 | 1906 | #------------------------------------------------------------------------- |
|
1901 | 1907 | |
|
1902 | 1908 | def _simple_error(self): |
|
1903 | 1909 | etype, value = sys.exc_info()[:2] |
|
1904 | 1910 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1905 | 1911 | |
|
1906 | 1912 | def user_variables(self, names): |
|
1907 | 1913 | """Get a list of variable names from the user's namespace. |
|
1908 | 1914 | |
|
1909 | 1915 | Parameters |
|
1910 | 1916 | ---------- |
|
1911 | 1917 | names : list of strings |
|
1912 | 1918 | A list of names of variables to be read from the user namespace. |
|
1913 | 1919 | |
|
1914 | 1920 | Returns |
|
1915 | 1921 | ------- |
|
1916 | 1922 | A dict, keyed by the input names and with the repr() of each value. |
|
1917 | 1923 | """ |
|
1918 | 1924 | out = {} |
|
1919 | 1925 | user_ns = self.user_ns |
|
1920 | 1926 | for varname in names: |
|
1921 | 1927 | try: |
|
1922 | 1928 | value = repr(user_ns[varname]) |
|
1923 | 1929 | except: |
|
1924 | 1930 | value = self._simple_error() |
|
1925 | 1931 | out[varname] = value |
|
1926 | 1932 | return out |
|
1927 | 1933 | |
|
1928 | 1934 | def user_expressions(self, expressions): |
|
1929 | 1935 | """Evaluate a dict of expressions in the user's namespace. |
|
1930 | 1936 | |
|
1931 | 1937 | Parameters |
|
1932 | 1938 | ---------- |
|
1933 | 1939 | expressions : dict |
|
1934 | 1940 | A dict with string keys and string values. The expression values |
|
1935 | 1941 | should be valid Python expressions, each of which will be evaluated |
|
1936 | 1942 | in the user namespace. |
|
1937 | 1943 | |
|
1938 | 1944 | Returns |
|
1939 | 1945 | ------- |
|
1940 | 1946 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1941 | 1947 | value. |
|
1942 | 1948 | """ |
|
1943 | 1949 | out = {} |
|
1944 | 1950 | user_ns = self.user_ns |
|
1945 | 1951 | global_ns = self.user_global_ns |
|
1946 | 1952 | for key, expr in expressions.iteritems(): |
|
1947 | 1953 | try: |
|
1948 | 1954 | value = repr(eval(expr, global_ns, user_ns)) |
|
1949 | 1955 | except: |
|
1950 | 1956 | value = self._simple_error() |
|
1951 | 1957 | out[key] = value |
|
1952 | 1958 | return out |
|
1953 | 1959 | |
|
1954 | 1960 | #------------------------------------------------------------------------- |
|
1955 | 1961 | # Things related to the running of code |
|
1956 | 1962 | #------------------------------------------------------------------------- |
|
1957 | 1963 | |
|
1958 | 1964 | def ex(self, cmd): |
|
1959 | 1965 | """Execute a normal python statement in user namespace.""" |
|
1960 | 1966 | with nested(self.builtin_trap,): |
|
1961 | 1967 | exec cmd in self.user_global_ns, self.user_ns |
|
1962 | 1968 | |
|
1963 | 1969 | def ev(self, expr): |
|
1964 | 1970 | """Evaluate python expression expr in user namespace. |
|
1965 | 1971 | |
|
1966 | 1972 | Returns the result of evaluation |
|
1967 | 1973 | """ |
|
1968 | 1974 | with nested(self.builtin_trap,): |
|
1969 | 1975 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1970 | 1976 | |
|
1971 | 1977 | def safe_execfile(self, fname, *where, **kw): |
|
1972 | 1978 | """A safe version of the builtin execfile(). |
|
1973 | 1979 | |
|
1974 | 1980 | This version will never throw an exception, but instead print |
|
1975 | 1981 | helpful error messages to the screen. This only works on pure |
|
1976 | 1982 | Python files with the .py extension. |
|
1977 | 1983 | |
|
1978 | 1984 | Parameters |
|
1979 | 1985 | ---------- |
|
1980 | 1986 | fname : string |
|
1981 | 1987 | The name of the file to be executed. |
|
1982 | 1988 | where : tuple |
|
1983 | 1989 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1984 | 1990 | If only one is given, it is passed as both. |
|
1985 | 1991 | exit_ignore : bool (False) |
|
1986 | 1992 | If True, then silence SystemExit for non-zero status (it is always |
|
1987 | 1993 | silenced for zero status, as it is so common). |
|
1988 | 1994 | """ |
|
1989 | 1995 | kw.setdefault('exit_ignore', False) |
|
1990 | 1996 | |
|
1991 | 1997 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1992 | 1998 | |
|
1993 | 1999 | # Make sure we have a .py file |
|
1994 | 2000 | if not fname.endswith('.py'): |
|
1995 | 2001 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1996 | 2002 | |
|
1997 | 2003 | # Make sure we can open the file |
|
1998 | 2004 | try: |
|
1999 | 2005 | with open(fname) as thefile: |
|
2000 | 2006 | pass |
|
2001 | 2007 | except: |
|
2002 | 2008 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2003 | 2009 | return |
|
2004 | 2010 | |
|
2005 | 2011 | # Find things also in current directory. This is needed to mimic the |
|
2006 | 2012 | # behavior of running a script from the system command line, where |
|
2007 | 2013 | # Python inserts the script's directory into sys.path |
|
2008 | 2014 | dname = os.path.dirname(fname) |
|
2009 | 2015 | |
|
2010 | 2016 | with prepended_to_syspath(dname): |
|
2011 | 2017 | try: |
|
2012 | 2018 | execfile(fname,*where) |
|
2013 | 2019 | except SystemExit, status: |
|
2014 | 2020 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2015 | 2021 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2016 | 2022 | # these are considered normal by the OS: |
|
2017 | 2023 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2018 | 2024 | # 0 |
|
2019 | 2025 | # > python -c'import sys;sys.exit()'; echo $? |
|
2020 | 2026 | # 0 |
|
2021 | 2027 | # For other exit status, we show the exception unless |
|
2022 | 2028 | # explicitly silenced, but only in short form. |
|
2023 | 2029 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2024 | 2030 | self.showtraceback(exception_only=True) |
|
2025 | 2031 | except: |
|
2026 | 2032 | self.showtraceback() |
|
2027 | 2033 | |
|
2028 | 2034 | def safe_execfile_ipy(self, fname): |
|
2029 | 2035 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2030 | 2036 | |
|
2031 | 2037 | Parameters |
|
2032 | 2038 | ---------- |
|
2033 | 2039 | fname : str |
|
2034 | 2040 | The name of the file to execute. The filename must have a |
|
2035 | 2041 | .ipy extension. |
|
2036 | 2042 | """ |
|
2037 | 2043 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2038 | 2044 | |
|
2039 | 2045 | # Make sure we have a .py file |
|
2040 | 2046 | if not fname.endswith('.ipy'): |
|
2041 | 2047 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2042 | 2048 | |
|
2043 | 2049 | # Make sure we can open the file |
|
2044 | 2050 | try: |
|
2045 | 2051 | with open(fname) as thefile: |
|
2046 | 2052 | pass |
|
2047 | 2053 | except: |
|
2048 | 2054 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2049 | 2055 | return |
|
2050 | 2056 | |
|
2051 | 2057 | # Find things also in current directory. This is needed to mimic the |
|
2052 | 2058 | # behavior of running a script from the system command line, where |
|
2053 | 2059 | # Python inserts the script's directory into sys.path |
|
2054 | 2060 | dname = os.path.dirname(fname) |
|
2055 | 2061 | |
|
2056 | 2062 | with prepended_to_syspath(dname): |
|
2057 | 2063 | try: |
|
2058 | 2064 | with open(fname) as thefile: |
|
2059 | 2065 | # self.run_cell currently captures all exceptions |
|
2060 | 2066 | # raised in user code. It would be nice if there were |
|
2061 | 2067 | # versions of runlines, execfile that did raise, so |
|
2062 | 2068 | # we could catch the errors. |
|
2063 | 2069 | self.run_cell(thefile.read()) |
|
2064 | 2070 | except: |
|
2065 | 2071 | self.showtraceback() |
|
2066 | 2072 | warn('Unknown failure executing file: <%s>' % fname) |
|
2067 | 2073 | |
|
2068 | 2074 | def run_cell(self, cell): |
|
2069 | 2075 | """Run the contents of an entire multiline 'cell' of code. |
|
2070 | 2076 | |
|
2071 | 2077 | The cell is split into separate blocks which can be executed |
|
2072 | 2078 | individually. Then, based on how many blocks there are, they are |
|
2073 | 2079 | executed as follows: |
|
2074 | 2080 | |
|
2075 | 2081 | - A single block: 'single' mode. |
|
2076 | 2082 | |
|
2077 | 2083 | If there's more than one block, it depends: |
|
2078 | 2084 | |
|
2079 | 2085 | - if the last one is no more than two lines long, run all but the last |
|
2080 | 2086 | in 'exec' mode and the very last one in 'single' mode. This makes it |
|
2081 | 2087 | easy to type simple expressions at the end to see computed values. - |
|
2082 | 2088 | otherwise (last one is also multiline), run all in 'exec' mode |
|
2083 | 2089 | |
|
2084 | 2090 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, |
|
2085 | 2091 | results are displayed and output prompts are computed. In 'exec' mode, |
|
2086 | 2092 | no results are displayed unless :func:`print` is called explicitly; |
|
2087 | 2093 | this mode is more akin to running a script. |
|
2088 | 2094 | |
|
2089 | 2095 | Parameters |
|
2090 | 2096 | ---------- |
|
2091 | 2097 | cell : str |
|
2092 | 2098 | A single or multiline string. |
|
2093 | 2099 | """ |
|
2094 | 2100 | |
|
2095 | 2101 | # We need to break up the input into executable blocks that can be run |
|
2096 | 2102 | # in 'single' mode, to provide comfortable user behavior. |
|
2097 | 2103 | blocks = self.input_splitter.split_blocks(cell) |
|
2098 | 2104 | |
|
2099 | 2105 | if not blocks: |
|
2100 | 2106 | return |
|
2101 | 2107 | |
|
2102 | 2108 | # Store the 'ipython' version of the cell as well, since that's what |
|
2103 | 2109 | # needs to go into the translated history and get executed (the |
|
2104 | 2110 | # original cell may contain non-python syntax). |
|
2105 | 2111 | ipy_cell = ''.join(blocks) |
|
2106 | 2112 | |
|
2107 | 2113 | # Store raw and processed history |
|
2108 | 2114 | self.history_manager.store_inputs(ipy_cell, cell) |
|
2109 | 2115 | |
|
2110 | 2116 | self.logger.log(ipy_cell, cell) |
|
2111 | 2117 | # dbg code!!! |
|
2112 | 2118 | if 0: |
|
2113 | 2119 | def myapp(self, val): # dbg |
|
2114 | 2120 | import traceback as tb |
|
2115 | 2121 | stack = ''.join(tb.format_stack()) |
|
2116 | 2122 | print 'Value:', val |
|
2117 | 2123 | print 'Stack:\n', stack |
|
2118 | 2124 | list.append(self, val) |
|
2119 | 2125 | |
|
2120 | 2126 | import new |
|
2121 | 2127 | self.history_manager.input_hist_parsed.append = types.MethodType(myapp, |
|
2122 | 2128 | self.history_manager.input_hist_parsed) |
|
2123 | 2129 | # End dbg |
|
2124 | 2130 | |
|
2125 | 2131 | # All user code execution must happen with our context managers active |
|
2126 | 2132 | with nested(self.builtin_trap, self.display_trap): |
|
2127 | 2133 | |
|
2128 | 2134 | # Single-block input should behave like an interactive prompt |
|
2129 | 2135 | if len(blocks) == 1: |
|
2130 | 2136 | # since we return here, we need to update the execution count |
|
2131 | 2137 | out = self.run_one_block(blocks[0]) |
|
2132 | 2138 | self.execution_count += 1 |
|
2133 | 2139 | return out |
|
2134 | 2140 | |
|
2135 | 2141 | # In multi-block input, if the last block is a simple (one-two |
|
2136 | 2142 | # lines) expression, run it in single mode so it produces output. |
|
2137 | 2143 | # Otherwise just feed the whole thing to run_code. This seems like |
|
2138 | 2144 | # a reasonable usability design. |
|
2139 | 2145 | last = blocks[-1] |
|
2140 | 2146 | last_nlines = len(last.splitlines()) |
|
2141 | 2147 | |
|
2142 | 2148 | # Note: below, whenever we call run_code, we must sync history |
|
2143 | 2149 | # ourselves, because run_code is NOT meant to manage history at all. |
|
2144 | 2150 | if last_nlines < 2: |
|
2145 | 2151 | # Here we consider the cell split between 'body' and 'last', |
|
2146 | 2152 | # store all history and execute 'body', and if successful, then |
|
2147 | 2153 | # proceed to execute 'last'. |
|
2148 | 2154 | |
|
2149 | 2155 | # Get the main body to run as a cell |
|
2150 | 2156 | ipy_body = ''.join(blocks[:-1]) |
|
2151 | 2157 | retcode = self.run_source(ipy_body, symbol='exec', |
|
2152 | 2158 | post_execute=False) |
|
2153 | 2159 | if retcode==0: |
|
2154 | 2160 | # And the last expression via runlines so it produces output |
|
2155 | 2161 | self.run_one_block(last) |
|
2156 | 2162 | else: |
|
2157 | 2163 | # Run the whole cell as one entity, storing both raw and |
|
2158 | 2164 | # processed input in history |
|
2159 | 2165 | self.run_source(ipy_cell, symbol='exec') |
|
2160 | 2166 | |
|
2161 | 2167 | # Each cell is a *single* input, regardless of how many lines it has |
|
2162 | 2168 | self.execution_count += 1 |
|
2163 | 2169 | |
|
2164 | 2170 | def run_one_block(self, block): |
|
2165 | 2171 | """Run a single interactive block. |
|
2166 | 2172 | |
|
2167 | 2173 | If the block is single-line, dynamic transformations are applied to it |
|
2168 | 2174 | (like automagics, autocall and alias recognition). |
|
2169 | 2175 | """ |
|
2170 | 2176 | if len(block.splitlines()) <= 1: |
|
2171 | 2177 | out = self.run_single_line(block) |
|
2172 | 2178 | else: |
|
2173 | 2179 | out = self.run_code(block) |
|
2174 | 2180 | return out |
|
2175 | 2181 | |
|
2176 | 2182 | def run_single_line(self, line): |
|
2177 | 2183 | """Run a single-line interactive statement. |
|
2178 | 2184 | |
|
2179 | 2185 | This assumes the input has been transformed to IPython syntax by |
|
2180 | 2186 | applying all static transformations (those with an explicit prefix like |
|
2181 | 2187 | % or !), but it will further try to apply the dynamic ones. |
|
2182 | 2188 | |
|
2183 | 2189 | It does not update history. |
|
2184 | 2190 | """ |
|
2185 | 2191 | tline = self.prefilter_manager.prefilter_line(line) |
|
2186 | 2192 | return self.run_source(tline) |
|
2187 | 2193 | |
|
2188 | 2194 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2189 | 2195 | # input logic has been 100% moved to frontends and is stable. |
|
2190 | 2196 | def runlines(self, lines, clean=False): |
|
2191 | 2197 | """Run a string of one or more lines of source. |
|
2192 | 2198 | |
|
2193 | 2199 | This method is capable of running a string containing multiple source |
|
2194 | 2200 | lines, as if they had been entered at the IPython prompt. Since it |
|
2195 | 2201 | exposes IPython's processing machinery, the given strings can contain |
|
2196 | 2202 | magic calls (%magic), special shell access (!cmd), etc. |
|
2197 | 2203 | """ |
|
2198 | 2204 | |
|
2199 | 2205 | if isinstance(lines, (list, tuple)): |
|
2200 | 2206 | lines = '\n'.join(lines) |
|
2201 | 2207 | |
|
2202 | 2208 | if clean: |
|
2203 | 2209 | lines = self._cleanup_ipy_script(lines) |
|
2204 | 2210 | |
|
2205 | 2211 | # We must start with a clean buffer, in case this is run from an |
|
2206 | 2212 | # interactive IPython session (via a magic, for example). |
|
2207 | 2213 | self.reset_buffer() |
|
2208 | 2214 | lines = lines.splitlines() |
|
2209 | 2215 | |
|
2210 | 2216 | # Since we will prefilter all lines, store the user's raw input too |
|
2211 | 2217 | # before we apply any transformations |
|
2212 | 2218 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2213 | 2219 | |
|
2214 | 2220 | more = False |
|
2215 | 2221 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2216 | 2222 | with nested(self.builtin_trap, self.display_trap): |
|
2217 | 2223 | for line in lines: |
|
2218 | 2224 | # skip blank lines so we don't mess up the prompt counter, but |
|
2219 | 2225 | # do NOT skip even a blank line if we are in a code block (more |
|
2220 | 2226 | # is true) |
|
2221 | 2227 | |
|
2222 | 2228 | if line or more: |
|
2223 | 2229 | more = self.push_line(prefilter_lines(line, more)) |
|
2224 | 2230 | # IPython's run_source returns None if there was an error |
|
2225 | 2231 | # compiling the code. This allows us to stop processing |
|
2226 | 2232 | # right away, so the user gets the error message at the |
|
2227 | 2233 | # right place. |
|
2228 | 2234 | if more is None: |
|
2229 | 2235 | break |
|
2230 | 2236 | # final newline in case the input didn't have it, so that the code |
|
2231 | 2237 | # actually does get executed |
|
2232 | 2238 | if more: |
|
2233 | 2239 | self.push_line('\n') |
|
2234 | 2240 | |
|
2235 | 2241 | def run_source(self, source, filename=None, |
|
2236 | 2242 | symbol='single', post_execute=True): |
|
2237 | 2243 | """Compile and run some source in the interpreter. |
|
2238 | 2244 | |
|
2239 | 2245 | Arguments are as for compile_command(). |
|
2240 | 2246 | |
|
2241 | 2247 | One several things can happen: |
|
2242 | 2248 | |
|
2243 | 2249 | 1) The input is incorrect; compile_command() raised an |
|
2244 | 2250 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2245 | 2251 | will be printed by calling the showsyntaxerror() method. |
|
2246 | 2252 | |
|
2247 | 2253 | 2) The input is incomplete, and more input is required; |
|
2248 | 2254 | compile_command() returned None. Nothing happens. |
|
2249 | 2255 | |
|
2250 | 2256 | 3) The input is complete; compile_command() returned a code |
|
2251 | 2257 | object. The code is executed by calling self.run_code() (which |
|
2252 | 2258 | also handles run-time exceptions, except for SystemExit). |
|
2253 | 2259 | |
|
2254 | 2260 | The return value is: |
|
2255 | 2261 | |
|
2256 | 2262 | - True in case 2 |
|
2257 | 2263 | |
|
2258 | 2264 | - False in the other cases, unless an exception is raised, where |
|
2259 | 2265 | None is returned instead. This can be used by external callers to |
|
2260 | 2266 | know whether to continue feeding input or not. |
|
2261 | 2267 | |
|
2262 | 2268 | The return value can be used to decide whether to use sys.ps1 or |
|
2263 | 2269 | sys.ps2 to prompt the next line.""" |
|
2264 | 2270 | |
|
2265 | 2271 | # We need to ensure that the source is unicode from here on. |
|
2266 | 2272 | if type(source)==str: |
|
2267 | 2273 | usource = source.decode(self.stdin_encoding) |
|
2268 | 2274 | else: |
|
2269 | 2275 | usource = source |
|
2270 | 2276 | |
|
2271 | 2277 | if 0: # dbg |
|
2272 | 2278 | print 'Source:', repr(source) # dbg |
|
2273 | 2279 | print 'USource:', repr(usource) # dbg |
|
2274 | 2280 | print 'type:', type(source) # dbg |
|
2275 | 2281 | print 'encoding', self.stdin_encoding # dbg |
|
2276 | 2282 | |
|
2277 | 2283 | try: |
|
2278 | 2284 | code = self.compile(usource, symbol, self.execution_count) |
|
2279 | 2285 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2280 | 2286 | # Case 1 |
|
2281 | 2287 | self.showsyntaxerror(filename) |
|
2282 | 2288 | return None |
|
2283 | 2289 | |
|
2284 | 2290 | if code is None: |
|
2285 | 2291 | # Case 2 |
|
2286 | 2292 | return True |
|
2287 | 2293 | |
|
2288 | 2294 | # Case 3 |
|
2289 | 2295 | # We store the code object so that threaded shells and |
|
2290 | 2296 | # custom exception handlers can access all this info if needed. |
|
2291 | 2297 | # The source corresponding to this can be obtained from the |
|
2292 | 2298 | # buffer attribute as '\n'.join(self.buffer). |
|
2293 | 2299 | self.code_to_run = code |
|
2294 | 2300 | # now actually execute the code object |
|
2295 | 2301 | if self.run_code(code, post_execute) == 0: |
|
2296 | 2302 | return False |
|
2297 | 2303 | else: |
|
2298 | 2304 | return None |
|
2299 | 2305 | |
|
2300 | 2306 | # For backwards compatibility |
|
2301 | 2307 | runsource = run_source |
|
2302 | 2308 | |
|
2303 | 2309 | def run_code(self, code_obj, post_execute=True): |
|
2304 | 2310 | """Execute a code object. |
|
2305 | 2311 | |
|
2306 | 2312 | When an exception occurs, self.showtraceback() is called to display a |
|
2307 | 2313 | traceback. |
|
2308 | 2314 | |
|
2309 | 2315 | Return value: a flag indicating whether the code to be run completed |
|
2310 | 2316 | successfully: |
|
2311 | 2317 | |
|
2312 | 2318 | - 0: successful execution. |
|
2313 | 2319 | - 1: an error occurred. |
|
2314 | 2320 | """ |
|
2315 | 2321 | |
|
2316 | 2322 | # Set our own excepthook in case the user code tries to call it |
|
2317 | 2323 | # directly, so that the IPython crash handler doesn't get triggered |
|
2318 | 2324 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2319 | 2325 | |
|
2320 | 2326 | # we save the original sys.excepthook in the instance, in case config |
|
2321 | 2327 | # code (such as magics) needs access to it. |
|
2322 | 2328 | self.sys_excepthook = old_excepthook |
|
2323 | 2329 | outflag = 1 # happens in more places, so it's easier as default |
|
2324 | 2330 | try: |
|
2325 | 2331 | try: |
|
2326 | 2332 | self.hooks.pre_run_code_hook() |
|
2327 | 2333 | #rprint('Running code') # dbg |
|
2328 | 2334 | exec code_obj in self.user_global_ns, self.user_ns |
|
2329 | 2335 | finally: |
|
2330 | 2336 | # Reset our crash handler in place |
|
2331 | 2337 | sys.excepthook = old_excepthook |
|
2332 | 2338 | except SystemExit: |
|
2333 | 2339 | self.reset_buffer() |
|
2334 | 2340 | self.showtraceback(exception_only=True) |
|
2335 | 2341 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2336 | 2342 | except self.custom_exceptions: |
|
2337 | 2343 | etype,value,tb = sys.exc_info() |
|
2338 | 2344 | self.CustomTB(etype,value,tb) |
|
2339 | 2345 | except: |
|
2340 | 2346 | self.showtraceback() |
|
2341 | 2347 | else: |
|
2342 | 2348 | outflag = 0 |
|
2343 | 2349 | if softspace(sys.stdout, 0): |
|
2344 | 2350 | |
|
2345 | 2351 | |
|
2346 | 2352 | # Execute any registered post-execution functions. Here, any errors |
|
2347 | 2353 | # are reported only minimally and just on the terminal, because the |
|
2348 | 2354 | # main exception channel may be occupied with a user traceback. |
|
2349 | 2355 | # FIXME: we need to think this mechanism a little more carefully. |
|
2350 | 2356 | if post_execute: |
|
2351 | 2357 | for func in self._post_execute: |
|
2352 | 2358 | try: |
|
2353 | 2359 | func() |
|
2354 | 2360 | except: |
|
2355 | 2361 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2356 | 2362 | func |
|
2357 | 2363 | print >> io.Term.cout, head |
|
2358 | 2364 | print >> io.Term.cout, self._simple_error() |
|
2359 | 2365 | print >> io.Term.cout, 'Removing from post_execute' |
|
2360 | 2366 | self._post_execute.remove(func) |
|
2361 | 2367 | |
|
2362 | 2368 | # Flush out code object which has been run (and source) |
|
2363 | 2369 | self.code_to_run = None |
|
2364 | 2370 | return outflag |
|
2365 | 2371 | |
|
2366 | 2372 | # For backwards compatibility |
|
2367 | 2373 | runcode = run_code |
|
2368 | 2374 | |
|
2369 | 2375 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2370 | 2376 | # input logic has been 100% moved to frontends and is stable. |
|
2371 | 2377 | def push_line(self, line): |
|
2372 | 2378 | """Push a line to the interpreter. |
|
2373 | 2379 | |
|
2374 | 2380 | The line should not have a trailing newline; it may have |
|
2375 | 2381 | internal newlines. The line is appended to a buffer and the |
|
2376 | 2382 | interpreter's run_source() method is called with the |
|
2377 | 2383 | concatenated contents of the buffer as source. If this |
|
2378 | 2384 | indicates that the command was executed or invalid, the buffer |
|
2379 | 2385 | is reset; otherwise, the command is incomplete, and the buffer |
|
2380 | 2386 | is left as it was after the line was appended. The return |
|
2381 | 2387 | value is 1 if more input is required, 0 if the line was dealt |
|
2382 | 2388 | with in some way (this is the same as run_source()). |
|
2383 | 2389 | """ |
|
2384 | 2390 | |
|
2385 | 2391 | # autoindent management should be done here, and not in the |
|
2386 | 2392 | # interactive loop, since that one is only seen by keyboard input. We |
|
2387 | 2393 | # need this done correctly even for code run via runlines (which uses |
|
2388 | 2394 | # push). |
|
2389 | 2395 | |
|
2390 | 2396 | #print 'push line: <%s>' % line # dbg |
|
2391 | 2397 | self.buffer.append(line) |
|
2392 | 2398 | full_source = '\n'.join(self.buffer) |
|
2393 | 2399 | more = self.run_source(full_source, self.filename) |
|
2394 | 2400 | if not more: |
|
2395 | 2401 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), |
|
2396 | 2402 | full_source) |
|
2397 | 2403 | self.reset_buffer() |
|
2398 | 2404 | self.execution_count += 1 |
|
2399 | 2405 | return more |
|
2400 | 2406 | |
|
2401 | 2407 | def reset_buffer(self): |
|
2402 | 2408 | """Reset the input buffer.""" |
|
2403 | 2409 | self.buffer[:] = [] |
|
2404 | 2410 | self.buffer_raw[:] = [] |
|
2405 | 2411 | self.input_splitter.reset() |
|
2406 | 2412 | |
|
2407 | 2413 | # For backwards compatibility |
|
2408 | 2414 | resetbuffer = reset_buffer |
|
2409 | 2415 | |
|
2410 | 2416 | def _is_secondary_block_start(self, s): |
|
2411 | 2417 | if not s.endswith(':'): |
|
2412 | 2418 | return False |
|
2413 | 2419 | if (s.startswith('elif') or |
|
2414 | 2420 | s.startswith('else') or |
|
2415 | 2421 | s.startswith('except') or |
|
2416 | 2422 | s.startswith('finally')): |
|
2417 | 2423 | return True |
|
2418 | 2424 | |
|
2419 | 2425 | def _cleanup_ipy_script(self, script): |
|
2420 | 2426 | """Make a script safe for self.runlines() |
|
2421 | 2427 | |
|
2422 | 2428 | Currently, IPython is lines based, with blocks being detected by |
|
2423 | 2429 | empty lines. This is a problem for block based scripts that may |
|
2424 | 2430 | not have empty lines after blocks. This script adds those empty |
|
2425 | 2431 | lines to make scripts safe for running in the current line based |
|
2426 | 2432 | IPython. |
|
2427 | 2433 | """ |
|
2428 | 2434 | res = [] |
|
2429 | 2435 | lines = script.splitlines() |
|
2430 | 2436 | level = 0 |
|
2431 | 2437 | |
|
2432 | 2438 | for l in lines: |
|
2433 | 2439 | lstripped = l.lstrip() |
|
2434 | 2440 | stripped = l.strip() |
|
2435 | 2441 | if not stripped: |
|
2436 | 2442 | continue |
|
2437 | 2443 | newlevel = len(l) - len(lstripped) |
|
2438 | 2444 | if level > 0 and newlevel == 0 and \ |
|
2439 | 2445 | not self._is_secondary_block_start(stripped): |
|
2440 | 2446 | # add empty line |
|
2441 | 2447 | res.append('') |
|
2442 | 2448 | res.append(l) |
|
2443 | 2449 | level = newlevel |
|
2444 | 2450 | |
|
2445 | 2451 | return '\n'.join(res) + '\n' |
|
2446 | 2452 | |
|
2447 | 2453 | #------------------------------------------------------------------------- |
|
2448 | 2454 | # Things related to GUI support and pylab |
|
2449 | 2455 | #------------------------------------------------------------------------- |
|
2450 | 2456 | |
|
2451 | 2457 | def enable_pylab(self, gui=None): |
|
2452 | 2458 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2453 | 2459 | |
|
2454 | 2460 | #------------------------------------------------------------------------- |
|
2455 | 2461 | # Utilities |
|
2456 | 2462 | #------------------------------------------------------------------------- |
|
2457 | 2463 | |
|
2458 | 2464 | def var_expand(self,cmd,depth=0): |
|
2459 | 2465 | """Expand python variables in a string. |
|
2460 | 2466 | |
|
2461 | 2467 | The depth argument indicates how many frames above the caller should |
|
2462 | 2468 | be walked to look for the local namespace where to expand variables. |
|
2463 | 2469 | |
|
2464 | 2470 | The global namespace for expansion is always the user's interactive |
|
2465 | 2471 | namespace. |
|
2466 | 2472 | """ |
|
2467 | 2473 | |
|
2468 | 2474 | return str(ItplNS(cmd, |
|
2469 | 2475 | self.user_ns, # globals |
|
2470 | 2476 | # Skip our own frame in searching for locals: |
|
2471 | 2477 | sys._getframe(depth+1).f_locals # locals |
|
2472 | 2478 | )) |
|
2473 | 2479 | |
|
2474 | 2480 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2475 | 2481 | """Make a new tempfile and return its filename. |
|
2476 | 2482 | |
|
2477 | 2483 | This makes a call to tempfile.mktemp, but it registers the created |
|
2478 | 2484 | filename internally so ipython cleans it up at exit time. |
|
2479 | 2485 | |
|
2480 | 2486 | Optional inputs: |
|
2481 | 2487 | |
|
2482 | 2488 | - data(None): if data is given, it gets written out to the temp file |
|
2483 | 2489 | immediately, and the file is closed again.""" |
|
2484 | 2490 | |
|
2485 | 2491 | filename = tempfile.mktemp('.py', prefix) |
|
2486 | 2492 | self.tempfiles.append(filename) |
|
2487 | 2493 | |
|
2488 | 2494 | if data: |
|
2489 | 2495 | tmp_file = open(filename,'w') |
|
2490 | 2496 | tmp_file.write(data) |
|
2491 | 2497 | tmp_file.close() |
|
2492 | 2498 | return filename |
|
2493 | 2499 | |
|
2494 | 2500 | # TODO: This should be removed when Term is refactored. |
|
2495 | 2501 | def write(self,data): |
|
2496 | 2502 | """Write a string to the default output""" |
|
2497 | 2503 | io.Term.cout.write(data) |
|
2498 | 2504 | |
|
2499 | 2505 | # TODO: This should be removed when Term is refactored. |
|
2500 | 2506 | def write_err(self,data): |
|
2501 | 2507 | """Write a string to the default error output""" |
|
2502 | 2508 | io.Term.cerr.write(data) |
|
2503 | 2509 | |
|
2504 | 2510 | def ask_yes_no(self,prompt,default=True): |
|
2505 | 2511 | if self.quiet: |
|
2506 | 2512 | return True |
|
2507 | 2513 | return ask_yes_no(prompt,default) |
|
2508 | 2514 | |
|
2509 | 2515 | def show_usage(self): |
|
2510 | 2516 | """Show a usage message""" |
|
2511 | 2517 | page.page(IPython.core.usage.interactive_usage) |
|
2512 | 2518 | |
|
2513 | 2519 | #------------------------------------------------------------------------- |
|
2514 | 2520 | # Things related to IPython exiting |
|
2515 | 2521 | #------------------------------------------------------------------------- |
|
2516 | 2522 | def atexit_operations(self): |
|
2517 | 2523 | """This will be executed at the time of exit. |
|
2518 | 2524 | |
|
2519 | 2525 | Cleanup operations and saving of persistent data that is done |
|
2520 | 2526 | unconditionally by IPython should be performed here. |
|
2521 | 2527 | |
|
2522 | 2528 | For things that may depend on startup flags or platform specifics (such |
|
2523 | 2529 | as having readline or not), register a separate atexit function in the |
|
2524 | 2530 | code that has the appropriate information, rather than trying to |
|
2525 | 2531 | clutter |
|
2526 | 2532 | """ |
|
2527 | 2533 | # Cleanup all tempfiles left around |
|
2528 | 2534 | for tfile in self.tempfiles: |
|
2529 | 2535 | try: |
|
2530 | 2536 | os.unlink(tfile) |
|
2531 | 2537 | except OSError: |
|
2532 | 2538 | pass |
|
2533 | 2539 | |
|
2534 | 2540 | self.save_history() |
|
2535 | 2541 | |
|
2536 | 2542 | # Clear all user namespaces to release all references cleanly. |
|
2537 | 2543 | self.reset() |
|
2538 | 2544 | |
|
2539 | 2545 | # Run user hooks |
|
2540 | 2546 | self.hooks.shutdown_hook() |
|
2541 | 2547 | |
|
2542 | 2548 | def cleanup(self): |
|
2543 | 2549 | self.restore_sys_module_state() |
|
2544 | 2550 | |
|
2545 | 2551 | |
|
2546 | 2552 | class InteractiveShellABC(object): |
|
2547 | 2553 | """An abstract base class for InteractiveShell.""" |
|
2548 | 2554 | __metaclass__ = abc.ABCMeta |
|
2549 | 2555 | |
|
2550 | 2556 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,598 +1,598 b'' | |||
|
1 | 1 | from __future__ import print_function |
|
2 | 2 | |
|
3 | 3 | # Standard library imports |
|
4 | 4 | from collections import namedtuple |
|
5 | 5 | import sys |
|
6 | 6 | import time |
|
7 | 7 | |
|
8 | 8 | # System library imports |
|
9 | 9 | from pygments.lexers import PythonLexer |
|
10 | 10 | from PyQt4 import QtCore, QtGui |
|
11 | 11 | |
|
12 | 12 | # Local imports |
|
13 | 13 | from IPython.core.inputsplitter import InputSplitter, transform_classic_prompt |
|
14 | 14 | from IPython.core.oinspect import call_tip |
|
15 | 15 | from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin |
|
16 | 16 | from IPython.utils.traitlets import Bool |
|
17 | 17 | from bracket_matcher import BracketMatcher |
|
18 | 18 | from call_tip_widget import CallTipWidget |
|
19 | 19 | from completion_lexer import CompletionLexer |
|
20 | 20 | from history_console_widget import HistoryConsoleWidget |
|
21 | 21 | from pygments_highlighter import PygmentsHighlighter |
|
22 | 22 | |
|
23 | 23 | |
|
24 | 24 | class FrontendHighlighter(PygmentsHighlighter): |
|
25 | 25 | """ A PygmentsHighlighter that can be turned on and off and that ignores |
|
26 | 26 | prompts. |
|
27 | 27 | """ |
|
28 | 28 | |
|
29 | 29 | def __init__(self, frontend): |
|
30 | 30 | super(FrontendHighlighter, self).__init__(frontend._control.document()) |
|
31 | 31 | self._current_offset = 0 |
|
32 | 32 | self._frontend = frontend |
|
33 | 33 | self.highlighting_on = False |
|
34 | 34 | |
|
35 | 35 | def highlightBlock(self, qstring): |
|
36 | 36 | """ Highlight a block of text. Reimplemented to highlight selectively. |
|
37 | 37 | """ |
|
38 | 38 | if not self.highlighting_on: |
|
39 | 39 | return |
|
40 | 40 | |
|
41 | 41 | # The input to this function is unicode string that may contain |
|
42 | 42 | # paragraph break characters, non-breaking spaces, etc. Here we acquire |
|
43 | 43 | # the string as plain text so we can compare it. |
|
44 | 44 | current_block = self.currentBlock() |
|
45 | 45 | string = self._frontend._get_block_plain_text(current_block) |
|
46 | 46 | |
|
47 | 47 | # Decide whether to check for the regular or continuation prompt. |
|
48 | 48 | if current_block.contains(self._frontend._prompt_pos): |
|
49 | 49 | prompt = self._frontend._prompt |
|
50 | 50 | else: |
|
51 | 51 | prompt = self._frontend._continuation_prompt |
|
52 | 52 | |
|
53 | 53 | # Don't highlight the part of the string that contains the prompt. |
|
54 | 54 | if string.startswith(prompt): |
|
55 | 55 | self._current_offset = len(prompt) |
|
56 | 56 | qstring.remove(0, len(prompt)) |
|
57 | 57 | else: |
|
58 | 58 | self._current_offset = 0 |
|
59 | 59 | |
|
60 | 60 | PygmentsHighlighter.highlightBlock(self, qstring) |
|
61 | 61 | |
|
62 | 62 | def rehighlightBlock(self, block): |
|
63 | 63 | """ Reimplemented to temporarily enable highlighting if disabled. |
|
64 | 64 | """ |
|
65 | 65 | old = self.highlighting_on |
|
66 | 66 | self.highlighting_on = True |
|
67 | 67 | super(FrontendHighlighter, self).rehighlightBlock(block) |
|
68 | 68 | self.highlighting_on = old |
|
69 | 69 | |
|
70 | 70 | def setFormat(self, start, count, format): |
|
71 | 71 | """ Reimplemented to highlight selectively. |
|
72 | 72 | """ |
|
73 | 73 | start += self._current_offset |
|
74 | 74 | PygmentsHighlighter.setFormat(self, start, count, format) |
|
75 | 75 | |
|
76 | 76 | |
|
77 | 77 | class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin): |
|
78 | 78 | """ A Qt frontend for a generic Python kernel. |
|
79 | 79 | """ |
|
80 | 80 | |
|
81 | 81 | # An option and corresponding signal for overriding the default kernel |
|
82 | 82 | # interrupt behavior. |
|
83 | 83 | custom_interrupt = Bool(False) |
|
84 | 84 | custom_interrupt_requested = QtCore.pyqtSignal() |
|
85 | 85 | |
|
86 | 86 | # An option and corresponding signals for overriding the default kernel |
|
87 | 87 | # restart behavior. |
|
88 | 88 | custom_restart = Bool(False) |
|
89 | 89 | custom_restart_kernel_died = QtCore.pyqtSignal(float) |
|
90 | 90 | custom_restart_requested = QtCore.pyqtSignal() |
|
91 | 91 | |
|
92 | 92 | # Emitted when an 'execute_reply' has been received from the kernel and |
|
93 | 93 | # processed by the FrontendWidget. |
|
94 | 94 | executed = QtCore.pyqtSignal(object) |
|
95 | 95 | |
|
96 | 96 | # Emitted when an exit request has been received from the kernel. |
|
97 | 97 | exit_requested = QtCore.pyqtSignal() |
|
98 | 98 | |
|
99 | 99 | # Protected class variables. |
|
100 | 100 | _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos']) |
|
101 | 101 | _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos']) |
|
102 | 102 | _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind']) |
|
103 | 103 | _input_splitter_class = InputSplitter |
|
104 | 104 | _local_kernel = False |
|
105 | 105 | |
|
106 | 106 | #--------------------------------------------------------------------------- |
|
107 | 107 | # 'object' interface |
|
108 | 108 | #--------------------------------------------------------------------------- |
|
109 | 109 | |
|
110 | 110 | def __init__(self, *args, **kw): |
|
111 | 111 | super(FrontendWidget, self).__init__(*args, **kw) |
|
112 | 112 | |
|
113 | 113 | # FrontendWidget protected variables. |
|
114 | 114 | self._bracket_matcher = BracketMatcher(self._control) |
|
115 | 115 | self._call_tip_widget = CallTipWidget(self._control) |
|
116 | 116 | self._completion_lexer = CompletionLexer(PythonLexer()) |
|
117 | 117 | self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None) |
|
118 | 118 | self._hidden = False |
|
119 | 119 | self._highlighter = FrontendHighlighter(self) |
|
120 | 120 | self._input_splitter = self._input_splitter_class(input_mode='cell') |
|
121 | 121 | self._kernel_manager = None |
|
122 | 122 | self._request_info = {} |
|
123 | 123 | |
|
124 | 124 | # Configure the ConsoleWidget. |
|
125 | 125 | self.tab_width = 4 |
|
126 | 126 | self._set_continuation_prompt('... ') |
|
127 | 127 | |
|
128 | 128 | # Configure the CallTipWidget. |
|
129 | 129 | self._call_tip_widget.setFont(self.font) |
|
130 | 130 | self.font_changed.connect(self._call_tip_widget.setFont) |
|
131 | 131 | |
|
132 | 132 | # Configure actions. |
|
133 | 133 | action = self._copy_raw_action |
|
134 | 134 | key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C |
|
135 | 135 | action.setEnabled(False) |
|
136 | 136 | action.setShortcut(QtGui.QKeySequence(key)) |
|
137 | 137 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) |
|
138 | 138 | action.triggered.connect(self.copy_raw) |
|
139 | 139 | self.copy_available.connect(action.setEnabled) |
|
140 | 140 | self.addAction(action) |
|
141 | 141 | |
|
142 | 142 | # Connect signal handlers. |
|
143 | 143 | document = self._control.document() |
|
144 | 144 | document.contentsChange.connect(self._document_contents_change) |
|
145 | 145 | |
|
146 | 146 | # set flag for whether we are connected via localhost |
|
147 | 147 | self._local_kernel = kw.get('local_kernel', FrontendWidget._local_kernel) |
|
148 | 148 | |
|
149 | 149 | #--------------------------------------------------------------------------- |
|
150 | 150 | # 'ConsoleWidget' public interface |
|
151 | 151 | #--------------------------------------------------------------------------- |
|
152 | 152 | |
|
153 | 153 | def copy(self): |
|
154 | 154 | """ Copy the currently selected text to the clipboard, removing prompts. |
|
155 | 155 | """ |
|
156 | 156 | text = unicode(self._control.textCursor().selection().toPlainText()) |
|
157 | 157 | if text: |
|
158 | 158 | lines = map(transform_classic_prompt, text.splitlines()) |
|
159 | 159 | text = '\n'.join(lines) |
|
160 | 160 | QtGui.QApplication.clipboard().setText(text) |
|
161 | 161 | |
|
162 | 162 | #--------------------------------------------------------------------------- |
|
163 | 163 | # 'ConsoleWidget' abstract interface |
|
164 | 164 | #--------------------------------------------------------------------------- |
|
165 | 165 | |
|
166 | 166 | def _is_complete(self, source, interactive): |
|
167 | 167 | """ Returns whether 'source' can be completely processed and a new |
|
168 | 168 | prompt created. When triggered by an Enter/Return key press, |
|
169 | 169 | 'interactive' is True; otherwise, it is False. |
|
170 | 170 | """ |
|
171 | 171 | complete = self._input_splitter.push(source) |
|
172 | 172 | if interactive: |
|
173 | 173 | complete = not self._input_splitter.push_accepts_more() |
|
174 | 174 | return complete |
|
175 | 175 | |
|
176 | 176 | def _execute(self, source, hidden): |
|
177 | 177 | """ Execute 'source'. If 'hidden', do not show any output. |
|
178 | 178 | |
|
179 | 179 | See parent class :meth:`execute` docstring for full details. |
|
180 | 180 | """ |
|
181 | 181 | msg_id = self.kernel_manager.xreq_channel.execute(source, hidden) |
|
182 | 182 | self._request_info['execute'] = self._ExecutionRequest(msg_id, 'user') |
|
183 | 183 | self._hidden = hidden |
|
184 | 184 | |
|
185 | 185 | def _prompt_started_hook(self): |
|
186 | 186 | """ Called immediately after a new prompt is displayed. |
|
187 | 187 | """ |
|
188 | 188 | if not self._reading: |
|
189 | 189 | self._highlighter.highlighting_on = True |
|
190 | 190 | |
|
191 | 191 | def _prompt_finished_hook(self): |
|
192 | 192 | """ Called immediately after a prompt is finished, i.e. when some input |
|
193 | 193 | will be processed and a new prompt displayed. |
|
194 | 194 | """ |
|
195 | 195 | if not self._reading: |
|
196 | 196 | self._highlighter.highlighting_on = False |
|
197 | 197 | |
|
198 | 198 | def _tab_pressed(self): |
|
199 | 199 | """ Called when the tab key is pressed. Returns whether to continue |
|
200 | 200 | processing the event. |
|
201 | 201 | """ |
|
202 | 202 | # Perform tab completion if: |
|
203 | 203 | # 1) The cursor is in the input buffer. |
|
204 | 204 | # 2) There is a non-whitespace character before the cursor. |
|
205 | 205 | text = self._get_input_buffer_cursor_line() |
|
206 | 206 | if text is None: |
|
207 | 207 | return False |
|
208 | 208 | complete = bool(text[:self._get_input_buffer_cursor_column()].strip()) |
|
209 | 209 | if complete: |
|
210 | 210 | self._complete() |
|
211 | 211 | return not complete |
|
212 | 212 | |
|
213 | 213 | #--------------------------------------------------------------------------- |
|
214 | 214 | # 'ConsoleWidget' protected interface |
|
215 | 215 | #--------------------------------------------------------------------------- |
|
216 | 216 | |
|
217 | 217 | def _context_menu_make(self, pos): |
|
218 | 218 | """ Reimplemented to add an action for raw copy. |
|
219 | 219 | """ |
|
220 | 220 | menu = super(FrontendWidget, self)._context_menu_make(pos) |
|
221 | 221 | for before_action in menu.actions(): |
|
222 | 222 | if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ |
|
223 | 223 | QtGui.QKeySequence.ExactMatch: |
|
224 | 224 | menu.insertAction(before_action, self._copy_raw_action) |
|
225 | 225 | break |
|
226 | 226 | return menu |
|
227 | 227 | |
|
228 | 228 | def _event_filter_console_keypress(self, event): |
|
229 | 229 | """ Reimplemented for execution interruption and smart backspace. |
|
230 | 230 | """ |
|
231 | 231 | key = event.key() |
|
232 | 232 | if self._control_key_down(event.modifiers(), include_command=False): |
|
233 | 233 | |
|
234 | 234 | if key == QtCore.Qt.Key_C and self._executing: |
|
235 | 235 | self.interrupt_kernel() |
|
236 | 236 | return True |
|
237 | 237 | |
|
238 | 238 | elif key == QtCore.Qt.Key_Period: |
|
239 | 239 | message = 'Are you sure you want to restart the kernel?' |
|
240 | 240 | self.restart_kernel(message, now=False) |
|
241 | 241 | return True |
|
242 | 242 | |
|
243 | 243 | elif not event.modifiers() & QtCore.Qt.AltModifier: |
|
244 | 244 | |
|
245 | 245 | # Smart backspace: remove four characters in one backspace if: |
|
246 | 246 | # 1) everything left of the cursor is whitespace |
|
247 | 247 | # 2) the four characters immediately left of the cursor are spaces |
|
248 | 248 | if key == QtCore.Qt.Key_Backspace: |
|
249 | 249 | col = self._get_input_buffer_cursor_column() |
|
250 | 250 | cursor = self._control.textCursor() |
|
251 | 251 | if col > 3 and not cursor.hasSelection(): |
|
252 | 252 | text = self._get_input_buffer_cursor_line()[:col] |
|
253 | 253 | if text.endswith(' ') and not text.strip(): |
|
254 | 254 | cursor.movePosition(QtGui.QTextCursor.Left, |
|
255 | 255 | QtGui.QTextCursor.KeepAnchor, 4) |
|
256 | 256 | cursor.removeSelectedText() |
|
257 | 257 | return True |
|
258 | 258 | |
|
259 | 259 | return super(FrontendWidget, self)._event_filter_console_keypress(event) |
|
260 | 260 | |
|
261 | 261 | def _insert_continuation_prompt(self, cursor): |
|
262 | 262 | """ Reimplemented for auto-indentation. |
|
263 | 263 | """ |
|
264 | 264 | super(FrontendWidget, self)._insert_continuation_prompt(cursor) |
|
265 | 265 | cursor.insertText(' ' * self._input_splitter.indent_spaces) |
|
266 | 266 | |
|
267 | 267 | #--------------------------------------------------------------------------- |
|
268 | 268 | # 'BaseFrontendMixin' abstract interface |
|
269 | 269 | #--------------------------------------------------------------------------- |
|
270 | 270 | |
|
271 | 271 | def _handle_complete_reply(self, rep): |
|
272 | 272 | """ Handle replies for tab completion. |
|
273 | 273 | """ |
|
274 | 274 | cursor = self._get_cursor() |
|
275 | 275 | info = self._request_info.get('complete') |
|
276 | 276 | if info and info.id == rep['parent_header']['msg_id'] and \ |
|
277 | 277 | info.pos == cursor.position(): |
|
278 | 278 | text = '.'.join(self._get_context()) |
|
279 | 279 | cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) |
|
280 | 280 | self._complete_with_items(cursor, rep['content']['matches']) |
|
281 | 281 | |
|
282 | 282 | def _handle_execute_reply(self, msg): |
|
283 | 283 | """ Handles replies for code execution. |
|
284 | 284 | """ |
|
285 | 285 | info = self._request_info.get('execute') |
|
286 | 286 | if info and info.id == msg['parent_header']['msg_id'] and \ |
|
287 | 287 | info.kind == 'user' and not self._hidden: |
|
288 | 288 | # Make sure that all output from the SUB channel has been processed |
|
289 | 289 | # before writing a new prompt. |
|
290 | 290 | self.kernel_manager.sub_channel.flush() |
|
291 | 291 | |
|
292 | 292 | # Reset the ANSI style information to prevent bad text in stdout |
|
293 | 293 | # from messing up our colors. We're not a true terminal so we're |
|
294 | 294 | # allowed to do this. |
|
295 | 295 | if self.ansi_codes: |
|
296 | 296 | self._ansi_processor.reset_sgr() |
|
297 | 297 | |
|
298 | 298 | content = msg['content'] |
|
299 | 299 | status = content['status'] |
|
300 | 300 | if status == 'ok': |
|
301 | 301 | self._process_execute_ok(msg) |
|
302 | 302 | elif status == 'error': |
|
303 | 303 | self._process_execute_error(msg) |
|
304 | 304 | elif status == 'abort': |
|
305 | 305 | self._process_execute_abort(msg) |
|
306 | 306 | |
|
307 | 307 | self._show_interpreter_prompt_for_reply(msg) |
|
308 | 308 | self.executed.emit(msg) |
|
309 | 309 | |
|
310 | 310 | def _handle_input_request(self, msg): |
|
311 | 311 | """ Handle requests for raw_input. |
|
312 | 312 | """ |
|
313 | 313 | if self._hidden: |
|
314 | 314 | raise RuntimeError('Request for raw input during hidden execution.') |
|
315 | 315 | |
|
316 | 316 | # Make sure that all output from the SUB channel has been processed |
|
317 | 317 | # before entering readline mode. |
|
318 | 318 | self.kernel_manager.sub_channel.flush() |
|
319 | 319 | |
|
320 | 320 | def callback(line): |
|
321 | 321 | self.kernel_manager.rep_channel.input(line) |
|
322 | 322 | self._readline(msg['content']['prompt'], callback=callback) |
|
323 | 323 | |
|
324 | 324 | def _handle_kernel_died(self, since_last_heartbeat): |
|
325 | 325 | """ Handle the kernel's death by asking if the user wants to restart. |
|
326 | 326 | """ |
|
327 | 327 | if self.custom_restart: |
|
328 | 328 | self.custom_restart_kernel_died.emit(since_last_heartbeat) |
|
329 | 329 | else: |
|
330 | 330 | message = 'The kernel heartbeat has been inactive for %.2f ' \ |
|
331 | 331 | 'seconds. Do you want to restart the kernel? You may ' \ |
|
332 | 332 | 'first want to check the network connection.' % \ |
|
333 | 333 | since_last_heartbeat |
|
334 | 334 | self.restart_kernel(message, now=True) |
|
335 | 335 | |
|
336 | 336 | def _handle_object_info_reply(self, rep): |
|
337 | 337 | """ Handle replies for call tips. |
|
338 | 338 | """ |
|
339 | 339 | cursor = self._get_cursor() |
|
340 | 340 | info = self._request_info.get('call_tip') |
|
341 | 341 | if info and info.id == rep['parent_header']['msg_id'] and \ |
|
342 | 342 | info.pos == cursor.position(): |
|
343 | 343 | # Get the information for a call tip. For now we format the call |
|
344 | 344 | # line as string, later we can pass False to format_call and |
|
345 | 345 | # syntax-highlight it ourselves for nicer formatting in the |
|
346 | 346 | # calltip. |
|
347 | 347 | call_info, doc = call_tip(rep['content'], format_call=True) |
|
348 | 348 | if call_info or doc: |
|
349 | 349 | self._call_tip_widget.show_call_info(call_info, doc) |
|
350 | 350 | |
|
351 | 351 | def _handle_pyout(self, msg): |
|
352 | 352 | """ Handle display hook output. |
|
353 | 353 | """ |
|
354 | 354 | if not self._hidden and self._is_from_this_session(msg): |
|
355 | self._append_plain_text(msg['content']['data'] + '\n') | |
|
355 | self._append_plain_text(msg['content']['data']['text/plain'] + '\n') | |
|
356 | 356 | |
|
357 | 357 | def _handle_stream(self, msg): |
|
358 | 358 | """ Handle stdout, stderr, and stdin. |
|
359 | 359 | """ |
|
360 | 360 | if not self._hidden and self._is_from_this_session(msg): |
|
361 | 361 | # Most consoles treat tabs as being 8 space characters. Convert tabs |
|
362 | 362 | # to spaces so that output looks as expected regardless of this |
|
363 | 363 | # widget's tab width. |
|
364 | 364 | text = msg['content']['data'].expandtabs(8) |
|
365 | 365 | |
|
366 | 366 | self._append_plain_text(text) |
|
367 | 367 | self._control.moveCursor(QtGui.QTextCursor.End) |
|
368 | 368 | |
|
369 | 369 | def _handle_shutdown_reply(self, msg): |
|
370 | 370 | """ Handle shutdown signal, only if from other console. |
|
371 | 371 | """ |
|
372 | 372 | if not self._hidden and not self._is_from_this_session(msg): |
|
373 | 373 | if self._local_kernel: |
|
374 | 374 | if not msg['content']['restart']: |
|
375 | 375 | sys.exit(0) |
|
376 | 376 | else: |
|
377 | 377 | # we just got notified of a restart! |
|
378 | 378 | time.sleep(0.25) # wait 1/4 sec to reset |
|
379 | 379 | # lest the request for a new prompt |
|
380 | 380 | # goes to the old kernel |
|
381 | 381 | self.reset() |
|
382 | 382 | else: # remote kernel, prompt on Kernel shutdown/reset |
|
383 | 383 | title = self.window().windowTitle() |
|
384 | 384 | if not msg['content']['restart']: |
|
385 | 385 | reply = QtGui.QMessageBox.question(self, title, |
|
386 | 386 | "Kernel has been shutdown permanently. Close the Console?", |
|
387 | 387 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) |
|
388 | 388 | if reply == QtGui.QMessageBox.Yes: |
|
389 | 389 | sys.exit(0) |
|
390 | 390 | else: |
|
391 | 391 | reply = QtGui.QMessageBox.question(self, title, |
|
392 | 392 | "Kernel has been reset. Clear the Console?", |
|
393 | 393 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) |
|
394 | 394 | if reply == QtGui.QMessageBox.Yes: |
|
395 | 395 | time.sleep(0.25) # wait 1/4 sec to reset |
|
396 | 396 | # lest the request for a new prompt |
|
397 | 397 | # goes to the old kernel |
|
398 | 398 | self.reset() |
|
399 | 399 | |
|
400 | 400 | def _started_channels(self): |
|
401 | 401 | """ Called when the KernelManager channels have started listening or |
|
402 | 402 | when the frontend is assigned an already listening KernelManager. |
|
403 | 403 | """ |
|
404 | 404 | self.reset() |
|
405 | 405 | |
|
406 | 406 | #--------------------------------------------------------------------------- |
|
407 | 407 | # 'FrontendWidget' public interface |
|
408 | 408 | #--------------------------------------------------------------------------- |
|
409 | 409 | |
|
410 | 410 | def copy_raw(self): |
|
411 | 411 | """ Copy the currently selected text to the clipboard without attempting |
|
412 | 412 | to remove prompts or otherwise alter the text. |
|
413 | 413 | """ |
|
414 | 414 | self._control.copy() |
|
415 | 415 | |
|
416 | 416 | def execute_file(self, path, hidden=False): |
|
417 | 417 | """ Attempts to execute file with 'path'. If 'hidden', no output is |
|
418 | 418 | shown. |
|
419 | 419 | """ |
|
420 | 420 | self.execute('execfile("%s")' % path, hidden=hidden) |
|
421 | 421 | |
|
422 | 422 | def interrupt_kernel(self): |
|
423 | 423 | """ Attempts to interrupt the running kernel. |
|
424 | 424 | """ |
|
425 | 425 | if self.custom_interrupt: |
|
426 | 426 | self.custom_interrupt_requested.emit() |
|
427 | 427 | elif self.kernel_manager.has_kernel: |
|
428 | 428 | self.kernel_manager.interrupt_kernel() |
|
429 | 429 | else: |
|
430 | 430 | self._append_plain_text('Kernel process is either remote or ' |
|
431 | 431 | 'unspecified. Cannot interrupt.\n') |
|
432 | 432 | |
|
433 | 433 | def reset(self): |
|
434 | 434 | """ Resets the widget to its initial state. Similar to ``clear``, but |
|
435 | 435 | also re-writes the banner and aborts execution if necessary. |
|
436 | 436 | """ |
|
437 | 437 | if self._executing: |
|
438 | 438 | self._executing = False |
|
439 | 439 | self._request_info['execute'] = None |
|
440 | 440 | self._reading = False |
|
441 | 441 | self._highlighter.highlighting_on = False |
|
442 | 442 | |
|
443 | 443 | self._control.clear() |
|
444 | 444 | self._append_plain_text(self._get_banner()) |
|
445 | 445 | self._show_interpreter_prompt() |
|
446 | 446 | |
|
447 | 447 | def restart_kernel(self, message, now=False): |
|
448 | 448 | """ Attempts to restart the running kernel. |
|
449 | 449 | """ |
|
450 | 450 | # FIXME: now should be configurable via a checkbox in the dialog. Right |
|
451 | 451 | # now at least the heartbeat path sets it to True and the manual restart |
|
452 | 452 | # to False. But those should just be the pre-selected states of a |
|
453 | 453 | # checkbox that the user could override if so desired. But I don't know |
|
454 | 454 | # enough Qt to go implementing the checkbox now. |
|
455 | 455 | |
|
456 | 456 | if self.custom_restart: |
|
457 | 457 | self.custom_restart_requested.emit() |
|
458 | 458 | |
|
459 | 459 | elif self.kernel_manager.has_kernel: |
|
460 | 460 | # Pause the heart beat channel to prevent further warnings. |
|
461 | 461 | self.kernel_manager.hb_channel.pause() |
|
462 | 462 | |
|
463 | 463 | # Prompt the user to restart the kernel. Un-pause the heartbeat if |
|
464 | 464 | # they decline. (If they accept, the heartbeat will be un-paused |
|
465 | 465 | # automatically when the kernel is restarted.) |
|
466 | 466 | buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No |
|
467 | 467 | result = QtGui.QMessageBox.question(self, 'Restart kernel?', |
|
468 | 468 | message, buttons) |
|
469 | 469 | if result == QtGui.QMessageBox.Yes: |
|
470 | 470 | try: |
|
471 | 471 | self.kernel_manager.restart_kernel(now=now) |
|
472 | 472 | except RuntimeError: |
|
473 | 473 | self._append_plain_text('Kernel started externally. ' |
|
474 | 474 | 'Cannot restart.\n') |
|
475 | 475 | else: |
|
476 | 476 | self.reset() |
|
477 | 477 | else: |
|
478 | 478 | self.kernel_manager.hb_channel.unpause() |
|
479 | 479 | |
|
480 | 480 | else: |
|
481 | 481 | self._append_plain_text('Kernel process is either remote or ' |
|
482 | 482 | 'unspecified. Cannot restart.\n') |
|
483 | 483 | |
|
484 | 484 | #--------------------------------------------------------------------------- |
|
485 | 485 | # 'FrontendWidget' protected interface |
|
486 | 486 | #--------------------------------------------------------------------------- |
|
487 | 487 | |
|
488 | 488 | def _call_tip(self): |
|
489 | 489 | """ Shows a call tip, if appropriate, at the current cursor location. |
|
490 | 490 | """ |
|
491 | 491 | # Decide if it makes sense to show a call tip |
|
492 | 492 | cursor = self._get_cursor() |
|
493 | 493 | cursor.movePosition(QtGui.QTextCursor.Left) |
|
494 | 494 | if cursor.document().characterAt(cursor.position()).toAscii() != '(': |
|
495 | 495 | return False |
|
496 | 496 | context = self._get_context(cursor) |
|
497 | 497 | if not context: |
|
498 | 498 | return False |
|
499 | 499 | |
|
500 | 500 | # Send the metadata request to the kernel |
|
501 | 501 | name = '.'.join(context) |
|
502 | 502 | msg_id = self.kernel_manager.xreq_channel.object_info(name) |
|
503 | 503 | pos = self._get_cursor().position() |
|
504 | 504 | self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) |
|
505 | 505 | return True |
|
506 | 506 | |
|
507 | 507 | def _complete(self): |
|
508 | 508 | """ Performs completion at the current cursor location. |
|
509 | 509 | """ |
|
510 | 510 | context = self._get_context() |
|
511 | 511 | if context: |
|
512 | 512 | # Send the completion request to the kernel |
|
513 | 513 | msg_id = self.kernel_manager.xreq_channel.complete( |
|
514 | 514 | '.'.join(context), # text |
|
515 | 515 | self._get_input_buffer_cursor_line(), # line |
|
516 | 516 | self._get_input_buffer_cursor_column(), # cursor_pos |
|
517 | 517 | self.input_buffer) # block |
|
518 | 518 | pos = self._get_cursor().position() |
|
519 | 519 | info = self._CompletionRequest(msg_id, pos) |
|
520 | 520 | self._request_info['complete'] = info |
|
521 | 521 | |
|
522 | 522 | def _get_banner(self): |
|
523 | 523 | """ Gets a banner to display at the beginning of a session. |
|
524 | 524 | """ |
|
525 | 525 | banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \ |
|
526 | 526 | '"license" for more information.' |
|
527 | 527 | return banner % (sys.version, sys.platform) |
|
528 | 528 | |
|
529 | 529 | def _get_context(self, cursor=None): |
|
530 | 530 | """ Gets the context for the specified cursor (or the current cursor |
|
531 | 531 | if none is specified). |
|
532 | 532 | """ |
|
533 | 533 | if cursor is None: |
|
534 | 534 | cursor = self._get_cursor() |
|
535 | 535 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, |
|
536 | 536 | QtGui.QTextCursor.KeepAnchor) |
|
537 | 537 | text = unicode(cursor.selection().toPlainText()) |
|
538 | 538 | return self._completion_lexer.get_context(text) |
|
539 | 539 | |
|
540 | 540 | def _process_execute_abort(self, msg): |
|
541 | 541 | """ Process a reply for an aborted execution request. |
|
542 | 542 | """ |
|
543 | 543 | self._append_plain_text("ERROR: execution aborted\n") |
|
544 | 544 | |
|
545 | 545 | def _process_execute_error(self, msg): |
|
546 | 546 | """ Process a reply for an execution request that resulted in an error. |
|
547 | 547 | """ |
|
548 | 548 | content = msg['content'] |
|
549 | 549 | # If a SystemExit is passed along, this means exit() was called - also |
|
550 | 550 | # all the ipython %exit magic syntax of '-k' to be used to keep |
|
551 | 551 | # the kernel running |
|
552 | 552 | if content['ename']=='SystemExit': |
|
553 | 553 | keepkernel = content['evalue']=='-k' or content['evalue']=='True' |
|
554 | 554 | self._keep_kernel_on_exit = keepkernel |
|
555 | 555 | self.exit_requested.emit() |
|
556 | 556 | else: |
|
557 | 557 | traceback = ''.join(content['traceback']) |
|
558 | 558 | self._append_plain_text(traceback) |
|
559 | 559 | |
|
560 | 560 | def _process_execute_ok(self, msg): |
|
561 | 561 | """ Process a reply for a successful execution equest. |
|
562 | 562 | """ |
|
563 | 563 | payload = msg['content']['payload'] |
|
564 | 564 | for item in payload: |
|
565 | 565 | if not self._process_execute_payload(item): |
|
566 | 566 | warning = 'Warning: received unknown payload of type %s' |
|
567 | 567 | print(warning % repr(item['source'])) |
|
568 | 568 | |
|
569 | 569 | def _process_execute_payload(self, item): |
|
570 | 570 | """ Process a single payload item from the list of payload items in an |
|
571 | 571 | execution reply. Returns whether the payload was handled. |
|
572 | 572 | """ |
|
573 | 573 | # The basic FrontendWidget doesn't handle payloads, as they are a |
|
574 | 574 | # mechanism for going beyond the standard Python interpreter model. |
|
575 | 575 | return False |
|
576 | 576 | |
|
577 | 577 | def _show_interpreter_prompt(self): |
|
578 | 578 | """ Shows a prompt for the interpreter. |
|
579 | 579 | """ |
|
580 | 580 | self._show_prompt('>>> ') |
|
581 | 581 | |
|
582 | 582 | def _show_interpreter_prompt_for_reply(self, msg): |
|
583 | 583 | """ Shows a prompt for the interpreter given an 'execute_reply' message. |
|
584 | 584 | """ |
|
585 | 585 | self._show_interpreter_prompt() |
|
586 | 586 | |
|
587 | 587 | #------ Signal handlers ---------------------------------------------------- |
|
588 | 588 | |
|
589 | 589 | def _document_contents_change(self, position, removed, added): |
|
590 | 590 | """ Called whenever the document's content changes. Display a call tip |
|
591 | 591 | if appropriate. |
|
592 | 592 | """ |
|
593 | 593 | # Calculate where the cursor should be *after* the change: |
|
594 | 594 | position += added |
|
595 | 595 | |
|
596 | 596 | document = self._control.document() |
|
597 | 597 | if position == self._get_cursor().position(): |
|
598 | 598 | self._call_tip() |
@@ -1,482 +1,495 b'' | |||
|
1 | 1 | """ A FrontendWidget that emulates the interface of the console IPython and |
|
2 | 2 | supports the additional functionality provided by the IPython kernel. |
|
3 | 3 | |
|
4 | 4 | TODO: Add support for retrieving the system default editor. Requires code |
|
5 | 5 | paths for Windows (use the registry), Mac OS (use LaunchServices), and |
|
6 | 6 | Linux (use the xdg system). |
|
7 | 7 | """ |
|
8 | 8 | |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | # Imports |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | # Standard library imports |
|
14 | 14 | from collections import namedtuple |
|
15 | 15 | import re |
|
16 | 16 | from subprocess import Popen |
|
17 | 17 | from textwrap import dedent |
|
18 | 18 | |
|
19 | 19 | # System library imports |
|
20 | 20 | from PyQt4 import QtCore, QtGui |
|
21 | 21 | |
|
22 | 22 | # Local imports |
|
23 | 23 | from IPython.core.inputsplitter import IPythonInputSplitter, \ |
|
24 | 24 | transform_ipy_prompt |
|
25 | 25 | from IPython.core.usage import default_gui_banner |
|
26 | 26 | from IPython.utils.traitlets import Bool, Str |
|
27 | 27 | from frontend_widget import FrontendWidget |
|
28 | 28 | from styles import (default_light_style_sheet, default_light_syntax_style, |
|
29 | 29 | default_dark_style_sheet, default_dark_syntax_style, |
|
30 | 30 | default_bw_style_sheet, default_bw_syntax_style) |
|
31 | 31 | |
|
32 | 32 | #----------------------------------------------------------------------------- |
|
33 | 33 | # Constants |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | |
|
36 | 36 | # Default strings to build and display input and output prompts (and separators |
|
37 | 37 | # in between) |
|
38 | 38 | default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' |
|
39 | 39 | default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' |
|
40 | 40 | default_input_sep = '\n' |
|
41 | 41 | default_output_sep = '' |
|
42 | 42 | default_output_sep2 = '' |
|
43 | 43 | |
|
44 | 44 | # Base path for most payload sources. |
|
45 | 45 | zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell' |
|
46 | 46 | |
|
47 | 47 | #----------------------------------------------------------------------------- |
|
48 | 48 | # IPythonWidget class |
|
49 | 49 | #----------------------------------------------------------------------------- |
|
50 | 50 | |
|
51 | 51 | class IPythonWidget(FrontendWidget): |
|
52 | 52 | """ A FrontendWidget for an IPython kernel. |
|
53 | 53 | """ |
|
54 | 54 | |
|
55 | 55 | # If set, the 'custom_edit_requested(str, int)' signal will be emitted when |
|
56 | 56 | # an editor is needed for a file. This overrides 'editor' and 'editor_line' |
|
57 | 57 | # settings. |
|
58 | 58 | custom_edit = Bool(False) |
|
59 | 59 | custom_edit_requested = QtCore.pyqtSignal(object, object) |
|
60 | 60 | |
|
61 | 61 | # A command for invoking a system text editor. If the string contains a |
|
62 | 62 | # {filename} format specifier, it will be used. Otherwise, the filename will |
|
63 | 63 | # be appended to the end the command. |
|
64 | 64 | editor = Str('default', config=True) |
|
65 | 65 | |
|
66 | 66 | # The editor command to use when a specific line number is requested. The |
|
67 | 67 | # string should contain two format specifiers: {line} and {filename}. If |
|
68 | 68 | # this parameter is not specified, the line number option to the %edit magic |
|
69 | 69 | # will be ignored. |
|
70 | 70 | editor_line = Str(config=True) |
|
71 | 71 | |
|
72 | 72 | # A CSS stylesheet. The stylesheet can contain classes for: |
|
73 | 73 | # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc |
|
74 | 74 | # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter) |
|
75 | 75 | # 3. IPython: .error, .in-prompt, .out-prompt, etc |
|
76 | 76 | style_sheet = Str(config=True) |
|
77 | 77 | |
|
78 | 78 | # If not empty, use this Pygments style for syntax highlighting. Otherwise, |
|
79 | 79 | # the style sheet is queried for Pygments style information. |
|
80 | 80 | syntax_style = Str(config=True) |
|
81 | 81 | |
|
82 | 82 | # Prompts. |
|
83 | 83 | in_prompt = Str(default_in_prompt, config=True) |
|
84 | 84 | out_prompt = Str(default_out_prompt, config=True) |
|
85 | 85 | input_sep = Str(default_input_sep, config=True) |
|
86 | 86 | output_sep = Str(default_output_sep, config=True) |
|
87 | 87 | output_sep2 = Str(default_output_sep2, config=True) |
|
88 | 88 | |
|
89 | 89 | # FrontendWidget protected class variables. |
|
90 | 90 | _input_splitter_class = IPythonInputSplitter |
|
91 | 91 | |
|
92 | 92 | # IPythonWidget protected class variables. |
|
93 | 93 | _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) |
|
94 | 94 | _payload_source_edit = zmq_shell_source + '.edit_magic' |
|
95 | 95 | _payload_source_exit = zmq_shell_source + '.ask_exit' |
|
96 | 96 | _payload_source_loadpy = zmq_shell_source + '.magic_loadpy' |
|
97 | 97 | _payload_source_page = 'IPython.zmq.page.page' |
|
98 | 98 | |
|
99 | 99 | #--------------------------------------------------------------------------- |
|
100 | 100 | # 'object' interface |
|
101 | 101 | #--------------------------------------------------------------------------- |
|
102 | 102 | |
|
103 | 103 | def __init__(self, *args, **kw): |
|
104 | 104 | super(IPythonWidget, self).__init__(*args, **kw) |
|
105 | 105 | |
|
106 | 106 | # IPythonWidget protected variables. |
|
107 | 107 | self._code_to_load = None |
|
108 | 108 | self._payload_handlers = { |
|
109 | 109 | self._payload_source_edit : self._handle_payload_edit, |
|
110 | 110 | self._payload_source_exit : self._handle_payload_exit, |
|
111 | 111 | self._payload_source_page : self._handle_payload_page, |
|
112 | 112 | self._payload_source_loadpy : self._handle_payload_loadpy } |
|
113 | 113 | self._previous_prompt_obj = None |
|
114 | 114 | self._keep_kernel_on_exit = None |
|
115 | 115 | |
|
116 | 116 | # Initialize widget styling. |
|
117 | 117 | if self.style_sheet: |
|
118 | 118 | self._style_sheet_changed() |
|
119 | 119 | self._syntax_style_changed() |
|
120 | 120 | else: |
|
121 | 121 | self.set_default_style() |
|
122 | 122 | |
|
123 | 123 | #--------------------------------------------------------------------------- |
|
124 | 124 | # 'BaseFrontendMixin' abstract interface |
|
125 | 125 | #--------------------------------------------------------------------------- |
|
126 | 126 | |
|
127 | 127 | def _handle_complete_reply(self, rep): |
|
128 | 128 | """ Reimplemented to support IPython's improved completion machinery. |
|
129 | 129 | """ |
|
130 | 130 | cursor = self._get_cursor() |
|
131 | 131 | info = self._request_info.get('complete') |
|
132 | 132 | if info and info.id == rep['parent_header']['msg_id'] and \ |
|
133 | 133 | info.pos == cursor.position(): |
|
134 | 134 | matches = rep['content']['matches'] |
|
135 | 135 | text = rep['content']['matched_text'] |
|
136 | 136 | offset = len(text) |
|
137 | 137 | |
|
138 | 138 | # Clean up matches with period and path separators if the matched |
|
139 | 139 | # text has not been transformed. This is done by truncating all |
|
140 | 140 | # but the last component and then suitably decreasing the offset |
|
141 | 141 | # between the current cursor position and the start of completion. |
|
142 | 142 | if len(matches) > 1 and matches[0][:offset] == text: |
|
143 | 143 | parts = re.split(r'[./\\]', text) |
|
144 | 144 | sep_count = len(parts) - 1 |
|
145 | 145 | if sep_count: |
|
146 | 146 | chop_length = sum(map(len, parts[:sep_count])) + sep_count |
|
147 | 147 | matches = [ match[chop_length:] for match in matches ] |
|
148 | 148 | offset -= chop_length |
|
149 | 149 | |
|
150 | 150 | # Move the cursor to the start of the match and complete. |
|
151 | 151 | cursor.movePosition(QtGui.QTextCursor.Left, n=offset) |
|
152 | 152 | self._complete_with_items(cursor, matches) |
|
153 | 153 | |
|
154 | 154 | def _handle_execute_reply(self, msg): |
|
155 | 155 | """ Reimplemented to support prompt requests. |
|
156 | 156 | """ |
|
157 | 157 | info = self._request_info.get('execute') |
|
158 | 158 | if info and info.id == msg['parent_header']['msg_id']: |
|
159 | 159 | if info.kind == 'prompt': |
|
160 | 160 | number = msg['content']['execution_count'] + 1 |
|
161 | 161 | self._show_interpreter_prompt(number) |
|
162 | 162 | else: |
|
163 | 163 | super(IPythonWidget, self)._handle_execute_reply(msg) |
|
164 | 164 | |
|
165 | 165 | def _handle_history_reply(self, msg): |
|
166 | 166 | """ Implemented to handle history replies, which are only supported by |
|
167 | 167 | the IPython kernel. |
|
168 | 168 | """ |
|
169 | 169 | history_dict = msg['content']['history'] |
|
170 | 170 | input_history_dict = {} |
|
171 | 171 | for key,val in history_dict.items(): |
|
172 | 172 | input_history_dict[int(key)] = val |
|
173 | 173 | items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ] |
|
174 | 174 | self._set_history(items) |
|
175 | 175 | |
|
176 | 176 | def _handle_pyout(self, msg): |
|
177 | 177 | """ Reimplemented for IPython-style "display hook". |
|
178 | 178 | """ |
|
179 | 179 | if not self._hidden and self._is_from_this_session(msg): |
|
180 | 180 | content = msg['content'] |
|
181 | 181 | prompt_number = content['execution_count'] |
|
182 | self._append_plain_text(self.output_sep) | |
|
183 | self._append_html(self._make_out_prompt(prompt_number)) | |
|
184 |
self._append_plain_text( |
|
|
182 | data = content['data'] | |
|
183 | if data.has_key('text/html'): | |
|
184 | self._append_plain_text(self.output_sep) | |
|
185 | self._append_html(self._make_out_prompt(prompt_number)) | |
|
186 | html = data['text/html'] | |
|
187 | self._append_plain_text('\n') | |
|
188 | self._append_html(html + self.output_sep2) | |
|
189 | elif data.has_key('text/plain'): | |
|
190 | self._append_plain_text(self.output_sep) | |
|
191 | self._append_html(self._make_out_prompt(prompt_number)) | |
|
192 | text = data['text/plain'] | |
|
193 | self._append_plain_text(text + self.output_sep2) | |
|
185 | 194 | |
|
186 | 195 | def _handle_display_data(self, msg): |
|
187 | 196 | """ The base handler for the ``display_data`` message. |
|
188 | 197 | """ |
|
189 | 198 | # For now, we don't display data from other frontends, but we |
|
190 | 199 | # eventually will as this allows all frontends to monitor the display |
|
191 | 200 | # data. But we need to figure out how to handle this in the GUI. |
|
192 | 201 | if not self._hidden and self._is_from_this_session(msg): |
|
193 | 202 | source = msg['content']['source'] |
|
194 | 203 | data = msg['content']['data'] |
|
195 | 204 | metadata = msg['content']['metadata'] |
|
196 | 205 | # In the regular IPythonWidget, we simply print the plain text |
|
197 | 206 | # representation. |
|
198 |
if data.has_key('text/ |
|
|
199 |
|
|
|
207 | if data.has_key('text/html'): | |
|
208 | html = data['text/html'] | |
|
209 | self._append_html(html) | |
|
210 | elif data.has_key('text/plain'): | |
|
211 | text = data['text/plain'] | |
|
212 | self._append_plain_text(text) | |
|
200 | 213 | |
|
201 | 214 | def _started_channels(self): |
|
202 | 215 | """ Reimplemented to make a history request. |
|
203 | 216 | """ |
|
204 | 217 | super(IPythonWidget, self)._started_channels() |
|
205 | 218 | self.kernel_manager.xreq_channel.history(raw=True, output=False) |
|
206 | 219 | |
|
207 | 220 | #--------------------------------------------------------------------------- |
|
208 | 221 | # 'ConsoleWidget' public interface |
|
209 | 222 | #--------------------------------------------------------------------------- |
|
210 | 223 | |
|
211 | 224 | def copy(self): |
|
212 | 225 | """ Copy the currently selected text to the clipboard, removing prompts |
|
213 | 226 | if possible. |
|
214 | 227 | """ |
|
215 | 228 | text = unicode(self._control.textCursor().selection().toPlainText()) |
|
216 | 229 | if text: |
|
217 | 230 | lines = map(transform_ipy_prompt, text.splitlines()) |
|
218 | 231 | text = '\n'.join(lines) |
|
219 | 232 | QtGui.QApplication.clipboard().setText(text) |
|
220 | 233 | |
|
221 | 234 | #--------------------------------------------------------------------------- |
|
222 | 235 | # 'FrontendWidget' public interface |
|
223 | 236 | #--------------------------------------------------------------------------- |
|
224 | 237 | |
|
225 | 238 | def execute_file(self, path, hidden=False): |
|
226 | 239 | """ Reimplemented to use the 'run' magic. |
|
227 | 240 | """ |
|
228 | 241 | self.execute('%%run %s' % path, hidden=hidden) |
|
229 | 242 | |
|
230 | 243 | #--------------------------------------------------------------------------- |
|
231 | 244 | # 'FrontendWidget' protected interface |
|
232 | 245 | #--------------------------------------------------------------------------- |
|
233 | 246 | |
|
234 | 247 | def _complete(self): |
|
235 | 248 | """ Reimplemented to support IPython's improved completion machinery. |
|
236 | 249 | """ |
|
237 | 250 | # We let the kernel split the input line, so we *always* send an empty |
|
238 | 251 | # text field. Readline-based frontends do get a real text field which |
|
239 | 252 | # they can use. |
|
240 | 253 | text = '' |
|
241 | 254 | |
|
242 | 255 | # Send the completion request to the kernel |
|
243 | 256 | msg_id = self.kernel_manager.xreq_channel.complete( |
|
244 | 257 | text, # text |
|
245 | 258 | self._get_input_buffer_cursor_line(), # line |
|
246 | 259 | self._get_input_buffer_cursor_column(), # cursor_pos |
|
247 | 260 | self.input_buffer) # block |
|
248 | 261 | pos = self._get_cursor().position() |
|
249 | 262 | info = self._CompletionRequest(msg_id, pos) |
|
250 | 263 | self._request_info['complete'] = info |
|
251 | 264 | |
|
252 | 265 | def _get_banner(self): |
|
253 | 266 | """ Reimplemented to return IPython's default banner. |
|
254 | 267 | """ |
|
255 | 268 | return default_gui_banner |
|
256 | 269 | |
|
257 | 270 | def _process_execute_error(self, msg): |
|
258 | 271 | """ Reimplemented for IPython-style traceback formatting. |
|
259 | 272 | """ |
|
260 | 273 | content = msg['content'] |
|
261 | 274 | traceback = '\n'.join(content['traceback']) + '\n' |
|
262 | 275 | if False: |
|
263 | 276 | # FIXME: For now, tracebacks come as plain text, so we can't use |
|
264 | 277 | # the html renderer yet. Once we refactor ultratb to produce |
|
265 | 278 | # properly styled tracebacks, this branch should be the default |
|
266 | 279 | traceback = traceback.replace(' ', ' ') |
|
267 | 280 | traceback = traceback.replace('\n', '<br/>') |
|
268 | 281 | |
|
269 | 282 | ename = content['ename'] |
|
270 | 283 | ename_styled = '<span class="error">%s</span>' % ename |
|
271 | 284 | traceback = traceback.replace(ename, ename_styled) |
|
272 | 285 | |
|
273 | 286 | self._append_html(traceback) |
|
274 | 287 | else: |
|
275 | 288 | # This is the fallback for now, using plain text with ansi escapes |
|
276 | 289 | self._append_plain_text(traceback) |
|
277 | 290 | |
|
278 | 291 | def _process_execute_payload(self, item): |
|
279 | 292 | """ Reimplemented to dispatch payloads to handler methods. |
|
280 | 293 | """ |
|
281 | 294 | handler = self._payload_handlers.get(item['source']) |
|
282 | 295 | if handler is None: |
|
283 | 296 | # We have no handler for this type of payload, simply ignore it |
|
284 | 297 | return False |
|
285 | 298 | else: |
|
286 | 299 | handler(item) |
|
287 | 300 | return True |
|
288 | 301 | |
|
289 | 302 | def _show_interpreter_prompt(self, number=None): |
|
290 | 303 | """ Reimplemented for IPython-style prompts. |
|
291 | 304 | """ |
|
292 | 305 | # If a number was not specified, make a prompt number request. |
|
293 | 306 | if number is None: |
|
294 | 307 | msg_id = self.kernel_manager.xreq_channel.execute('', silent=True) |
|
295 | 308 | info = self._ExecutionRequest(msg_id, 'prompt') |
|
296 | 309 | self._request_info['execute'] = info |
|
297 | 310 | return |
|
298 | 311 | |
|
299 | 312 | # Show a new prompt and save information about it so that it can be |
|
300 | 313 | # updated later if the prompt number turns out to be wrong. |
|
301 | 314 | self._prompt_sep = self.input_sep |
|
302 | 315 | self._show_prompt(self._make_in_prompt(number), html=True) |
|
303 | 316 | block = self._control.document().lastBlock() |
|
304 | 317 | length = len(self._prompt) |
|
305 | 318 | self._previous_prompt_obj = self._PromptBlock(block, length, number) |
|
306 | 319 | |
|
307 | 320 | # Update continuation prompt to reflect (possibly) new prompt length. |
|
308 | 321 | self._set_continuation_prompt( |
|
309 | 322 | self._make_continuation_prompt(self._prompt), html=True) |
|
310 | 323 | |
|
311 | 324 | # Load code from the %loadpy magic, if necessary. |
|
312 | 325 | if self._code_to_load is not None: |
|
313 | 326 | self.input_buffer = dedent(unicode(self._code_to_load).rstrip()) |
|
314 | 327 | self._code_to_load = None |
|
315 | 328 | |
|
316 | 329 | def _show_interpreter_prompt_for_reply(self, msg): |
|
317 | 330 | """ Reimplemented for IPython-style prompts. |
|
318 | 331 | """ |
|
319 | 332 | # Update the old prompt number if necessary. |
|
320 | 333 | content = msg['content'] |
|
321 | 334 | previous_prompt_number = content['execution_count'] |
|
322 | 335 | if self._previous_prompt_obj and \ |
|
323 | 336 | self._previous_prompt_obj.number != previous_prompt_number: |
|
324 | 337 | block = self._previous_prompt_obj.block |
|
325 | 338 | |
|
326 | 339 | # Make sure the prompt block has not been erased. |
|
327 | 340 | if block.isValid() and not block.text().isEmpty(): |
|
328 | 341 | |
|
329 | 342 | # Remove the old prompt and insert a new prompt. |
|
330 | 343 | cursor = QtGui.QTextCursor(block) |
|
331 | 344 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
332 | 345 | QtGui.QTextCursor.KeepAnchor, |
|
333 | 346 | self._previous_prompt_obj.length) |
|
334 | 347 | prompt = self._make_in_prompt(previous_prompt_number) |
|
335 | 348 | self._prompt = self._insert_html_fetching_plain_text( |
|
336 | 349 | cursor, prompt) |
|
337 | 350 | |
|
338 | 351 | # When the HTML is inserted, Qt blows away the syntax |
|
339 | 352 | # highlighting for the line, so we need to rehighlight it. |
|
340 | 353 | self._highlighter.rehighlightBlock(cursor.block()) |
|
341 | 354 | |
|
342 | 355 | self._previous_prompt_obj = None |
|
343 | 356 | |
|
344 | 357 | # Show a new prompt with the kernel's estimated prompt number. |
|
345 | 358 | self._show_interpreter_prompt(previous_prompt_number + 1) |
|
346 | 359 | |
|
347 | 360 | #--------------------------------------------------------------------------- |
|
348 | 361 | # 'IPythonWidget' interface |
|
349 | 362 | #--------------------------------------------------------------------------- |
|
350 | 363 | |
|
351 | 364 | def set_default_style(self, colors='lightbg'): |
|
352 | 365 | """ Sets the widget style to the class defaults. |
|
353 | 366 | |
|
354 | 367 | Parameters: |
|
355 | 368 | ----------- |
|
356 | 369 | colors : str, optional (default lightbg) |
|
357 | 370 | Whether to use the default IPython light background or dark |
|
358 | 371 | background or B&W style. |
|
359 | 372 | """ |
|
360 | 373 | colors = colors.lower() |
|
361 | 374 | if colors=='lightbg': |
|
362 | 375 | self.style_sheet = default_light_style_sheet |
|
363 | 376 | self.syntax_style = default_light_syntax_style |
|
364 | 377 | elif colors=='linux': |
|
365 | 378 | self.style_sheet = default_dark_style_sheet |
|
366 | 379 | self.syntax_style = default_dark_syntax_style |
|
367 | 380 | elif colors=='nocolor': |
|
368 | 381 | self.style_sheet = default_bw_style_sheet |
|
369 | 382 | self.syntax_style = default_bw_syntax_style |
|
370 | 383 | else: |
|
371 | 384 | raise KeyError("No such color scheme: %s"%colors) |
|
372 | 385 | |
|
373 | 386 | #--------------------------------------------------------------------------- |
|
374 | 387 | # 'IPythonWidget' protected interface |
|
375 | 388 | #--------------------------------------------------------------------------- |
|
376 | 389 | |
|
377 | 390 | def _edit(self, filename, line=None): |
|
378 | 391 | """ Opens a Python script for editing. |
|
379 | 392 | |
|
380 | 393 | Parameters: |
|
381 | 394 | ----------- |
|
382 | 395 | filename : str |
|
383 | 396 | A path to a local system file. |
|
384 | 397 | |
|
385 | 398 | line : int, optional |
|
386 | 399 | A line of interest in the file. |
|
387 | 400 | """ |
|
388 | 401 | if self.custom_edit: |
|
389 | 402 | self.custom_edit_requested.emit(filename, line) |
|
390 | 403 | elif self.editor == 'default': |
|
391 | 404 | self._append_plain_text('No default editor available.\n') |
|
392 | 405 | else: |
|
393 | 406 | try: |
|
394 | 407 | filename = '"%s"' % filename |
|
395 | 408 | if line and self.editor_line: |
|
396 | 409 | command = self.editor_line.format(filename=filename, |
|
397 | 410 | line=line) |
|
398 | 411 | else: |
|
399 | 412 | try: |
|
400 | 413 | command = self.editor.format() |
|
401 | 414 | except KeyError: |
|
402 | 415 | command = self.editor.format(filename=filename) |
|
403 | 416 | else: |
|
404 | 417 | command += ' ' + filename |
|
405 | 418 | except KeyError: |
|
406 | 419 | self._append_plain_text('Invalid editor command.\n') |
|
407 | 420 | else: |
|
408 | 421 | try: |
|
409 | 422 | Popen(command, shell=True) |
|
410 | 423 | except OSError: |
|
411 | 424 | msg = 'Opening editor with command "%s" failed.\n' |
|
412 | 425 | self._append_plain_text(msg % command) |
|
413 | 426 | |
|
414 | 427 | def _make_in_prompt(self, number): |
|
415 | 428 | """ Given a prompt number, returns an HTML In prompt. |
|
416 | 429 | """ |
|
417 | 430 | body = self.in_prompt % number |
|
418 | 431 | return '<span class="in-prompt">%s</span>' % body |
|
419 | 432 | |
|
420 | 433 | def _make_continuation_prompt(self, prompt): |
|
421 | 434 | """ Given a plain text version of an In prompt, returns an HTML |
|
422 | 435 | continuation prompt. |
|
423 | 436 | """ |
|
424 | 437 | end_chars = '...: ' |
|
425 | 438 | space_count = len(prompt.lstrip('\n')) - len(end_chars) |
|
426 | 439 | body = ' ' * space_count + end_chars |
|
427 | 440 | return '<span class="in-prompt">%s</span>' % body |
|
428 | 441 | |
|
429 | 442 | def _make_out_prompt(self, number): |
|
430 | 443 | """ Given a prompt number, returns an HTML Out prompt. |
|
431 | 444 | """ |
|
432 | 445 | body = self.out_prompt % number |
|
433 | 446 | return '<span class="out-prompt">%s</span>' % body |
|
434 | 447 | |
|
435 | 448 | #------ Payload handlers -------------------------------------------------- |
|
436 | 449 | |
|
437 | 450 | # Payload handlers with a generic interface: each takes the opaque payload |
|
438 | 451 | # dict, unpacks it and calls the underlying functions with the necessary |
|
439 | 452 | # arguments. |
|
440 | 453 | |
|
441 | 454 | def _handle_payload_edit(self, item): |
|
442 | 455 | self._edit(item['filename'], item['line_number']) |
|
443 | 456 | |
|
444 | 457 | def _handle_payload_exit(self, item): |
|
445 | 458 | self._keep_kernel_on_exit = item['keepkernel'] |
|
446 | 459 | self.exit_requested.emit() |
|
447 | 460 | |
|
448 | 461 | def _handle_payload_loadpy(self, item): |
|
449 | 462 | # Simple save the text of the .py file for later. The text is written |
|
450 | 463 | # to the buffer when _prompt_started_hook is called. |
|
451 | 464 | self._code_to_load = item['text'] |
|
452 | 465 | |
|
453 | 466 | def _handle_payload_page(self, item): |
|
454 | 467 | # Since the plain text widget supports only a very small subset of HTML |
|
455 | 468 | # and we have no control over the HTML source, we only page HTML |
|
456 | 469 | # payloads in the rich text widget. |
|
457 | 470 | if item['html'] and self.kind == 'rich': |
|
458 | 471 | self._page(item['html'], html=True) |
|
459 | 472 | else: |
|
460 | 473 | self._page(item['text'], html=False) |
|
461 | 474 | |
|
462 | 475 | #------ Trait change handlers -------------------------------------------- |
|
463 | 476 | |
|
464 | 477 | def _style_sheet_changed(self): |
|
465 | 478 | """ Set the style sheets of the underlying widgets. |
|
466 | 479 | """ |
|
467 | 480 | self.setStyleSheet(self.style_sheet) |
|
468 | 481 | self._control.document().setDefaultStyleSheet(self.style_sheet) |
|
469 | 482 | if self._page_control: |
|
470 | 483 | self._page_control.document().setDefaultStyleSheet(self.style_sheet) |
|
471 | 484 | |
|
472 | 485 | bg_color = self._control.palette().background().color() |
|
473 | 486 | self._ansi_processor.set_background_color(bg_color) |
|
474 | 487 | |
|
475 | 488 | def _syntax_style_changed(self): |
|
476 | 489 | """ Set the style for the syntax highlighter. |
|
477 | 490 | """ |
|
478 | 491 | if self.syntax_style: |
|
479 | 492 | self._highlighter.set_style(self.syntax_style) |
|
480 | 493 | else: |
|
481 | 494 | self._highlighter.set_style_sheet(self.style_sheet) |
|
482 | 495 |
@@ -1,226 +1,240 b'' | |||
|
1 | 1 | # System library imports |
|
2 | 2 | import os |
|
3 | 3 | import re |
|
4 | 4 | from PyQt4 import QtCore, QtGui |
|
5 | 5 | |
|
6 | 6 | # Local imports |
|
7 | 7 | from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image |
|
8 | 8 | from ipython_widget import IPythonWidget |
|
9 | 9 | |
|
10 | 10 | |
|
11 | 11 | class RichIPythonWidget(IPythonWidget): |
|
12 | 12 | """ An IPythonWidget that supports rich text, including lists, images, and |
|
13 | 13 | tables. Note that raw performance will be reduced compared to the plain |
|
14 | 14 | text version. |
|
15 | 15 | """ |
|
16 | 16 | |
|
17 | 17 | # RichIPythonWidget protected class variables. |
|
18 | 18 | _payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload' |
|
19 | 19 | _svg_text_format_property = 1 |
|
20 | 20 | |
|
21 | 21 | #--------------------------------------------------------------------------- |
|
22 | 22 | # 'object' interface |
|
23 | 23 | #--------------------------------------------------------------------------- |
|
24 | 24 | |
|
25 | 25 | def __init__(self, *args, **kw): |
|
26 | 26 | """ Create a RichIPythonWidget. |
|
27 | 27 | """ |
|
28 | 28 | kw['kind'] = 'rich' |
|
29 | 29 | super(RichIPythonWidget, self).__init__(*args, **kw) |
|
30 | 30 | # Dictionary for resolving Qt names to images when |
|
31 | 31 | # generating XHTML output |
|
32 | 32 | self._name_to_svg = {} |
|
33 | 33 | |
|
34 | 34 | #--------------------------------------------------------------------------- |
|
35 | 35 | # 'ConsoleWidget' protected interface |
|
36 | 36 | #--------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | def _context_menu_make(self, pos): |
|
39 | 39 | """ Reimplemented to return a custom context menu for images. |
|
40 | 40 | """ |
|
41 | 41 | format = self._control.cursorForPosition(pos).charFormat() |
|
42 | 42 | name = format.stringProperty(QtGui.QTextFormat.ImageName) |
|
43 | 43 | if name.isEmpty(): |
|
44 | 44 | menu = super(RichIPythonWidget, self)._context_menu_make(pos) |
|
45 | 45 | else: |
|
46 | 46 | menu = QtGui.QMenu() |
|
47 | 47 | |
|
48 | 48 | menu.addAction('Copy Image', lambda: self._copy_image(name)) |
|
49 | 49 | menu.addAction('Save Image As...', lambda: self._save_image(name)) |
|
50 | 50 | menu.addSeparator() |
|
51 | 51 | |
|
52 | 52 | svg = format.stringProperty(self._svg_text_format_property) |
|
53 | 53 | if not svg.isEmpty(): |
|
54 | 54 | menu.addSeparator() |
|
55 | 55 | menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg)) |
|
56 | 56 | menu.addAction('Save SVG As...', |
|
57 | 57 | lambda: save_svg(svg, self._control)) |
|
58 | 58 | return menu |
|
59 | 59 | |
|
60 | 60 | #--------------------------------------------------------------------------- |
|
61 | 61 | # 'BaseFrontendMixin' abstract interface |
|
62 | 62 | #--------------------------------------------------------------------------- |
|
63 | 63 | |
|
64 | def _handle_pyout(self, msg): | |
|
65 | """ Overridden to handle rich data types, like SVG. | |
|
66 | """ | |
|
67 | if not self._hidden and self._is_from_this_session(msg): | |
|
68 | content = msg['content'] | |
|
69 | prompt_number = content['execution_count'] | |
|
70 | data = content['data'] | |
|
71 | if data.has_key('image/svg+xml'): | |
|
72 | self._append_plain_text(self.output_sep) | |
|
73 | self._append_html(self._make_out_prompt(prompt_number)) | |
|
74 | # TODO: try/except this call. | |
|
75 | self._append_svg(data['image/svg+xml']) | |
|
76 | self._append_html(self.output_sep2) | |
|
77 | else: | |
|
78 | # Default back to the plain text representation. | |
|
79 | return super(RichIPythonWidget, self)._handle_pyout(msg) | |
|
80 | ||
|
64 | 81 | def _handle_display_data(self, msg): |
|
65 | """ A handler for ``display_data`` message that handles html and svg. | |
|
82 | """ Overridden to handle rich data types, like SVG. | |
|
66 | 83 | """ |
|
67 | 84 | if not self._hidden and self._is_from_this_session(msg): |
|
68 | 85 | source = msg['content']['source'] |
|
69 | 86 | data = msg['content']['data'] |
|
70 | 87 | metadata = msg['content']['metadata'] |
|
71 | 88 | # Try to use the svg or html representations. |
|
72 | 89 | # FIXME: Is this the right ordering of things to try? |
|
73 | 90 | if data.has_key('image/svg+xml'): |
|
74 | 91 | svg = data['image/svg+xml'] |
|
75 | 92 | # TODO: try/except this call. |
|
76 | 93 | self._append_svg(svg) |
|
77 | elif data.has_key('text/html'): | |
|
78 | html = data['text/html'] | |
|
79 | self._append_html(html) | |
|
80 | 94 | else: |
|
81 | 95 | # Default back to the plain text representation. |
|
82 | 96 | return super(RichIPythonWidget, self)._handle_display_data(msg) |
|
83 | 97 | |
|
84 | 98 | #--------------------------------------------------------------------------- |
|
85 | 99 | # 'FrontendWidget' protected interface |
|
86 | 100 | #--------------------------------------------------------------------------- |
|
87 | 101 | |
|
88 | 102 | def _process_execute_payload(self, item): |
|
89 | 103 | """ Reimplemented to handle matplotlib plot payloads. |
|
90 | 104 | """ |
|
105 | # TODO: remove this as all plot data is coming back through the | |
|
106 | # display_data message type. | |
|
91 | 107 | if item['source'] == self._payload_source_plot: |
|
92 | # TODO: remove this as all plot data is coming back through the | |
|
93 | # display_data message type. | |
|
94 | 108 | if item['format'] == 'svg': |
|
95 | 109 | svg = item['data'] |
|
96 | 110 | self._append_svg(svg) |
|
97 | 111 | return True |
|
98 | 112 | else: |
|
99 | 113 | # Add other plot formats here! |
|
100 | 114 | return False |
|
101 | 115 | else: |
|
102 | 116 | return super(RichIPythonWidget, self)._process_execute_payload(item) |
|
103 | 117 | |
|
104 | 118 | #--------------------------------------------------------------------------- |
|
105 | 119 | # 'RichIPythonWidget' protected interface |
|
106 | 120 | #--------------------------------------------------------------------------- |
|
107 | 121 | |
|
108 | 122 | def _append_svg(self, svg): |
|
109 | 123 | """ Append raw svg data to the widget. |
|
110 | 124 | """ |
|
111 | 125 | try: |
|
112 | 126 | image = svg_to_image(svg) |
|
113 | 127 | except ValueError: |
|
114 | 128 | self._append_plain_text('Received invalid plot data.') |
|
115 | 129 | else: |
|
116 | 130 | format = self._add_image(image) |
|
117 | 131 | self._name_to_svg[str(format.name())] = svg |
|
118 | 132 | format.setProperty(self._svg_text_format_property, svg) |
|
119 | 133 | cursor = self._get_end_cursor() |
|
120 | 134 | cursor.insertBlock() |
|
121 | 135 | cursor.insertImage(format) |
|
122 | 136 | cursor.insertBlock() |
|
123 | 137 | |
|
124 | 138 | def _add_image(self, image): |
|
125 | 139 | """ Adds the specified QImage to the document and returns a |
|
126 | 140 | QTextImageFormat that references it. |
|
127 | 141 | """ |
|
128 | 142 | document = self._control.document() |
|
129 | 143 | name = QtCore.QString.number(image.cacheKey()) |
|
130 | 144 | document.addResource(QtGui.QTextDocument.ImageResource, |
|
131 | 145 | QtCore.QUrl(name), image) |
|
132 | 146 | format = QtGui.QTextImageFormat() |
|
133 | 147 | format.setName(name) |
|
134 | 148 | return format |
|
135 | 149 | |
|
136 | 150 | def _copy_image(self, name): |
|
137 | 151 | """ Copies the ImageResource with 'name' to the clipboard. |
|
138 | 152 | """ |
|
139 | 153 | image = self._get_image(name) |
|
140 | 154 | QtGui.QApplication.clipboard().setImage(image) |
|
141 | 155 | |
|
142 | 156 | def _get_image(self, name): |
|
143 | 157 | """ Returns the QImage stored as the ImageResource with 'name'. |
|
144 | 158 | """ |
|
145 | 159 | document = self._control.document() |
|
146 | 160 | variant = document.resource(QtGui.QTextDocument.ImageResource, |
|
147 | 161 | QtCore.QUrl(name)) |
|
148 | 162 | return variant.toPyObject() |
|
149 | 163 | |
|
150 | 164 | def _save_image(self, name, format='PNG'): |
|
151 | 165 | """ Shows a save dialog for the ImageResource with 'name'. |
|
152 | 166 | """ |
|
153 | 167 | dialog = QtGui.QFileDialog(self._control, 'Save Image') |
|
154 | 168 | dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) |
|
155 | 169 | dialog.setDefaultSuffix(format.lower()) |
|
156 | 170 | dialog.setNameFilter('%s file (*.%s)' % (format, format.lower())) |
|
157 | 171 | if dialog.exec_(): |
|
158 | 172 | filename = dialog.selectedFiles()[0] |
|
159 | 173 | image = self._get_image(name) |
|
160 | 174 | image.save(filename, format) |
|
161 | 175 | |
|
162 | 176 | def image_tag(self, match, path = None, format = "png"): |
|
163 | 177 | """ Return (X)HTML mark-up for the image-tag given by match. |
|
164 | 178 | |
|
165 | 179 | Parameters |
|
166 | 180 | ---------- |
|
167 | 181 | match : re.SRE_Match |
|
168 | 182 | A match to an HTML image tag as exported by Qt, with |
|
169 | 183 | match.group("Name") containing the matched image ID. |
|
170 | 184 | |
|
171 | 185 | path : string|None, optional [default None] |
|
172 | 186 | If not None, specifies a path to which supporting files |
|
173 | 187 | may be written (e.g., for linked images). |
|
174 | 188 | If None, all images are to be included inline. |
|
175 | 189 | |
|
176 | 190 | format : "png"|"svg", optional [default "png"] |
|
177 | 191 | Format for returned or referenced images. |
|
178 | 192 | |
|
179 | 193 | Subclasses supporting image display should override this |
|
180 | 194 | method. |
|
181 | 195 | """ |
|
182 | 196 | |
|
183 | 197 | if(format == "png"): |
|
184 | 198 | try: |
|
185 | 199 | image = self._get_image(match.group("name")) |
|
186 | 200 | except KeyError: |
|
187 | 201 | return "<b>Couldn't find image %s</b>" % match.group("name") |
|
188 | 202 | |
|
189 | 203 | if(path is not None): |
|
190 | 204 | if not os.path.exists(path): |
|
191 | 205 | os.mkdir(path) |
|
192 | 206 | relpath = os.path.basename(path) |
|
193 | 207 | if(image.save("%s/qt_img%s.png" % (path,match.group("name")), |
|
194 | 208 | "PNG")): |
|
195 | 209 | return '<img src="%s/qt_img%s.png">' % (relpath, |
|
196 | 210 | match.group("name")) |
|
197 | 211 | else: |
|
198 | 212 | return "<b>Couldn't save image!</b>" |
|
199 | 213 | else: |
|
200 | 214 | ba = QtCore.QByteArray() |
|
201 | 215 | buffer_ = QtCore.QBuffer(ba) |
|
202 | 216 | buffer_.open(QtCore.QIODevice.WriteOnly) |
|
203 | 217 | image.save(buffer_, "PNG") |
|
204 | 218 | buffer_.close() |
|
205 | 219 | return '<img src="data:image/png;base64,\n%s\n" />' % ( |
|
206 | 220 | re.sub(r'(.{60})',r'\1\n',str(ba.toBase64()))) |
|
207 | 221 | |
|
208 | 222 | elif(format == "svg"): |
|
209 | 223 | try: |
|
210 | 224 | svg = str(self._name_to_svg[match.group("name")]) |
|
211 | 225 | except KeyError: |
|
212 | 226 | return "<b>Couldn't find image %s</b>" % match.group("name") |
|
213 | 227 | |
|
214 | 228 | # Not currently checking path, because it's tricky to find a |
|
215 | 229 | # cross-browser way to embed external SVG images (e.g., via |
|
216 | 230 | # object or embed tags). |
|
217 | 231 | |
|
218 | 232 | # Chop stand-alone header from matplotlib SVG |
|
219 | 233 | offset = svg.find("<svg") |
|
220 | 234 | assert(offset > -1) |
|
221 | 235 | |
|
222 | 236 | return svg[offset:] |
|
223 | 237 | |
|
224 | 238 | else: |
|
225 | 239 | return '<b>Unrecognized image format</b>' |
|
226 | 240 |
@@ -1,110 +1,110 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | |
|
4 | 4 | """This module contains blocking clients for the controller interfaces. |
|
5 | 5 | |
|
6 | 6 | Unlike the clients in `asyncclient.py`, the clients in this module are fully |
|
7 | 7 | blocking. This means that methods on the clients return the actual results |
|
8 | 8 | rather than a deferred to the result. Also, we manage the Twisted reactor |
|
9 | 9 | for you. This is done by running the reactor in a thread. |
|
10 | 10 | |
|
11 | 11 | The main classes in this module are: |
|
12 | 12 | |
|
13 | 13 | * MultiEngineClient |
|
14 | 14 | * TaskClient |
|
15 | 15 | * Task |
|
16 | 16 | * CompositeError |
|
17 | 17 | """ |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Copyright (C) 2008-2009 The IPython Development Team |
|
21 | 21 | # |
|
22 | 22 | # Distributed under the terms of the BSD License. The full license is in |
|
23 | 23 | # the file COPYING, distributed as part of this software. |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | # Warnings control |
|
28 | 28 | #----------------------------------------------------------------------------- |
|
29 | 29 | |
|
30 | 30 | import warnings |
|
31 | 31 | |
|
32 | 32 | # Twisted generates annoying warnings with Python 2.6, as will do other code |
|
33 | 33 | # that imports 'sets' as of today |
|
34 | 34 | warnings.filterwarnings('ignore', 'the sets module is deprecated', |
|
35 | 35 | DeprecationWarning ) |
|
36 | 36 | |
|
37 | 37 | # This one also comes from Twisted |
|
38 | 38 | warnings.filterwarnings('ignore', 'the sha module is deprecated', |
|
39 | 39 | DeprecationWarning) |
|
40 | 40 | |
|
41 | 41 | #----------------------------------------------------------------------------- |
|
42 | 42 | # Imports |
|
43 | 43 | #----------------------------------------------------------------------------- |
|
44 | 44 | |
|
45 | 45 | import sys |
|
46 | 46 | |
|
47 | 47 | import twisted |
|
48 | 48 | from twisted.internet import reactor |
|
49 | 49 | from twisted.python import log |
|
50 | 50 | |
|
51 | 51 | from IPython.kernel.clientconnector import ClientConnector, Cluster |
|
52 | 52 | from IPython.kernel.twistedutil import ReactorInThread |
|
53 | 53 | from IPython.kernel.twistedutil import blockingCallFromThread |
|
54 | 54 | |
|
55 | 55 | # These enable various things |
|
56 | 56 | from IPython.kernel import codeutil |
|
57 | 57 | |
|
58 | 58 | # Other things that the user will need |
|
59 | 59 | from IPython.kernel.task import MapTask, StringTask |
|
60 | 60 | from IPython.kernel.error import CompositeError |
|
61 | 61 | |
|
62 | 62 | #------------------------------------------------------------------------------- |
|
63 | 63 | # Code |
|
64 | 64 | #------------------------------------------------------------------------------- |
|
65 | 65 | |
|
66 | 66 | # PotentialZombieWarning is deprecated from Twisted 10.0.0 and above and |
|
67 | 67 | # using the filter on > 10.0.0 creates a warning itself. |
|
68 | 68 | if twisted.version.major < 10: |
|
69 | 69 | from twisted.internet.error import PotentialZombieWarning |
|
70 | 70 | warnings.simplefilter('ignore', PotentialZombieWarning) |
|
71 | 71 | |
|
72 | 72 | _client_tub = ClientConnector() |
|
73 | 73 | |
|
74 | 74 | get_multiengine_client = _client_tub.get_multiengine_client |
|
75 | 75 | get_task_client = _client_tub.get_task_client |
|
76 | 76 | MultiEngineClient = get_multiengine_client |
|
77 | 77 | TaskClient = get_task_client |
|
78 | 78 | |
|
79 | 79 | # This isn't great. I should probably set this up in the ReactorInThread |
|
80 | 80 | # class below. But, it does work for now. |
|
81 | 81 | log.startLogging(sys.stdout, setStdout=0) |
|
82 | 82 | |
|
83 | 83 | def _result_list_printer(obj, p, cycle): |
|
84 | 84 | if cycle: |
|
85 | 85 | return p.text('ResultList(...)') |
|
86 | 86 | return p.text(repr(obj)) |
|
87 | 87 | |
|
88 | 88 | # ResultList is a list subclass and will use the default pretty printer. |
|
89 | 89 | # This overrides that to use the __repr__ of ResultList. |
|
90 | 90 | ip = get_ipython() |
|
91 |
ip.display |
|
|
91 | ip.display_formatter.formatters['text/plain'].for_type_by_name( | |
|
92 | 92 | 'IPython.kernel.multiengineclient', 'ResultList', _result_list_printer |
|
93 | 93 | ) |
|
94 | 94 | |
|
95 | 95 | # Now we start the reactor in a thread |
|
96 | 96 | rit = ReactorInThread() |
|
97 | 97 | rit.setDaemon(True) |
|
98 | 98 | rit.start() |
|
99 | 99 | |
|
100 | 100 | |
|
101 | 101 | __all__ = [ |
|
102 | 102 | 'MapTask', |
|
103 | 103 | 'StringTask', |
|
104 | 104 | 'MultiEngineClient', |
|
105 | 105 | 'TaskClient', |
|
106 | 106 | 'CompositeError', |
|
107 | 107 | 'get_task_client', |
|
108 | 108 | 'get_multiengine_client', |
|
109 | 109 | 'Cluster' |
|
110 | 110 | ] |
@@ -1,123 +1,123 b'' | |||
|
1 | 1 | """Produce SVG versions of active plots for display by the rich Qt frontend. |
|
2 | 2 | """ |
|
3 | 3 | #----------------------------------------------------------------------------- |
|
4 | 4 | # Imports |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | from __future__ import print_function |
|
7 | 7 | |
|
8 | 8 | # Standard library imports |
|
9 | 9 | from cStringIO import StringIO |
|
10 | 10 | |
|
11 | 11 | # System library imports. |
|
12 | 12 | import matplotlib |
|
13 | 13 | from matplotlib.backends.backend_svg import new_figure_manager |
|
14 | 14 | from matplotlib._pylab_helpers import Gcf |
|
15 | 15 | |
|
16 | 16 | # Local imports. |
|
17 | 17 | from IPython.core.displaypub import publish_display_data |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Functions |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | def show(close=True): |
|
24 | 24 | """Show all figures as SVG payloads sent to the IPython clients. |
|
25 | 25 | |
|
26 | 26 | Parameters |
|
27 | 27 | ---------- |
|
28 | 28 | close : bool, optional |
|
29 | 29 | If true, a ``plt.close('all')`` call is automatically issued after |
|
30 | 30 | sending all the SVG figures. |
|
31 | 31 | """ |
|
32 | 32 | for figure_manager in Gcf.get_all_fig_managers(): |
|
33 | 33 | send_svg_canvas(figure_manager.canvas) |
|
34 | 34 | if close: |
|
35 | 35 | matplotlib.pyplot.close('all') |
|
36 | 36 | |
|
37 | 37 | # This flag will be reset by draw_if_interactive when called |
|
38 | 38 | show._draw_called = False |
|
39 | 39 | |
|
40 | 40 | |
|
41 | 41 | def figsize(sizex, sizey): |
|
42 | 42 | """Set the default figure size to be [sizex, sizey]. |
|
43 | 43 | |
|
44 | 44 | This is just an easy to remember, convenience wrapper that sets:: |
|
45 | 45 | |
|
46 | 46 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
|
47 | 47 | """ |
|
48 | 48 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
|
49 | 49 | |
|
50 | 50 | |
|
51 | 51 | def pastefig(*figs): |
|
52 | 52 | """Paste one or more figures into the console workspace. |
|
53 | 53 | |
|
54 | 54 | If no arguments are given, all available figures are pasted. If the |
|
55 | 55 | argument list contains references to invalid figures, a warning is printed |
|
56 | 56 | but the function continues pasting further figures. |
|
57 | 57 | |
|
58 | 58 | Parameters |
|
59 | 59 | ---------- |
|
60 | 60 | figs : tuple |
|
61 | 61 | A tuple that can contain any mixture of integers and figure objects. |
|
62 | 62 | """ |
|
63 | 63 | if not figs: |
|
64 | 64 | show(close=False) |
|
65 | 65 | else: |
|
66 | 66 | fig_managers = Gcf.get_all_fig_managers() |
|
67 | 67 | fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers] |
|
68 | 68 | + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] ) |
|
69 | 69 | |
|
70 | 70 | for fig in figs: |
|
71 | 71 | canvas = fig_index.get(fig) |
|
72 | 72 | if canvas is None: |
|
73 | 73 | print('Warning: figure %s not available.' % fig) |
|
74 | 74 | else: |
|
75 | 75 | send_svg_canvas(canvas) |
|
76 | 76 | |
|
77 | 77 | |
|
78 | 78 | def send_svg_canvas(canvas): |
|
79 | 79 | """Draw the current canvas and send it as an SVG payload. |
|
80 | 80 | """ |
|
81 | 81 | # Set the background to white instead so it looks good on black. We store |
|
82 | 82 | # the current values to restore them at the end. |
|
83 | 83 | fc = canvas.figure.get_facecolor() |
|
84 | 84 | ec = canvas.figure.get_edgecolor() |
|
85 | 85 | canvas.figure.set_facecolor('white') |
|
86 | 86 | canvas.figure.set_edgecolor('white') |
|
87 | 87 | try: |
|
88 | 88 | publish_display_data( |
|
89 | 89 | 'IPython.zmq.pylab.backend_inline.send_svg_canvas', |
|
90 |
' |
|
|
91 |
|
|
|
90 | 'Matplotlib Plot', | |
|
91 | {'image/svg+xml' : svg_from_canvas(canvas)} | |
|
92 | 92 | ) |
|
93 | 93 | finally: |
|
94 | 94 | canvas.figure.set_facecolor(fc) |
|
95 | 95 | canvas.figure.set_edgecolor(ec) |
|
96 | 96 | |
|
97 | 97 | |
|
98 | 98 | def svg_from_canvas(canvas): |
|
99 | 99 | """ Return a string containing the SVG representation of a FigureCanvasSvg. |
|
100 | 100 | """ |
|
101 | 101 | string_io = StringIO() |
|
102 | 102 | canvas.print_figure(string_io, format='svg') |
|
103 | 103 | return string_io.getvalue() |
|
104 | 104 | |
|
105 | 105 | |
|
106 | 106 | def draw_if_interactive(): |
|
107 | 107 | """ |
|
108 | 108 | Is called after every pylab drawing command |
|
109 | 109 | """ |
|
110 | 110 | # We simply flag we were called and otherwise do nothing. At the end of |
|
111 | 111 | # the code execution, a separate call to show_close() will act upon this. |
|
112 | 112 | show._draw_called = True |
|
113 | 113 | |
|
114 | 114 | |
|
115 | 115 | def flush_svg(): |
|
116 | 116 | """Call show, close all open figures, sending all SVG images. |
|
117 | 117 | |
|
118 | 118 | This is meant to be called automatically and will call show() if, during |
|
119 | 119 | prior code execution, there had been any calls to draw_if_interactive. |
|
120 | 120 | """ |
|
121 | 121 | if show._draw_called: |
|
122 | 122 | show(close=True) |
|
123 | 123 | show._draw_called = False |
@@ -1,605 +1,605 b'' | |||
|
1 | 1 | """A ZMQ-based subclass of InteractiveShell. |
|
2 | 2 | |
|
3 | 3 | This code is meant to ease the refactoring of the base InteractiveShell into |
|
4 | 4 | something with a cleaner architecture for 2-process use, without actually |
|
5 | 5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where |
|
6 | 6 | we subclass and override what we want to fix. Once this is working well, we |
|
7 | 7 | can go back to the base class and refactor the code for a cleaner inheritance |
|
8 | 8 | implementation that doesn't rely on so much monkeypatching. |
|
9 | 9 | |
|
10 | 10 | But this lets us maintain a fully working IPython as we develop the new |
|
11 | 11 | machinery. This should thus be thought of as scaffolding. |
|
12 | 12 | """ |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | from __future__ import print_function |
|
17 | 17 | |
|
18 | 18 | # Stdlib |
|
19 | 19 | import inspect |
|
20 | 20 | import os |
|
21 | 21 | import re |
|
22 | 22 | |
|
23 | 23 | # Our own |
|
24 | 24 | from IPython.core.interactiveshell import ( |
|
25 | 25 | InteractiveShell, InteractiveShellABC |
|
26 | 26 | ) |
|
27 | 27 | from IPython.core import page |
|
28 | 28 | from IPython.core.displayhook import DisplayHook |
|
29 | 29 | from IPython.core.displaypub import DisplayPublisher |
|
30 | 30 | from IPython.core.macro import Macro |
|
31 | 31 | from IPython.core.payloadpage import install_payload_page |
|
32 | 32 | from IPython.utils import io |
|
33 | 33 | from IPython.utils.path import get_py_filename |
|
34 | 34 | from IPython.utils.text import StringTypes |
|
35 | 35 | from IPython.utils.traitlets import Instance, Type, Dict |
|
36 | 36 | from IPython.utils.warn import warn |
|
37 | 37 | from IPython.zmq.session import extract_header |
|
38 | 38 | from session import Session |
|
39 | 39 | |
|
40 | 40 | #----------------------------------------------------------------------------- |
|
41 | 41 | # Globals and side-effects |
|
42 | 42 | #----------------------------------------------------------------------------- |
|
43 | 43 | |
|
44 | 44 | # Install the payload version of page. |
|
45 | 45 | install_payload_page() |
|
46 | 46 | |
|
47 | 47 | #----------------------------------------------------------------------------- |
|
48 | 48 | # Functions and classes |
|
49 | 49 | #----------------------------------------------------------------------------- |
|
50 | 50 | |
|
51 | 51 | class ZMQDisplayHook(DisplayHook): |
|
52 | """A displayhook subclass that publishes data using ZeroMQ.""" | |
|
52 | 53 | |
|
53 | 54 | session = Instance(Session) |
|
54 | 55 | pub_socket = Instance('zmq.Socket') |
|
55 | 56 | parent_header = Dict({}) |
|
56 | 57 | |
|
57 | 58 | def set_parent(self, parent): |
|
58 | 59 | """Set the parent for outbound messages.""" |
|
59 | 60 | self.parent_header = extract_header(parent) |
|
60 | 61 | |
|
61 | 62 | def start_displayhook(self): |
|
62 | 63 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) |
|
63 | 64 | |
|
64 | 65 | def write_output_prompt(self): |
|
65 | 66 | """Write the output prompt.""" |
|
66 | 67 | if self.do_full_cache: |
|
67 | 68 | self.msg['content']['execution_count'] = self.prompt_count |
|
68 | 69 | |
|
69 |
def write_ |
|
|
70 |
self.msg['content']['data'] = |
|
|
71 | self.msg['content']['extra_formats'] = extra_formats | |
|
70 | def write_format_data(self, format_dict): | |
|
71 | self.msg['content']['data'] = format_dict | |
|
72 | 72 | |
|
73 | 73 | def finish_displayhook(self): |
|
74 | 74 | """Finish up all displayhook activities.""" |
|
75 | 75 | self.session.send(self.pub_socket, self.msg) |
|
76 | 76 | self.msg = None |
|
77 | 77 | |
|
78 | 78 | |
|
79 | 79 | class ZMQDisplayPublisher(DisplayPublisher): |
|
80 |
"""A |
|
|
80 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" | |
|
81 | 81 | |
|
82 | 82 | session = Instance(Session) |
|
83 | 83 | pub_socket = Instance('zmq.Socket') |
|
84 | 84 | parent_header = Dict({}) |
|
85 | 85 | |
|
86 | 86 | def set_parent(self, parent): |
|
87 | 87 | """Set the parent for outbound messages.""" |
|
88 | 88 | self.parent_header = extract_header(parent) |
|
89 | 89 | |
|
90 | 90 | def publish(self, source, data, metadata=None): |
|
91 | 91 | if metadata is None: |
|
92 | 92 | metadata = {} |
|
93 | 93 | self._validate_data(source, data, metadata) |
|
94 | 94 | msg = self.session.msg(u'display_data', {}, parent=self.parent_header) |
|
95 | 95 | msg['content']['source'] = source |
|
96 | 96 | msg['content']['data'] = data |
|
97 | 97 | msg['content']['metadata'] = metadata |
|
98 | 98 | self.pub_socket.send_json(msg) |
|
99 | 99 | |
|
100 | 100 | |
|
101 | 101 | class ZMQInteractiveShell(InteractiveShell): |
|
102 | 102 | """A subclass of InteractiveShell for ZMQ.""" |
|
103 | 103 | |
|
104 | 104 | displayhook_class = Type(ZMQDisplayHook) |
|
105 | 105 | display_pub_class = Type(ZMQDisplayPublisher) |
|
106 | 106 | |
|
107 | 107 | keepkernel_on_exit = None |
|
108 | 108 | |
|
109 | 109 | def init_environment(self): |
|
110 | 110 | """Configure the user's environment. |
|
111 | 111 | |
|
112 | 112 | """ |
|
113 | 113 | env = os.environ |
|
114 | 114 | # These two ensure 'ls' produces nice coloring on BSD-derived systems |
|
115 | 115 | env['TERM'] = 'xterm-color' |
|
116 | 116 | env['CLICOLOR'] = '1' |
|
117 | 117 | # Since normal pagers don't work at all (over pexpect we don't have |
|
118 | 118 | # single-key control of the subprocess), try to disable paging in |
|
119 | 119 | # subprocesses as much as possible. |
|
120 | 120 | env['PAGER'] = 'cat' |
|
121 | 121 | env['GIT_PAGER'] = 'cat' |
|
122 | 122 | |
|
123 | 123 | def auto_rewrite_input(self, cmd): |
|
124 | 124 | """Called to show the auto-rewritten input for autocall and friends. |
|
125 | 125 | |
|
126 | 126 | FIXME: this payload is currently not correctly processed by the |
|
127 | 127 | frontend. |
|
128 | 128 | """ |
|
129 | 129 | new = self.displayhook.prompt1.auto_rewrite() + cmd |
|
130 | 130 | payload = dict( |
|
131 | 131 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', |
|
132 | 132 | transformed_input=new, |
|
133 | 133 | ) |
|
134 | 134 | self.payload_manager.write_payload(payload) |
|
135 | 135 | |
|
136 | 136 | def ask_exit(self): |
|
137 | 137 | """Engage the exit actions.""" |
|
138 | 138 | payload = dict( |
|
139 | 139 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', |
|
140 | 140 | exit=True, |
|
141 | 141 | keepkernel=self.keepkernel_on_exit, |
|
142 | 142 | ) |
|
143 | 143 | self.payload_manager.write_payload(payload) |
|
144 | 144 | |
|
145 | 145 | def _showtraceback(self, etype, evalue, stb): |
|
146 | 146 | |
|
147 | 147 | exc_content = { |
|
148 | 148 | u'traceback' : stb, |
|
149 | 149 | u'ename' : unicode(etype.__name__), |
|
150 | 150 | u'evalue' : unicode(evalue) |
|
151 | 151 | } |
|
152 | 152 | |
|
153 | 153 | dh = self.displayhook |
|
154 | 154 | # Send exception info over pub socket for other clients than the caller |
|
155 | 155 | # to pick up |
|
156 | 156 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header) |
|
157 | 157 | |
|
158 | 158 | # FIXME - Hack: store exception info in shell object. Right now, the |
|
159 | 159 | # caller is reading this info after the fact, we need to fix this logic |
|
160 | 160 | # to remove this hack. Even uglier, we need to store the error status |
|
161 | 161 | # here, because in the main loop, the logic that sets it is being |
|
162 | 162 | # skipped because runlines swallows the exceptions. |
|
163 | 163 | exc_content[u'status'] = u'error' |
|
164 | 164 | self._reply_content = exc_content |
|
165 | 165 | # /FIXME |
|
166 | 166 | |
|
167 | 167 | return exc_content |
|
168 | 168 | |
|
169 | 169 | #------------------------------------------------------------------------ |
|
170 | 170 | # Magic overrides |
|
171 | 171 | #------------------------------------------------------------------------ |
|
172 | 172 | # Once the base class stops inheriting from magic, this code needs to be |
|
173 | 173 | # moved into a separate machinery as well. For now, at least isolate here |
|
174 | 174 | # the magics which this class needs to implement differently from the base |
|
175 | 175 | # class, or that are unique to it. |
|
176 | 176 | |
|
177 | 177 | def magic_doctest_mode(self,parameter_s=''): |
|
178 | 178 | """Toggle doctest mode on and off. |
|
179 | 179 | |
|
180 | 180 | This mode is intended to make IPython behave as much as possible like a |
|
181 | 181 | plain Python shell, from the perspective of how its prompts, exceptions |
|
182 | 182 | and output look. This makes it easy to copy and paste parts of a |
|
183 | 183 | session into doctests. It does so by: |
|
184 | 184 | |
|
185 | 185 | - Changing the prompts to the classic ``>>>`` ones. |
|
186 | 186 | - Changing the exception reporting mode to 'Plain'. |
|
187 | 187 | - Disabling pretty-printing of output. |
|
188 | 188 | |
|
189 | 189 | Note that IPython also supports the pasting of code snippets that have |
|
190 | 190 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
191 | 191 | doctests from files or docstrings (even if they have leading |
|
192 | 192 | whitespace), and the code will execute correctly. You can then use |
|
193 | 193 | '%history -t' to see the translated history; this will give you the |
|
194 | 194 | input after removal of all the leading prompts and whitespace, which |
|
195 | 195 | can be pasted back into an editor. |
|
196 | 196 | |
|
197 | 197 | With these features, you can switch into this mode easily whenever you |
|
198 | 198 | need to do testing and changes to doctests, without having to leave |
|
199 | 199 | your existing IPython session. |
|
200 | 200 | """ |
|
201 | 201 | |
|
202 | 202 | from IPython.utils.ipstruct import Struct |
|
203 | 203 | |
|
204 | 204 | # Shorthands |
|
205 | 205 | shell = self.shell |
|
206 | 206 | # dstore is a data store kept in the instance metadata bag to track any |
|
207 | 207 | # changes we make, so we can undo them later. |
|
208 | 208 | dstore = shell.meta.setdefault('doctest_mode', Struct()) |
|
209 | 209 | save_dstore = dstore.setdefault |
|
210 | 210 | |
|
211 | 211 | # save a few values we'll need to recover later |
|
212 | 212 | mode = save_dstore('mode', False) |
|
213 | 213 | save_dstore('rc_pprint', shell.pprint) |
|
214 | 214 | save_dstore('xmode', shell.InteractiveTB.mode) |
|
215 | 215 | |
|
216 | 216 | if mode == False: |
|
217 | 217 | # turn on |
|
218 | 218 | shell.pprint = False |
|
219 | 219 | shell.magic_xmode('Plain') |
|
220 | 220 | else: |
|
221 | 221 | # turn off |
|
222 | 222 | shell.pprint = dstore.rc_pprint |
|
223 | 223 | shell.magic_xmode(dstore.xmode) |
|
224 | 224 | |
|
225 | 225 | # Store new mode and inform on console |
|
226 | 226 | dstore.mode = bool(1-int(mode)) |
|
227 | 227 | mode_label = ['OFF','ON'][dstore.mode] |
|
228 | 228 | print('Doctest mode is:', mode_label) |
|
229 | 229 | |
|
230 | 230 | # Send the payload back so that clients can modify their prompt display |
|
231 | 231 | payload = dict( |
|
232 | 232 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', |
|
233 | 233 | mode=dstore.mode) |
|
234 | 234 | self.payload_manager.write_payload(payload) |
|
235 | 235 | |
|
236 | 236 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
237 | 237 | """Bring up an editor and execute the resulting code. |
|
238 | 238 | |
|
239 | 239 | Usage: |
|
240 | 240 | %edit [options] [args] |
|
241 | 241 | |
|
242 | 242 | %edit runs IPython's editor hook. The default version of this hook is |
|
243 | 243 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
244 | 244 | environment variable $EDITOR. If this isn't found, it will default to |
|
245 | 245 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
246 | 246 | docstring for how to change the editor hook. |
|
247 | 247 | |
|
248 | 248 | You can also set the value of this editor via the command line option |
|
249 | 249 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
250 | 250 | specifically for IPython an editor different from your typical default |
|
251 | 251 | (and for Windows users who typically don't set environment variables). |
|
252 | 252 | |
|
253 | 253 | This command allows you to conveniently edit multi-line code right in |
|
254 | 254 | your IPython session. |
|
255 | 255 | |
|
256 | 256 | If called without arguments, %edit opens up an empty editor with a |
|
257 | 257 | temporary file and will execute the contents of this file when you |
|
258 | 258 | close it (don't forget to save it!). |
|
259 | 259 | |
|
260 | 260 | |
|
261 | 261 | Options: |
|
262 | 262 | |
|
263 | 263 | -n <number>: open the editor at a specified line number. By default, |
|
264 | 264 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
265 | 265 | you can configure this by providing your own modified hook if your |
|
266 | 266 | favorite editor supports line-number specifications with a different |
|
267 | 267 | syntax. |
|
268 | 268 | |
|
269 | 269 | -p: this will call the editor with the same data as the previous time |
|
270 | 270 | it was used, regardless of how long ago (in your current session) it |
|
271 | 271 | was. |
|
272 | 272 | |
|
273 | 273 | -r: use 'raw' input. This option only applies to input taken from the |
|
274 | 274 | user's history. By default, the 'processed' history is used, so that |
|
275 | 275 | magics are loaded in their transformed version to valid Python. If |
|
276 | 276 | this option is given, the raw input as typed as the command line is |
|
277 | 277 | used instead. When you exit the editor, it will be executed by |
|
278 | 278 | IPython's own processor. |
|
279 | 279 | |
|
280 | 280 | -x: do not execute the edited code immediately upon exit. This is |
|
281 | 281 | mainly useful if you are editing programs which need to be called with |
|
282 | 282 | command line arguments, which you can then do using %run. |
|
283 | 283 | |
|
284 | 284 | |
|
285 | 285 | Arguments: |
|
286 | 286 | |
|
287 | 287 | If arguments are given, the following possibilites exist: |
|
288 | 288 | |
|
289 | 289 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
290 | 290 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
291 | 291 | loaded into the editor. The syntax is the same of the %macro command. |
|
292 | 292 | |
|
293 | 293 | - If the argument doesn't start with a number, it is evaluated as a |
|
294 | 294 | variable and its contents loaded into the editor. You can thus edit |
|
295 | 295 | any string which contains python code (including the result of |
|
296 | 296 | previous edits). |
|
297 | 297 | |
|
298 | 298 | - If the argument is the name of an object (other than a string), |
|
299 | 299 | IPython will try to locate the file where it was defined and open the |
|
300 | 300 | editor at the point where it is defined. You can use `%edit function` |
|
301 | 301 | to load an editor exactly at the point where 'function' is defined, |
|
302 | 302 | edit it and have the file be executed automatically. |
|
303 | 303 | |
|
304 | 304 | If the object is a macro (see %macro for details), this opens up your |
|
305 | 305 | specified editor with a temporary file containing the macro's data. |
|
306 | 306 | Upon exit, the macro is reloaded with the contents of the file. |
|
307 | 307 | |
|
308 | 308 | Note: opening at an exact line is only supported under Unix, and some |
|
309 | 309 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
310 | 310 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
311 | 311 | (X)Emacs, vi, jed, pico and joe all do. |
|
312 | 312 | |
|
313 | 313 | - If the argument is not found as a variable, IPython will look for a |
|
314 | 314 | file with that name (adding .py if necessary) and load it into the |
|
315 | 315 | editor. It will execute its contents with execfile() when you exit, |
|
316 | 316 | loading any code in the file into your interactive namespace. |
|
317 | 317 | |
|
318 | 318 | After executing your code, %edit will return as output the code you |
|
319 | 319 | typed in the editor (except when it was an existing file). This way |
|
320 | 320 | you can reload the code in further invocations of %edit as a variable, |
|
321 | 321 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
322 | 322 | the output. |
|
323 | 323 | |
|
324 | 324 | Note that %edit is also available through the alias %ed. |
|
325 | 325 | |
|
326 | 326 | This is an example of creating a simple function inside the editor and |
|
327 | 327 | then modifying it. First, start up the editor: |
|
328 | 328 | |
|
329 | 329 | In [1]: ed |
|
330 | 330 | Editing... done. Executing edited code... |
|
331 | 331 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
332 | 332 | |
|
333 | 333 | We can then call the function foo(): |
|
334 | 334 | |
|
335 | 335 | In [2]: foo() |
|
336 | 336 | foo() was defined in an editing session |
|
337 | 337 | |
|
338 | 338 | Now we edit foo. IPython automatically loads the editor with the |
|
339 | 339 | (temporary) file where foo() was previously defined: |
|
340 | 340 | |
|
341 | 341 | In [3]: ed foo |
|
342 | 342 | Editing... done. Executing edited code... |
|
343 | 343 | |
|
344 | 344 | And if we call foo() again we get the modified version: |
|
345 | 345 | |
|
346 | 346 | In [4]: foo() |
|
347 | 347 | foo() has now been changed! |
|
348 | 348 | |
|
349 | 349 | Here is an example of how to edit a code snippet successive |
|
350 | 350 | times. First we call the editor: |
|
351 | 351 | |
|
352 | 352 | In [5]: ed |
|
353 | 353 | Editing... done. Executing edited code... |
|
354 | 354 | hello |
|
355 | 355 | Out[5]: "print 'hello'n" |
|
356 | 356 | |
|
357 | 357 | Now we call it again with the previous output (stored in _): |
|
358 | 358 | |
|
359 | 359 | In [6]: ed _ |
|
360 | 360 | Editing... done. Executing edited code... |
|
361 | 361 | hello world |
|
362 | 362 | Out[6]: "print 'hello world'n" |
|
363 | 363 | |
|
364 | 364 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
365 | 365 | |
|
366 | 366 | In [7]: ed _8 |
|
367 | 367 | Editing... done. Executing edited code... |
|
368 | 368 | hello again |
|
369 | 369 | Out[7]: "print 'hello again'n" |
|
370 | 370 | |
|
371 | 371 | |
|
372 | 372 | Changing the default editor hook: |
|
373 | 373 | |
|
374 | 374 | If you wish to write your own editor hook, you can put it in a |
|
375 | 375 | configuration file which you load at startup time. The default hook |
|
376 | 376 | is defined in the IPython.core.hooks module, and you can use that as a |
|
377 | 377 | starting example for further modifications. That file also has |
|
378 | 378 | general instructions on how to set a new hook for use once you've |
|
379 | 379 | defined it.""" |
|
380 | 380 | |
|
381 | 381 | # FIXME: This function has become a convoluted mess. It needs a |
|
382 | 382 | # ground-up rewrite with clean, simple logic. |
|
383 | 383 | |
|
384 | 384 | def make_filename(arg): |
|
385 | 385 | "Make a filename from the given args" |
|
386 | 386 | try: |
|
387 | 387 | filename = get_py_filename(arg) |
|
388 | 388 | except IOError: |
|
389 | 389 | if args.endswith('.py'): |
|
390 | 390 | filename = arg |
|
391 | 391 | else: |
|
392 | 392 | filename = None |
|
393 | 393 | return filename |
|
394 | 394 | |
|
395 | 395 | # custom exceptions |
|
396 | 396 | class DataIsObject(Exception): pass |
|
397 | 397 | |
|
398 | 398 | opts,args = self.parse_options(parameter_s,'prn:') |
|
399 | 399 | # Set a few locals from the options for convenience: |
|
400 | 400 | opts_p = opts.has_key('p') |
|
401 | 401 | opts_r = opts.has_key('r') |
|
402 | 402 | |
|
403 | 403 | # Default line number value |
|
404 | 404 | lineno = opts.get('n',None) |
|
405 | 405 | if lineno is not None: |
|
406 | 406 | try: |
|
407 | 407 | lineno = int(lineno) |
|
408 | 408 | except: |
|
409 | 409 | warn("The -n argument must be an integer.") |
|
410 | 410 | return |
|
411 | 411 | |
|
412 | 412 | if opts_p: |
|
413 | 413 | args = '_%s' % last_call[0] |
|
414 | 414 | if not self.shell.user_ns.has_key(args): |
|
415 | 415 | args = last_call[1] |
|
416 | 416 | |
|
417 | 417 | # use last_call to remember the state of the previous call, but don't |
|
418 | 418 | # let it be clobbered by successive '-p' calls. |
|
419 | 419 | try: |
|
420 | 420 | last_call[0] = self.shell.displayhook.prompt_count |
|
421 | 421 | if not opts_p: |
|
422 | 422 | last_call[1] = parameter_s |
|
423 | 423 | except: |
|
424 | 424 | pass |
|
425 | 425 | |
|
426 | 426 | # by default this is done with temp files, except when the given |
|
427 | 427 | # arg is a filename |
|
428 | 428 | use_temp = 1 |
|
429 | 429 | |
|
430 | 430 | if re.match(r'\d',args): |
|
431 | 431 | # Mode where user specifies ranges of lines, like in %macro. |
|
432 | 432 | # This means that you can't edit files whose names begin with |
|
433 | 433 | # numbers this way. Tough. |
|
434 | 434 | ranges = args.split() |
|
435 | 435 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
436 | 436 | elif args.endswith('.py'): |
|
437 | 437 | filename = make_filename(args) |
|
438 | 438 | data = '' |
|
439 | 439 | use_temp = 0 |
|
440 | 440 | elif args: |
|
441 | 441 | try: |
|
442 | 442 | # Load the parameter given as a variable. If not a string, |
|
443 | 443 | # process it as an object instead (below) |
|
444 | 444 | |
|
445 | 445 | #print '*** args',args,'type',type(args) # dbg |
|
446 | 446 | data = eval(args,self.shell.user_ns) |
|
447 | 447 | if not type(data) in StringTypes: |
|
448 | 448 | raise DataIsObject |
|
449 | 449 | |
|
450 | 450 | except (NameError,SyntaxError): |
|
451 | 451 | # given argument is not a variable, try as a filename |
|
452 | 452 | filename = make_filename(args) |
|
453 | 453 | if filename is None: |
|
454 | 454 | warn("Argument given (%s) can't be found as a variable " |
|
455 | 455 | "or as a filename." % args) |
|
456 | 456 | return |
|
457 | 457 | |
|
458 | 458 | data = '' |
|
459 | 459 | use_temp = 0 |
|
460 | 460 | except DataIsObject: |
|
461 | 461 | |
|
462 | 462 | # macros have a special edit function |
|
463 | 463 | if isinstance(data,Macro): |
|
464 | 464 | self._edit_macro(args,data) |
|
465 | 465 | return |
|
466 | 466 | |
|
467 | 467 | # For objects, try to edit the file where they are defined |
|
468 | 468 | try: |
|
469 | 469 | filename = inspect.getabsfile(data) |
|
470 | 470 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
471 | 471 | # class created by %edit? Try to find source |
|
472 | 472 | # by looking for method definitions instead, the |
|
473 | 473 | # __module__ in those classes is FakeModule. |
|
474 | 474 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
475 | 475 | for attr in attrs: |
|
476 | 476 | if not inspect.ismethod(attr): |
|
477 | 477 | continue |
|
478 | 478 | filename = inspect.getabsfile(attr) |
|
479 | 479 | if filename and 'fakemodule' not in filename.lower(): |
|
480 | 480 | # change the attribute to be the edit target instead |
|
481 | 481 | data = attr |
|
482 | 482 | break |
|
483 | 483 | |
|
484 | 484 | datafile = 1 |
|
485 | 485 | except TypeError: |
|
486 | 486 | filename = make_filename(args) |
|
487 | 487 | datafile = 1 |
|
488 | 488 | warn('Could not find file where `%s` is defined.\n' |
|
489 | 489 | 'Opening a file named `%s`' % (args,filename)) |
|
490 | 490 | # Now, make sure we can actually read the source (if it was in |
|
491 | 491 | # a temp file it's gone by now). |
|
492 | 492 | if datafile: |
|
493 | 493 | try: |
|
494 | 494 | if lineno is None: |
|
495 | 495 | lineno = inspect.getsourcelines(data)[1] |
|
496 | 496 | except IOError: |
|
497 | 497 | filename = make_filename(args) |
|
498 | 498 | if filename is None: |
|
499 | 499 | warn('The file `%s` where `%s` was defined cannot ' |
|
500 | 500 | 'be read.' % (filename,data)) |
|
501 | 501 | return |
|
502 | 502 | use_temp = 0 |
|
503 | 503 | else: |
|
504 | 504 | data = '' |
|
505 | 505 | |
|
506 | 506 | if use_temp: |
|
507 | 507 | filename = self.shell.mktempfile(data) |
|
508 | 508 | print('IPython will make a temporary file named:', filename) |
|
509 | 509 | |
|
510 | 510 | # Make sure we send to the client an absolute path, in case the working |
|
511 | 511 | # directory of client and kernel don't match |
|
512 | 512 | filename = os.path.abspath(filename) |
|
513 | 513 | |
|
514 | 514 | payload = { |
|
515 | 515 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
516 | 516 | 'filename' : filename, |
|
517 | 517 | 'line_number' : lineno |
|
518 | 518 | } |
|
519 | 519 | self.payload_manager.write_payload(payload) |
|
520 | 520 | |
|
521 | 521 | def magic_gui(self, *args, **kwargs): |
|
522 | 522 | raise NotImplementedError( |
|
523 | 523 | 'GUI support must be enabled in command line options.') |
|
524 | 524 | |
|
525 | 525 | def magic_pylab(self, *args, **kwargs): |
|
526 | 526 | raise NotImplementedError( |
|
527 | 527 | 'pylab support must be enabled in command line options.') |
|
528 | 528 | |
|
529 | 529 | # A few magics that are adapted to the specifics of using pexpect and a |
|
530 | 530 | # remote terminal |
|
531 | 531 | |
|
532 | 532 | def magic_clear(self, arg_s): |
|
533 | 533 | """Clear the terminal.""" |
|
534 | 534 | if os.name == 'posix': |
|
535 | 535 | self.shell.system("clear") |
|
536 | 536 | else: |
|
537 | 537 | self.shell.system("cls") |
|
538 | 538 | |
|
539 | 539 | if os.name == 'nt': |
|
540 | 540 | # This is the usual name in windows |
|
541 | 541 | magic_cls = magic_clear |
|
542 | 542 | |
|
543 | 543 | # Terminal pagers won't work over pexpect, but we do have our own pager |
|
544 | 544 | |
|
545 | 545 | def magic_less(self, arg_s): |
|
546 | 546 | """Show a file through the pager. |
|
547 | 547 | |
|
548 | 548 | Files ending in .py are syntax-highlighted.""" |
|
549 | 549 | cont = open(arg_s).read() |
|
550 | 550 | if arg_s.endswith('.py'): |
|
551 | 551 | cont = self.shell.pycolorize(cont) |
|
552 | 552 | page.page(cont) |
|
553 | 553 | |
|
554 | 554 | magic_more = magic_less |
|
555 | 555 | |
|
556 | 556 | # Man calls a pager, so we also need to redefine it |
|
557 | 557 | if os.name == 'posix': |
|
558 | 558 | def magic_man(self, arg_s): |
|
559 | 559 | """Find the man page for the given command and display in pager.""" |
|
560 | 560 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, |
|
561 | 561 | split=False)) |
|
562 | 562 | |
|
563 | 563 | # FIXME: this is specific to the GUI, so we should let the gui app load |
|
564 | 564 | # magics at startup that are only for the gui. Once the gui app has proper |
|
565 | 565 | # profile and configuration management, we can have it initialize a kernel |
|
566 | 566 | # with a special config file that provides these. |
|
567 | 567 | def magic_guiref(self, arg_s): |
|
568 | 568 | """Show a basic reference about the GUI console.""" |
|
569 | 569 | from IPython.core.usage import gui_reference |
|
570 | 570 | page.page(gui_reference, auto_html=True) |
|
571 | 571 | |
|
572 | 572 | def magic_loadpy(self, arg_s): |
|
573 | 573 | """Load a .py python script into the GUI console. |
|
574 | 574 | |
|
575 | 575 | This magic command can either take a local filename or a url:: |
|
576 | 576 | |
|
577 | 577 | %loadpy myscript.py |
|
578 | 578 | %loadpy http://www.example.com/myscript.py |
|
579 | 579 | """ |
|
580 | 580 | if not arg_s.endswith('.py'): |
|
581 | 581 | raise ValueError('%%load only works with .py files: %s' % arg_s) |
|
582 | 582 | if arg_s.startswith('http'): |
|
583 | 583 | import urllib2 |
|
584 | 584 | response = urllib2.urlopen(arg_s) |
|
585 | 585 | content = response.read() |
|
586 | 586 | else: |
|
587 | 587 | content = open(arg_s).read() |
|
588 | 588 | payload = dict( |
|
589 | 589 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy', |
|
590 | 590 | text=content |
|
591 | 591 | ) |
|
592 | 592 | self.payload_manager.write_payload(payload) |
|
593 | 593 | |
|
594 | 594 | def magic_Exit(self, parameter_s=''): |
|
595 | 595 | """Exit IPython. If the -k option is provided, the kernel will be left |
|
596 | 596 | running. Otherwise, it will shutdown without prompting. |
|
597 | 597 | """ |
|
598 | 598 | opts,args = self.parse_options(parameter_s,'k') |
|
599 | 599 | self.shell.keepkernel_on_exit = opts.has_key('k') |
|
600 | 600 | self.shell.ask_exit() |
|
601 | 601 | |
|
602 | 602 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
603 | 603 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
604 | 604 | |
|
605 | 605 | InteractiveShellABC.register(ZMQInteractiveShell) |
@@ -1,936 +1,922 b'' | |||
|
1 | 1 | .. _messaging: |
|
2 | 2 | |
|
3 | 3 | ====================== |
|
4 | 4 | Messaging in IPython |
|
5 | 5 | ====================== |
|
6 | 6 | |
|
7 | 7 | |
|
8 | 8 | Introduction |
|
9 | 9 | ============ |
|
10 | 10 | |
|
11 | 11 | This document explains the basic communications design and messaging |
|
12 | 12 | specification for how the various IPython objects interact over a network |
|
13 | 13 | transport. The current implementation uses the ZeroMQ_ library for messaging |
|
14 | 14 | within and between hosts. |
|
15 | 15 | |
|
16 | 16 | .. Note:: |
|
17 | 17 | |
|
18 | 18 | This document should be considered the authoritative description of the |
|
19 | 19 | IPython messaging protocol, and all developers are strongly encouraged to |
|
20 | 20 | keep it updated as the implementation evolves, so that we have a single |
|
21 | 21 | common reference for all protocol details. |
|
22 | 22 | |
|
23 | 23 | The basic design is explained in the following diagram: |
|
24 | 24 | |
|
25 | 25 | .. image:: frontend-kernel.png |
|
26 | 26 | :width: 450px |
|
27 | 27 | :alt: IPython kernel/frontend messaging architecture. |
|
28 | 28 | :align: center |
|
29 | 29 | :target: ../_images/frontend-kernel.png |
|
30 | 30 | |
|
31 | 31 | A single kernel can be simultaneously connected to one or more frontends. The |
|
32 | 32 | kernel has three sockets that serve the following functions: |
|
33 | 33 | |
|
34 | 34 | 1. REQ: this socket is connected to a *single* frontend at a time, and it allows |
|
35 | 35 | the kernel to request input from a frontend when :func:`raw_input` is called. |
|
36 | 36 | The frontend holding the matching REP socket acts as a 'virtual keyboard' |
|
37 | 37 | for the kernel while this communication is happening (illustrated in the |
|
38 | 38 | figure by the black outline around the central keyboard). In practice, |
|
39 | 39 | frontends may display such kernel requests using a special input widget or |
|
40 | 40 | otherwise indicating that the user is to type input for the kernel instead |
|
41 | 41 | of normal commands in the frontend. |
|
42 | 42 | |
|
43 | 43 | 2. XREP: this single sockets allows multiple incoming connections from |
|
44 | 44 | frontends, and this is the socket where requests for code execution, object |
|
45 | 45 | information, prompts, etc. are made to the kernel by any frontend. The |
|
46 | 46 | communication on this socket is a sequence of request/reply actions from |
|
47 | 47 | each frontend and the kernel. |
|
48 | 48 | |
|
49 | 49 | 3. PUB: this socket is the 'broadcast channel' where the kernel publishes all |
|
50 | 50 | side effects (stdout, stderr, etc.) as well as the requests coming from any |
|
51 | 51 | client over the XREP socket and its own requests on the REP socket. There |
|
52 | 52 | are a number of actions in Python which generate side effects: :func:`print` |
|
53 | 53 | writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in |
|
54 | 54 | a multi-client scenario, we want all frontends to be able to know what each |
|
55 | 55 | other has sent to the kernel (this can be useful in collaborative scenarios, |
|
56 | 56 | for example). This socket allows both side effects and the information |
|
57 | 57 | about communications taking place with one client over the XREQ/XREP channel |
|
58 | 58 | to be made available to all clients in a uniform manner. |
|
59 | 59 | |
|
60 | 60 | All messages are tagged with enough information (details below) for clients |
|
61 | 61 | to know which messages come from their own interaction with the kernel and |
|
62 | 62 | which ones are from other clients, so they can display each type |
|
63 | 63 | appropriately. |
|
64 | 64 | |
|
65 | 65 | The actual format of the messages allowed on each of these channels is |
|
66 | 66 | specified below. Messages are dicts of dicts with string keys and values that |
|
67 | 67 | are reasonably representable in JSON. Our current implementation uses JSON |
|
68 | 68 | explicitly as its message format, but this shouldn't be considered a permanent |
|
69 | 69 | feature. As we've discovered that JSON has non-trivial performance issues due |
|
70 | 70 | to excessive copying, we may in the future move to a pure pickle-based raw |
|
71 | 71 | message format. However, it should be possible to easily convert from the raw |
|
72 | 72 | objects to JSON, since we may have non-python clients (e.g. a web frontend). |
|
73 | 73 | As long as it's easy to make a JSON version of the objects that is a faithful |
|
74 | 74 | representation of all the data, we can communicate with such clients. |
|
75 | 75 | |
|
76 | 76 | .. Note:: |
|
77 | 77 | |
|
78 | 78 | Not all of these have yet been fully fleshed out, but the key ones are, see |
|
79 | 79 | kernel and frontend files for actual implementation details. |
|
80 | 80 | |
|
81 | 81 | |
|
82 | 82 | Python functional API |
|
83 | 83 | ===================== |
|
84 | 84 | |
|
85 | 85 | As messages are dicts, they map naturally to a ``func(**kw)`` call form. We |
|
86 | 86 | should develop, at a few key points, functional forms of all the requests that |
|
87 | 87 | take arguments in this manner and automatically construct the necessary dict |
|
88 | 88 | for sending. |
|
89 | 89 | |
|
90 | 90 | |
|
91 | 91 | General Message Format |
|
92 | 92 | ====================== |
|
93 | 93 | |
|
94 | 94 | All messages send or received by any IPython process should have the following |
|
95 | 95 | generic structure:: |
|
96 | 96 | |
|
97 | 97 | { |
|
98 | 98 | # The message header contains a pair of unique identifiers for the |
|
99 | 99 | # originating session and the actual message id, in addition to the |
|
100 | 100 | # username for the process that generated the message. This is useful in |
|
101 | 101 | # collaborative settings where multiple users may be interacting with the |
|
102 | 102 | # same kernel simultaneously, so that frontends can label the various |
|
103 | 103 | # messages in a meaningful way. |
|
104 | 104 | 'header' : { 'msg_id' : uuid, |
|
105 | 105 | 'username' : str, |
|
106 | 106 | 'session' : uuid |
|
107 | 107 | }, |
|
108 | 108 | |
|
109 | 109 | # In a chain of messages, the header from the parent is copied so that |
|
110 | 110 | # clients can track where messages come from. |
|
111 | 111 | 'parent_header' : dict, |
|
112 | 112 | |
|
113 | 113 | # All recognized message type strings are listed below. |
|
114 | 114 | 'msg_type' : str, |
|
115 | 115 | |
|
116 | 116 | # The actual content of the message must be a dict, whose structure |
|
117 | 117 | # depends on the message type.x |
|
118 | 118 | 'content' : dict, |
|
119 | 119 | } |
|
120 | 120 | |
|
121 | 121 | For each message type, the actual content will differ and all existing message |
|
122 | 122 | types are specified in what follows of this document. |
|
123 | 123 | |
|
124 | 124 | |
|
125 | 125 | Messages on the XREP/XREQ socket |
|
126 | 126 | ================================ |
|
127 | 127 | |
|
128 | 128 | .. _execute: |
|
129 | 129 | |
|
130 | 130 | Execute |
|
131 | 131 | ------- |
|
132 | 132 | |
|
133 | 133 | This message type is used by frontends to ask the kernel to execute code on |
|
134 | 134 | behalf of the user, in a namespace reserved to the user's variables (and thus |
|
135 | 135 | separate from the kernel's own internal code and variables). |
|
136 | 136 | |
|
137 | 137 | Message type: ``execute_request``:: |
|
138 | 138 | |
|
139 | 139 | content = { |
|
140 | 140 | # Source code to be executed by the kernel, one or more lines. |
|
141 | 141 | 'code' : str, |
|
142 | 142 | |
|
143 | 143 | # A boolean flag which, if True, signals the kernel to execute this |
|
144 | 144 | # code as quietly as possible. This means that the kernel will compile |
|
145 | 145 | # the code witIPython/core/tests/h 'exec' instead of 'single' (so |
|
146 | 146 | # sys.displayhook will not fire), and will *not*: |
|
147 | 147 | # - broadcast exceptions on the PUB socket |
|
148 | 148 | # - do any logging |
|
149 | 149 | # - populate any history |
|
150 | 150 | # |
|
151 | 151 | # The default is False. |
|
152 | 152 | 'silent' : bool, |
|
153 | 153 | |
|
154 | 154 | # A list of variable names from the user's namespace to be retrieved. What |
|
155 | 155 | # returns is a JSON string of the variable's repr(), not a python object. |
|
156 | 156 | 'user_variables' : list, |
|
157 | 157 | |
|
158 | 158 | # Similarly, a dict mapping names to expressions to be evaluated in the |
|
159 | 159 | # user's dict. |
|
160 | 160 | 'user_expressions' : dict, |
|
161 | 161 | } |
|
162 | 162 | |
|
163 | 163 | The ``code`` field contains a single string (possibly multiline). The kernel |
|
164 | 164 | is responsible for splitting this into one or more independent execution blocks |
|
165 | 165 | and deciding whether to compile these in 'single' or 'exec' mode (see below for |
|
166 | 166 | detailed execution semantics). |
|
167 | 167 | |
|
168 | 168 | The ``user_`` fields deserve a detailed explanation. In the past, IPython had |
|
169 | 169 | the notion of a prompt string that allowed arbitrary code to be evaluated, and |
|
170 | 170 | this was put to good use by many in creating prompts that displayed system |
|
171 | 171 | status, path information, and even more esoteric uses like remote instrument |
|
172 | 172 | status aqcuired over the network. But now that IPython has a clean separation |
|
173 | 173 | between the kernel and the clients, the kernel has no prompt knowledge; prompts |
|
174 | 174 | are a frontend-side feature, and it should be even possible for different |
|
175 | 175 | frontends to display different prompts while interacting with the same kernel. |
|
176 | 176 | |
|
177 | 177 | The kernel now provides the ability to retrieve data from the user's namespace |
|
178 | 178 | after the execution of the main ``code``, thanks to two fields in the |
|
179 | 179 | ``execute_request`` message: |
|
180 | 180 | |
|
181 | 181 | - ``user_variables``: If only variables from the user's namespace are needed, a |
|
182 | 182 | list of variable names can be passed and a dict with these names as keys and |
|
183 | 183 | their :func:`repr()` as values will be returned. |
|
184 | 184 | |
|
185 | 185 | - ``user_expressions``: For more complex expressions that require function |
|
186 | 186 | evaluations, a dict can be provided with string keys and arbitrary python |
|
187 | 187 | expressions as values. The return message will contain also a dict with the |
|
188 | 188 | same keys and the :func:`repr()` of the evaluated expressions as value. |
|
189 | 189 | |
|
190 | 190 | With this information, frontends can display any status information they wish |
|
191 | 191 | in the form that best suits each frontend (a status line, a popup, inline for a |
|
192 | 192 | terminal, etc). |
|
193 | 193 | |
|
194 | 194 | .. Note:: |
|
195 | 195 | |
|
196 | 196 | In order to obtain the current execution counter for the purposes of |
|
197 | 197 | displaying input prompts, frontends simply make an execution request with an |
|
198 | 198 | empty code string and ``silent=True``. |
|
199 | 199 | |
|
200 | 200 | Execution semantics |
|
201 | 201 | ~~~~~~~~~~~~~~~~~~~ |
|
202 | 202 | |
|
203 | 203 | When the silent flag is false, the execution of use code consists of the |
|
204 | 204 | following phases (in silent mode, only the ``code`` field is executed): |
|
205 | 205 | |
|
206 | 206 | 1. Run the ``pre_runcode_hook``. |
|
207 | 207 | |
|
208 | 208 | 2. Execute the ``code`` field, see below for details. |
|
209 | 209 | |
|
210 | 210 | 3. If #2 succeeds, compute ``user_variables`` and ``user_expressions`` are |
|
211 | 211 | computed. This ensures that any error in the latter don't harm the main |
|
212 | 212 | code execution. |
|
213 | 213 | |
|
214 | 214 | 4. Call any method registered with :meth:`register_post_execute`. |
|
215 | 215 | |
|
216 | 216 | .. warning:: |
|
217 | 217 | |
|
218 | 218 | The API for running code before/after the main code block is likely to |
|
219 | 219 | change soon. Both the ``pre_runcode_hook`` and the |
|
220 | 220 | :meth:`register_post_execute` are susceptible to modification, as we find a |
|
221 | 221 | consistent model for both. |
|
222 | 222 | |
|
223 | 223 | To understand how the ``code`` field is executed, one must know that Python |
|
224 | 224 | code can be compiled in one of three modes (controlled by the ``mode`` argument |
|
225 | 225 | to the :func:`compile` builtin): |
|
226 | 226 | |
|
227 | 227 | *single* |
|
228 | 228 | Valid for a single interactive statement (though the source can contain |
|
229 | 229 | multiple lines, such as a for loop). When compiled in this mode, the |
|
230 | 230 | generated bytecode contains special instructions that trigger the calling of |
|
231 | 231 | :func:`sys.displayhook` for any expression in the block that returns a value. |
|
232 | 232 | This means that a single statement can actually produce multiple calls to |
|
233 | 233 | :func:`sys.displayhook`, if for example it contains a loop where each |
|
234 | 234 | iteration computes an unassigned expression would generate 10 calls:: |
|
235 | 235 | |
|
236 | 236 | for i in range(10): |
|
237 | 237 | i**2 |
|
238 | 238 | |
|
239 | 239 | *exec* |
|
240 | 240 | An arbitrary amount of source code, this is how modules are compiled. |
|
241 | 241 | :func:`sys.displayhook` is *never* implicitly called. |
|
242 | 242 | |
|
243 | 243 | *eval* |
|
244 | 244 | A single expression that returns a value. :func:`sys.displayhook` is *never* |
|
245 | 245 | implicitly called. |
|
246 | 246 | |
|
247 | 247 | |
|
248 | 248 | The ``code`` field is split into individual blocks each of which is valid for |
|
249 | 249 | execution in 'single' mode, and then: |
|
250 | 250 | |
|
251 | 251 | - If there is only a single block: it is executed in 'single' mode. |
|
252 | 252 | |
|
253 | 253 | - If there is more than one block: |
|
254 | 254 | |
|
255 | 255 | * if the last one is a single line long, run all but the last in 'exec' mode |
|
256 | 256 | and the very last one in 'single' mode. This makes it easy to type simple |
|
257 | 257 | expressions at the end to see computed values. |
|
258 | 258 | |
|
259 | 259 | * if the last one is no more than two lines long, run all but the last in |
|
260 | 260 | 'exec' mode and the very last one in 'single' mode. This makes it easy to |
|
261 | 261 | type simple expressions at the end to see computed values. - otherwise |
|
262 | 262 | (last one is also multiline), run all in 'exec' mode |
|
263 | 263 | |
|
264 | 264 | * otherwise (last one is also multiline), run all in 'exec' mode as a single |
|
265 | 265 | unit. |
|
266 | 266 | |
|
267 | 267 | Any error in retrieving the ``user_variables`` or evaluating the |
|
268 | 268 | ``user_expressions`` will result in a simple error message in the return fields |
|
269 | 269 | of the form:: |
|
270 | 270 | |
|
271 | 271 | [ERROR] ExceptionType: Exception message |
|
272 | 272 | |
|
273 | 273 | The user can simply send the same variable name or expression for evaluation to |
|
274 | 274 | see a regular traceback. |
|
275 | 275 | |
|
276 | 276 | Errors in any registered post_execute functions are also reported similarly, |
|
277 | 277 | and the failing function is removed from the post_execution set so that it does |
|
278 | 278 | not continue triggering failures. |
|
279 | 279 | |
|
280 | 280 | Upon completion of the execution request, the kernel *always* sends a reply, |
|
281 | 281 | with a status code indicating what happened and additional data depending on |
|
282 | 282 | the outcome. See :ref:`below <execution_results>` for the possible return |
|
283 | 283 | codes and associated data. |
|
284 | 284 | |
|
285 | 285 | |
|
286 | 286 | Execution counter (old prompt number) |
|
287 | 287 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
288 | 288 | |
|
289 | 289 | The kernel has a single, monotonically increasing counter of all execution |
|
290 | 290 | requests that are made with ``silent=False``. This counter is used to populate |
|
291 | 291 | the ``In[n]``, ``Out[n]`` and ``_n`` variables, so clients will likely want to |
|
292 | 292 | display it in some form to the user, which will typically (but not necessarily) |
|
293 | 293 | be done in the prompts. The value of this counter will be returned as the |
|
294 | 294 | ``execution_count`` field of all ``execute_reply`` messages. |
|
295 | 295 | |
|
296 | 296 | .. _execution_results: |
|
297 | 297 | |
|
298 | 298 | Execution results |
|
299 | 299 | ~~~~~~~~~~~~~~~~~ |
|
300 | 300 | |
|
301 | 301 | Message type: ``execute_reply``:: |
|
302 | 302 | |
|
303 | 303 | content = { |
|
304 | 304 | # One of: 'ok' OR 'error' OR 'abort' |
|
305 | 305 | 'status' : str, |
|
306 | 306 | |
|
307 | 307 | # The global kernel counter that increases by one with each non-silent |
|
308 | 308 | # executed request. This will typically be used by clients to display |
|
309 | 309 | # prompt numbers to the user. If the request was a silent one, this will |
|
310 | 310 | # be the current value of the counter in the kernel. |
|
311 | 311 | 'execution_count' : int, |
|
312 | 312 | } |
|
313 | 313 | |
|
314 | 314 | When status is 'ok', the following extra fields are present:: |
|
315 | 315 | |
|
316 | 316 | { |
|
317 | 317 | # The execution payload is a dict with string keys that may have been |
|
318 | 318 | # produced by the code being executed. It is retrieved by the kernel at |
|
319 | 319 | # the end of the execution and sent back to the front end, which can take |
|
320 | 320 | # action on it as needed. See main text for further details. |
|
321 | 321 | 'payload' : dict, |
|
322 | 322 | |
|
323 | 323 | # Results for the user_variables and user_expressions. |
|
324 | 324 | 'user_variables' : dict, |
|
325 | 325 | 'user_expressions' : dict, |
|
326 | 326 | |
|
327 | 327 | # The kernel will often transform the input provided to it. If the |
|
328 | 328 | # '---->' transform had been applied, this is filled, otherwise it's the |
|
329 | 329 | # empty string. So transformations like magics don't appear here, only |
|
330 | 330 | # autocall ones. |
|
331 | 331 | 'transformed_code' : str, |
|
332 | 332 | } |
|
333 | 333 | |
|
334 | 334 | .. admonition:: Execution payloads |
|
335 | 335 | |
|
336 | 336 | The notion of an 'execution payload' is different from a return value of a |
|
337 | 337 | given set of code, which normally is just displayed on the pyout stream |
|
338 | 338 | through the PUB socket. The idea of a payload is to allow special types of |
|
339 | 339 | code, typically magics, to populate a data container in the IPython kernel |
|
340 | 340 | that will be shipped back to the caller via this channel. The kernel will |
|
341 | 341 | have an API for this, probably something along the lines of:: |
|
342 | 342 | |
|
343 | 343 | ip.exec_payload_add(key, value) |
|
344 | 344 | |
|
345 | 345 | though this API is still in the design stages. The data returned in this |
|
346 | 346 | payload will allow frontends to present special views of what just happened. |
|
347 | 347 | |
|
348 | 348 | |
|
349 | 349 | When status is 'error', the following extra fields are present:: |
|
350 | 350 | |
|
351 | 351 | { |
|
352 | 352 | 'exc_name' : str, # Exception name, as a string |
|
353 | 353 | 'exc_value' : str, # Exception value, as a string |
|
354 | 354 | |
|
355 | 355 | # The traceback will contain a list of frames, represented each as a |
|
356 | 356 | # string. For now we'll stick to the existing design of ultraTB, which |
|
357 | 357 | # controls exception level of detail statefully. But eventually we'll |
|
358 | 358 | # want to grow into a model where more information is collected and |
|
359 | 359 | # packed into the traceback object, with clients deciding how little or |
|
360 | 360 | # how much of it to unpack. But for now, let's start with a simple list |
|
361 | 361 | # of strings, since that requires only minimal changes to ultratb as |
|
362 | 362 | # written. |
|
363 | 363 | 'traceback' : list, |
|
364 | 364 | } |
|
365 | 365 | |
|
366 | 366 | |
|
367 | 367 | When status is 'abort', there are for now no additional data fields. This |
|
368 | 368 | happens when the kernel was interrupted by a signal. |
|
369 | 369 | |
|
370 | 370 | Kernel attribute access |
|
371 | 371 | ----------------------- |
|
372 | 372 | |
|
373 | 373 | .. warning:: |
|
374 | 374 | |
|
375 | 375 | This part of the messaging spec is not actually implemented in the kernel |
|
376 | 376 | yet. |
|
377 | 377 | |
|
378 | 378 | While this protocol does not specify full RPC access to arbitrary methods of |
|
379 | 379 | the kernel object, the kernel does allow read (and in some cases write) access |
|
380 | 380 | to certain attributes. |
|
381 | 381 | |
|
382 | 382 | The policy for which attributes can be read is: any attribute of the kernel, or |
|
383 | 383 | its sub-objects, that belongs to a :class:`Configurable` object and has been |
|
384 | 384 | declared at the class-level with Traits validation, is in principle accessible |
|
385 | 385 | as long as its name does not begin with a leading underscore. The attribute |
|
386 | 386 | itself will have metadata indicating whether it allows remote read and/or write |
|
387 | 387 | access. The message spec follows for attribute read and write requests. |
|
388 | 388 | |
|
389 | 389 | Message type: ``getattr_request``:: |
|
390 | 390 | |
|
391 | 391 | content = { |
|
392 | 392 | # The (possibly dotted) name of the attribute |
|
393 | 393 | 'name' : str, |
|
394 | 394 | } |
|
395 | 395 | |
|
396 | 396 | When a ``getattr_request`` fails, there are two possible error types: |
|
397 | 397 | |
|
398 | 398 | - AttributeError: this type of error was raised when trying to access the |
|
399 | 399 | given name by the kernel itself. This means that the attribute likely |
|
400 | 400 | doesn't exist. |
|
401 | 401 | |
|
402 | 402 | - AccessError: the attribute exists but its value is not readable remotely. |
|
403 | 403 | |
|
404 | 404 | |
|
405 | 405 | Message type: ``getattr_reply``:: |
|
406 | 406 | |
|
407 | 407 | content = { |
|
408 | 408 | # One of ['ok', 'AttributeError', 'AccessError']. |
|
409 | 409 | 'status' : str, |
|
410 | 410 | # If status is 'ok', a JSON object. |
|
411 | 411 | 'value' : object, |
|
412 | 412 | } |
|
413 | 413 | |
|
414 | 414 | Message type: ``setattr_request``:: |
|
415 | 415 | |
|
416 | 416 | content = { |
|
417 | 417 | # The (possibly dotted) name of the attribute |
|
418 | 418 | 'name' : str, |
|
419 | 419 | |
|
420 | 420 | # A JSON-encoded object, that will be validated by the Traits |
|
421 | 421 | # information in the kernel |
|
422 | 422 | 'value' : object, |
|
423 | 423 | } |
|
424 | 424 | |
|
425 | 425 | When a ``setattr_request`` fails, there are also two possible error types with |
|
426 | 426 | similar meanings as those of the ``getattr_request`` case, but for writing. |
|
427 | 427 | |
|
428 | 428 | Message type: ``setattr_reply``:: |
|
429 | 429 | |
|
430 | 430 | content = { |
|
431 | 431 | # One of ['ok', 'AttributeError', 'AccessError']. |
|
432 | 432 | 'status' : str, |
|
433 | 433 | } |
|
434 | 434 | |
|
435 | 435 | |
|
436 | 436 | |
|
437 | 437 | Object information |
|
438 | 438 | ------------------ |
|
439 | 439 | |
|
440 | 440 | One of IPython's most used capabilities is the introspection of Python objects |
|
441 | 441 | in the user's namespace, typically invoked via the ``?`` and ``??`` characters |
|
442 | 442 | (which in reality are shorthands for the ``%pinfo`` magic). This is used often |
|
443 | 443 | enough that it warrants an explicit message type, especially because frontends |
|
444 | 444 | may want to get object information in response to user keystrokes (like Tab or |
|
445 | 445 | F1) besides from the user explicitly typing code like ``x??``. |
|
446 | 446 | |
|
447 | 447 | Message type: ``object_info_request``:: |
|
448 | 448 | |
|
449 | 449 | content = { |
|
450 | 450 | # The (possibly dotted) name of the object to be searched in all |
|
451 | 451 | # relevant namespaces |
|
452 | 452 | 'name' : str, |
|
453 | 453 | |
|
454 | 454 | # The level of detail desired. The default (0) is equivalent to typing |
|
455 | 455 | # 'x?' at the prompt, 1 is equivalent to 'x??'. |
|
456 | 456 | 'detail_level' : int, |
|
457 | 457 | } |
|
458 | 458 | |
|
459 | 459 | The returned information will be a dictionary with keys very similar to the |
|
460 | 460 | field names that IPython prints at the terminal. |
|
461 | 461 | |
|
462 | 462 | Message type: ``object_info_reply``:: |
|
463 | 463 | |
|
464 | 464 | content = { |
|
465 | 465 | # The name the object was requested under |
|
466 | 466 | 'name' : str, |
|
467 | 467 | |
|
468 | 468 | # Boolean flag indicating whether the named object was found or not. If |
|
469 | 469 | # it's false, all other fields will be empty. |
|
470 | 470 | 'found' : bool, |
|
471 | 471 | |
|
472 | 472 | # Flags for magics and system aliases |
|
473 | 473 | 'ismagic' : bool, |
|
474 | 474 | 'isalias' : bool, |
|
475 | 475 | |
|
476 | 476 | # The name of the namespace where the object was found ('builtin', |
|
477 | 477 | # 'magics', 'alias', 'interactive', etc.) |
|
478 | 478 | 'namespace' : str, |
|
479 | 479 | |
|
480 | 480 | # The type name will be type.__name__ for normal Python objects, but it |
|
481 | 481 | # can also be a string like 'Magic function' or 'System alias' |
|
482 | 482 | 'type_name' : str, |
|
483 | 483 | |
|
484 | 484 | 'string_form' : str, |
|
485 | 485 | |
|
486 | 486 | # For objects with a __class__ attribute this will be set |
|
487 | 487 | 'base_class' : str, |
|
488 | 488 | |
|
489 | 489 | # For objects with a __len__ attribute this will be set |
|
490 | 490 | 'length' : int, |
|
491 | 491 | |
|
492 | 492 | # If the object is a function, class or method whose file we can find, |
|
493 | 493 | # we give its full path |
|
494 | 494 | 'file' : str, |
|
495 | 495 | |
|
496 | 496 | # For pure Python callable objects, we can reconstruct the object |
|
497 | 497 | # definition line which provides its call signature. For convenience this |
|
498 | 498 | # is returned as a single 'definition' field, but below the raw parts that |
|
499 | 499 | # compose it are also returned as the argspec field. |
|
500 | 500 | 'definition' : str, |
|
501 | 501 | |
|
502 | 502 | # The individual parts that together form the definition string. Clients |
|
503 | 503 | # with rich display capabilities may use this to provide a richer and more |
|
504 | 504 | # precise representation of the definition line (e.g. by highlighting |
|
505 | 505 | # arguments based on the user's cursor position). For non-callable |
|
506 | 506 | # objects, this field is empty. |
|
507 | 507 | 'argspec' : { # The names of all the arguments |
|
508 | 508 | args : list, |
|
509 | 509 | # The name of the varargs (*args), if any |
|
510 | 510 | varargs : str, |
|
511 | 511 | # The name of the varkw (**kw), if any |
|
512 | 512 | varkw : str, |
|
513 | 513 | # The values (as strings) of all default arguments. Note |
|
514 | 514 | # that these must be matched *in reverse* with the 'args' |
|
515 | 515 | # list above, since the first positional args have no default |
|
516 | 516 | # value at all. |
|
517 | 517 | defaults : list, |
|
518 | 518 | }, |
|
519 | 519 | |
|
520 | 520 | # For instances, provide the constructor signature (the definition of |
|
521 | 521 | # the __init__ method): |
|
522 | 522 | 'init_definition' : str, |
|
523 | 523 | |
|
524 | 524 | # Docstrings: for any object (function, method, module, package) with a |
|
525 | 525 | # docstring, we show it. But in addition, we may provide additional |
|
526 | 526 | # docstrings. For example, for instances we will show the constructor |
|
527 | 527 | # and class docstrings as well, if available. |
|
528 | 528 | 'docstring' : str, |
|
529 | 529 | |
|
530 | 530 | # For instances, provide the constructor and class docstrings |
|
531 | 531 | 'init_docstring' : str, |
|
532 | 532 | 'class_docstring' : str, |
|
533 | 533 | |
|
534 | 534 | # If it's a callable object whose call method has a separate docstring and |
|
535 | 535 | # definition line: |
|
536 | 536 | 'call_def' : str, |
|
537 | 537 | 'call_docstring' : str, |
|
538 | 538 | |
|
539 | 539 | # If detail_level was 1, we also try to find the source code that |
|
540 | 540 | # defines the object, if possible. The string 'None' will indicate |
|
541 | 541 | # that no source was found. |
|
542 | 542 | 'source' : str, |
|
543 | 543 | } |
|
544 | 544 | ' |
|
545 | 545 | |
|
546 | 546 | Complete |
|
547 | 547 | -------- |
|
548 | 548 | |
|
549 | 549 | Message type: ``complete_request``:: |
|
550 | 550 | |
|
551 | 551 | content = { |
|
552 | 552 | # The text to be completed, such as 'a.is' |
|
553 | 553 | 'text' : str, |
|
554 | 554 | |
|
555 | 555 | # The full line, such as 'print a.is'. This allows completers to |
|
556 | 556 | # make decisions that may require information about more than just the |
|
557 | 557 | # current word. |
|
558 | 558 | 'line' : str, |
|
559 | 559 | |
|
560 | 560 | # The entire block of text where the line is. This may be useful in the |
|
561 | 561 | # case of multiline completions where more context may be needed. Note: if |
|
562 | 562 | # in practice this field proves unnecessary, remove it to lighten the |
|
563 | 563 | # messages. |
|
564 | 564 | |
|
565 | 565 | 'block' : str, |
|
566 | 566 | |
|
567 | 567 | # The position of the cursor where the user hit 'TAB' on the line. |
|
568 | 568 | 'cursor_pos' : int, |
|
569 | 569 | } |
|
570 | 570 | |
|
571 | 571 | Message type: ``complete_reply``:: |
|
572 | 572 | |
|
573 | 573 | content = { |
|
574 | 574 | # The list of all matches to the completion request, such as |
|
575 | 575 | # ['a.isalnum', 'a.isalpha'] for the above example. |
|
576 | 576 | 'matches' : list |
|
577 | 577 | } |
|
578 | 578 | |
|
579 | 579 | |
|
580 | 580 | History |
|
581 | 581 | ------- |
|
582 | 582 | |
|
583 | 583 | For clients to explicitly request history from a kernel. The kernel has all |
|
584 | 584 | the actual execution history stored in a single location, so clients can |
|
585 | 585 | request it from the kernel when needed. |
|
586 | 586 | |
|
587 | 587 | Message type: ``history_request``:: |
|
588 | 588 | |
|
589 | 589 | content = { |
|
590 | 590 | |
|
591 | 591 | # If True, also return output history in the resulting dict. |
|
592 | 592 | 'output' : bool, |
|
593 | 593 | |
|
594 | 594 | # If True, return the raw input history, else the transformed input. |
|
595 | 595 | 'raw' : bool, |
|
596 | 596 | |
|
597 | 597 | # This parameter can be one of: A number, a pair of numbers, None |
|
598 | 598 | # If not given, last 40 are returned. |
|
599 | 599 | # - number n: return the last n entries. |
|
600 | 600 | # - pair n1, n2: return entries in the range(n1, n2). |
|
601 | 601 | # - None: return all history |
|
602 | 602 | 'index' : n or (n1, n2) or None, |
|
603 | 603 | } |
|
604 | 604 | |
|
605 | 605 | Message type: ``history_reply``:: |
|
606 | 606 | |
|
607 | 607 | content = { |
|
608 | 608 | # A dict with prompt numbers as keys and either (input, output) or input |
|
609 | 609 | # as the value depending on whether output was True or False, |
|
610 | 610 | # respectively. |
|
611 | 611 | 'history' : dict, |
|
612 | 612 | } |
|
613 | 613 | |
|
614 | 614 | |
|
615 | 615 | Connect |
|
616 | 616 | ------- |
|
617 | 617 | |
|
618 | 618 | When a client connects to the request/reply socket of the kernel, it can issue |
|
619 | 619 | a connect request to get basic information about the kernel, such as the ports |
|
620 | 620 | the other ZeroMQ sockets are listening on. This allows clients to only have |
|
621 | 621 | to know about a single port (the XREQ/XREP channel) to connect to a kernel. |
|
622 | 622 | |
|
623 | 623 | Message type: ``connect_request``:: |
|
624 | 624 | |
|
625 | 625 | content = { |
|
626 | 626 | } |
|
627 | 627 | |
|
628 | 628 | Message type: ``connect_reply``:: |
|
629 | 629 | |
|
630 | 630 | content = { |
|
631 | 631 | 'xrep_port' : int # The port the XREP socket is listening on. |
|
632 | 632 | 'pub_port' : int # The port the PUB socket is listening on. |
|
633 | 633 | 'req_port' : int # The port the REQ socket is listening on. |
|
634 | 634 | 'hb_port' : int # The port the heartbeat socket is listening on. |
|
635 | 635 | } |
|
636 | 636 | |
|
637 | 637 | |
|
638 | 638 | |
|
639 | 639 | Kernel shutdown |
|
640 | 640 | --------------- |
|
641 | 641 | |
|
642 | 642 | The clients can request the kernel to shut itself down; this is used in |
|
643 | 643 | multiple cases: |
|
644 | 644 | |
|
645 | 645 | - when the user chooses to close the client application via a menu or window |
|
646 | 646 | control. |
|
647 | 647 | - when the user types 'exit' or 'quit' (or their uppercase magic equivalents). |
|
648 | 648 | - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the |
|
649 | 649 | IPythonQt client) to force a kernel restart to get a clean kernel without |
|
650 | 650 | losing client-side state like history or inlined figures. |
|
651 | 651 | |
|
652 | 652 | The client sends a shutdown request to the kernel, and once it receives the |
|
653 | 653 | reply message (which is otherwise empty), it can assume that the kernel has |
|
654 | 654 | completed shutdown safely. |
|
655 | 655 | |
|
656 | 656 | Upon their own shutdown, client applications will typically execute a last |
|
657 | 657 | minute sanity check and forcefully terminate any kernel that is still alive, to |
|
658 | 658 | avoid leaving stray processes in the user's machine. |
|
659 | 659 | |
|
660 | 660 | For both shutdown request and reply, there is no actual content that needs to |
|
661 | 661 | be sent, so the content dict is empty. |
|
662 | 662 | |
|
663 | 663 | Message type: ``shutdown_request``:: |
|
664 | 664 | |
|
665 | 665 | content = { |
|
666 | 666 | 'restart' : bool # whether the shutdown is final, or precedes a restart |
|
667 | 667 | } |
|
668 | 668 | |
|
669 | 669 | Message type: ``shutdown_reply``:: |
|
670 | 670 | |
|
671 | 671 | content = { |
|
672 | 672 | 'restart' : bool # whether the shutdown is final, or precedes a restart |
|
673 | 673 | } |
|
674 | 674 | |
|
675 | 675 | .. Note:: |
|
676 | 676 | |
|
677 | 677 | When the clients detect a dead kernel thanks to inactivity on the heartbeat |
|
678 | 678 | socket, they simply send a forceful process termination signal, since a dead |
|
679 | 679 | process is unlikely to respond in any useful way to messages. |
|
680 | 680 | |
|
681 | 681 | |
|
682 | 682 | Messages on the PUB/SUB socket |
|
683 | 683 | ============================== |
|
684 | 684 | |
|
685 | 685 | Streams (stdout, stderr, etc) |
|
686 | 686 | ------------------------------ |
|
687 | 687 | |
|
688 | 688 | Message type: ``stream``:: |
|
689 | 689 | |
|
690 | 690 | content = { |
|
691 | 691 | # The name of the stream is one of 'stdin', 'stdout', 'stderr' |
|
692 | 'name' : str, | |
|
692 | 'name' : str, | |
|
693 | 693 | |
|
694 | # The data is an arbitrary string to be written to that stream | |
|
695 | 'data' : str, | |
|
694 | # The data is an arbitrary string to be written to that stream | |
|
695 | 'data' : str, | |
|
696 | 696 | } |
|
697 | 697 | |
|
698 | 698 | When a kernel receives a raw_input call, it should also broadcast it on the pub |
|
699 | 699 | socket with the names 'stdin' and 'stdin_reply'. This will allow other clients |
|
700 | 700 | to monitor/display kernel interactions and possibly replay them to their user |
|
701 | 701 | or otherwise expose them. |
|
702 | 702 | |
|
703 | 703 | Display Data |
|
704 | 704 | ------------ |
|
705 | 705 | |
|
706 | 706 | This type of message is used to bring back data that should be diplayed (text, |
|
707 | 707 | html, svg, etc.) in the frontends. This data is published to all frontends. |
|
708 | 708 | Each message can have multiple representations of the data; it is up to the |
|
709 | 709 | frontend to decide which to use and how. A single message should contain all |
|
710 | 710 | possible representations of the same information. Each representation should |
|
711 | 711 | be a JSON'able data structure, and should be a valid MIME type. |
|
712 | 712 | |
|
713 | 713 | Some questions remain about this design: |
|
714 | 714 | |
|
715 | 715 | * Do we use this message type for pyout/displayhook? Probably not, because |
|
716 | 716 | the displayhook also has to handle the Out prompt display. On the other hand |
|
717 | 717 | we could put that information into the metadata secion. |
|
718 | 718 | |
|
719 | 719 | Message type: ``display_data``:: |
|
720 | 720 | |
|
721 | 721 | content = { |
|
722 | 'source' : str # Who create the data | |
|
723 | 'data' : dict # {'mimetype1' : data1, 'mimetype2' : data2} | |
|
724 | 'metadata' : dict # Any metadata that describes the data | |
|
725 | } | |
|
726 | ||
|
727 | Other options for ``display_data`` content:: | |
|
728 | 722 | |
|
729 | # Option 2: allowing for a different source for each representation, | |
|
730 | but not keyed by anything. | |
|
731 | content = { | |
|
732 | 'data' = [(source, type, data), (source, type, data)] | |
|
733 | 'metadata' = dict | |
|
734 | } | |
|
723 | # Who create the data | |
|
724 | 'source' : str, | |
|
735 | 725 | |
|
736 | # Option 3: like option 2, but keyed by the MIME types. | |
|
737 | content = { | |
|
738 | 'data' = {'mimetype1' : (source, data), 'mimetype2' : (source, data)} | |
|
739 | 'metadata' = dict | |
|
740 | } | |
|
726 | # The data dict contains key/value pairs, where the kids are MIME | |
|
727 | # types and the values are the raw data of the representation in that | |
|
728 | # format. The data dict must minimally contain the ``text/plain`` | |
|
729 | # MIME type which is used as a backup representation. | |
|
730 | 'data' : dict, | |
|
741 | 731 | |
|
742 | # Option 4: like option 2, but keyed by the source. | |
|
743 | content = { | |
|
744 | 'data' = {'source' : (mimetype, data), 'source' : (mimetype, data)} | |
|
745 | 'metadata' = dict | |
|
732 | # Any metadata that describes the data | |
|
733 | 'metadata' : dict | |
|
746 | 734 | } |
|
747 | 735 | |
|
748 | 736 | Python inputs |
|
749 | 737 | ------------- |
|
750 | 738 | |
|
751 | 739 | These messages are the re-broadcast of the ``execute_request``. |
|
752 | 740 | |
|
753 | 741 | Message type: ``pyin``:: |
|
754 | 742 | |
|
755 | 743 | content = { |
|
756 | 744 | 'code' : str # Source code to be executed, one or more lines |
|
757 | 745 | } |
|
758 | 746 | |
|
759 | 747 | Python outputs |
|
760 | 748 | -------------- |
|
761 | 749 | |
|
762 | 750 | When Python produces output from code that has been compiled in with the |
|
763 | 751 | 'single' flag to :func:`compile`, any expression that produces a value (such as |
|
764 | 752 | ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with |
|
765 | 753 | this value whatever it wants. The default behavior of ``sys.displayhook`` in |
|
766 | 754 | the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of |
|
767 | 755 | the value as long as it is not ``None`` (which isn't printed at all). In our |
|
768 | 756 | case, the kernel instantiates as ``sys.displayhook`` an object which has |
|
769 | 757 | similar behavior, but which instead of printing to stdout, broadcasts these |
|
770 | 758 | values as ``pyout`` messages for clients to display appropriately. |
|
771 | 759 | |
|
772 | 760 | IPython's displayhook can handle multiple simultaneous formats depending on its |
|
773 | 761 | configuration. The default pretty-printed repr text is always given with the |
|
774 | 762 | ``data`` entry in this message. Any other formats are provided in the |
|
775 | 763 | ``extra_formats`` list. Frontends are free to display any or all of these |
|
776 | 764 | according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID |
|
777 | 765 | string, a type string, and the data. The ID is unique to the formatter |
|
778 | 766 | implementation that created the data. Frontends will typically ignore the ID |
|
779 | 767 | unless if it has requested a particular formatter. The type string tells the |
|
780 | 768 | frontend how to interpret the data. It is often, but not always a MIME type. |
|
781 | 769 | Frontends should ignore types that it does not understand. The data itself is |
|
782 | 770 | any JSON object and depends on the format. It is often, but not always a string. |
|
783 | 771 | |
|
784 | 772 | Message type: ``pyout``:: |
|
785 | 773 | |
|
786 | 774 | content = { |
|
787 | # The data is typically the repr() of the object. It should be displayed | |
|
788 | # as monospaced text. | |
|
789 | 'data' : str, | |
|
790 | ||
|
775 | ||
|
791 | 776 | # The counter for this execution is also provided so that clients can |
|
792 | 777 | # display it, since IPython automatically creates variables called _N |
|
793 | 778 | # (for prompt N). |
|
794 | 779 | 'execution_count' : int, |
|
780 | ||
|
781 | # The data dict contains key/value pairs, where the kids are MIME | |
|
782 | # types and the values are the raw data of the representation in that | |
|
783 | # format. The data dict must minimally contain the ``text/plain`` | |
|
784 | # MIME type which is used as a backup representation. | |
|
785 | 'data' : dict, | |
|
795 | 786 | |
|
796 | # Any extra formats. | |
|
797 | # The tuples are of the form (ID, type, data). | |
|
798 | 'extra_formats' : [ | |
|
799 | [str, str, object] | |
|
800 | ] | |
|
801 | 787 | } |
|
802 | 788 | |
|
803 | 789 | Python errors |
|
804 | 790 | ------------- |
|
805 | 791 | |
|
806 | 792 | When an error occurs during code execution |
|
807 | 793 | |
|
808 | 794 | Message type: ``pyerr``:: |
|
809 | 795 | |
|
810 | 796 | content = { |
|
811 | 797 | # Similar content to the execute_reply messages for the 'error' case, |
|
812 | 798 | # except the 'status' field is omitted. |
|
813 | 799 | } |
|
814 | 800 | |
|
815 | 801 | Kernel status |
|
816 | 802 | ------------- |
|
817 | 803 | |
|
818 | 804 | This message type is used by frontends to monitor the status of the kernel. |
|
819 | 805 | |
|
820 | 806 | Message type: ``status``:: |
|
821 | 807 | |
|
822 | 808 | content = { |
|
823 | 809 | # When the kernel starts to execute code, it will enter the 'busy' |
|
824 | 810 | # state and when it finishes, it will enter the 'idle' state. |
|
825 | 811 | execution_state : ('busy', 'idle') |
|
826 | 812 | } |
|
827 | 813 | |
|
828 | 814 | Kernel crashes |
|
829 | 815 | -------------- |
|
830 | 816 | |
|
831 | 817 | When the kernel has an unexpected exception, caught by the last-resort |
|
832 | 818 | sys.excepthook, we should broadcast the crash handler's output before exiting. |
|
833 | 819 | This will allow clients to notice that a kernel died, inform the user and |
|
834 | 820 | propose further actions. |
|
835 | 821 | |
|
836 | 822 | Message type: ``crash``:: |
|
837 | 823 | |
|
838 | 824 | content = { |
|
839 | 825 | # Similarly to the 'error' case for execute_reply messages, this will |
|
840 | 826 | # contain exc_name, exc_type and traceback fields. |
|
841 | 827 | |
|
842 | 828 | # An additional field with supplementary information such as where to |
|
843 | 829 | # send the crash message |
|
844 | 830 | 'info' : str, |
|
845 | 831 | } |
|
846 | 832 | |
|
847 | 833 | |
|
848 | 834 | Future ideas |
|
849 | 835 | ------------ |
|
850 | 836 | |
|
851 | 837 | Other potential message types, currently unimplemented, listed below as ideas. |
|
852 | 838 | |
|
853 | 839 | Message type: ``file``:: |
|
854 | 840 | |
|
855 | 841 | content = { |
|
856 | 842 | 'path' : 'cool.jpg', |
|
857 | 843 | 'mimetype' : str, |
|
858 | 844 | 'data' : str, |
|
859 | 845 | } |
|
860 | 846 | |
|
861 | 847 | |
|
862 | 848 | Messages on the REQ/REP socket |
|
863 | 849 | ============================== |
|
864 | 850 | |
|
865 | 851 | This is a socket that goes in the opposite direction: from the kernel to a |
|
866 | 852 | *single* frontend, and its purpose is to allow ``raw_input`` and similar |
|
867 | 853 | operations that read from ``sys.stdin`` on the kernel to be fulfilled by the |
|
868 | 854 | client. For now we will keep these messages as simple as possible, since they |
|
869 | 855 | basically only mean to convey the ``raw_input(prompt)`` call. |
|
870 | 856 | |
|
871 | 857 | Message type: ``input_request``:: |
|
872 | 858 | |
|
873 | 859 | content = { 'prompt' : str } |
|
874 | 860 | |
|
875 | 861 | Message type: ``input_reply``:: |
|
876 | 862 | |
|
877 | 863 | content = { 'value' : str } |
|
878 | 864 | |
|
879 | 865 | .. Note:: |
|
880 | 866 | |
|
881 | 867 | We do not explicitly try to forward the raw ``sys.stdin`` object, because in |
|
882 | 868 | practice the kernel should behave like an interactive program. When a |
|
883 | 869 | program is opened on the console, the keyboard effectively takes over the |
|
884 | 870 | ``stdin`` file descriptor, and it can't be used for raw reading anymore. |
|
885 | 871 | Since the IPython kernel effectively behaves like a console program (albeit |
|
886 | 872 | one whose "keyboard" is actually living in a separate process and |
|
887 | 873 | transported over the zmq connection), raw ``stdin`` isn't expected to be |
|
888 | 874 | available. |
|
889 | 875 | |
|
890 | 876 | |
|
891 | 877 | Heartbeat for kernels |
|
892 | 878 | ===================== |
|
893 | 879 | |
|
894 | 880 | Initially we had considered using messages like those above over ZMQ for a |
|
895 | 881 | kernel 'heartbeat' (a way to detect quickly and reliably whether a kernel is |
|
896 | 882 | alive at all, even if it may be busy executing user code). But this has the |
|
897 | 883 | problem that if the kernel is locked inside extension code, it wouldn't execute |
|
898 | 884 | the python heartbeat code. But it turns out that we can implement a basic |
|
899 | 885 | heartbeat with pure ZMQ, without using any Python messaging at all. |
|
900 | 886 | |
|
901 | 887 | The monitor sends out a single zmq message (right now, it is a str of the |
|
902 | 888 | monitor's lifetime in seconds), and gets the same message right back, prefixed |
|
903 | 889 | with the zmq identity of the XREQ socket in the heartbeat process. This can be |
|
904 | 890 | a uuid, or even a full message, but there doesn't seem to be a need for packing |
|
905 | 891 | up a message when the sender and receiver are the exact same Python object. |
|
906 | 892 | |
|
907 | 893 | The model is this:: |
|
908 | 894 | |
|
909 | 895 | monitor.send(str(self.lifetime)) # '1.2345678910' |
|
910 | 896 | |
|
911 | 897 | and the monitor receives some number of messages of the form:: |
|
912 | 898 | |
|
913 | 899 | ['uuid-abcd-dead-beef', '1.2345678910'] |
|
914 | 900 | |
|
915 | 901 | where the first part is the zmq.IDENTITY of the heart's XREQ on the engine, and |
|
916 | 902 | the rest is the message sent by the monitor. No Python code ever has any |
|
917 | 903 | access to the message between the monitor's send, and the monitor's recv. |
|
918 | 904 | |
|
919 | 905 | |
|
920 | 906 | ToDo |
|
921 | 907 | ==== |
|
922 | 908 | |
|
923 | 909 | Missing things include: |
|
924 | 910 | |
|
925 | 911 | * Important: finish thinking through the payload concept and API. |
|
926 | 912 | |
|
927 | 913 | * Important: ensure that we have a good solution for magics like %edit. It's |
|
928 | 914 | likely that with the payload concept we can build a full solution, but not |
|
929 | 915 | 100% clear yet. |
|
930 | 916 | |
|
931 | 917 | * Finishing the details of the heartbeat protocol. |
|
932 | 918 | |
|
933 | 919 | * Signal handling: specify what kind of information kernel should broadcast (or |
|
934 | 920 | not) when it receives signals. |
|
935 | 921 | |
|
936 | 922 | .. include:: ../links.rst |
General Comments 0
You need to be logged in to leave comments.
Login now