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 | c = get_config() |
|
1 | c = get_config() | |
2 |
|
2 | |||
3 | # This can be used at any point in a config file to load a sub config |
|
3 | # This can be used at any point in a config file to load a sub config | |
4 | # and merge it into the current one. |
|
4 | # and merge it into the current one. | |
5 | load_subconfig('ipython_config.py') |
|
5 | load_subconfig('ipython_config.py') | |
6 |
|
6 | |||
7 | lines = """ |
|
7 | lines = """ | |
8 | from __future__ import division |
|
8 | from __future__ import division | |
9 | from sympy import * |
|
9 | from sympy import * | |
10 | x, y, z = symbols('xyz') |
|
10 | x, y, z = symbols('xyz') | |
11 | k, m, n = symbols('kmn', integer=True) |
|
11 | k, m, n = symbols('kmn', integer=True) | |
12 | f, g, h = map(Function, 'fgh') |
|
12 | f, g, h = map(Function, 'fgh') | |
13 | """ |
|
13 | """ | |
14 |
|
14 | |||
15 | # You have to make sure that attributes that are containers already |
|
15 | # You have to make sure that attributes that are containers already | |
16 | # exist before using them. Simple assigning a new list will override |
|
16 | # exist before using them. Simple assigning a new list will override | |
17 | # all previous values. |
|
17 | # all previous values. | |
|
18 | ||||
18 | if hasattr(c.Global, 'exec_lines'): |
|
19 | if hasattr(c.Global, 'exec_lines'): | |
19 | c.Global.exec_lines.append(lines) |
|
20 | c.Global.exec_lines.append(lines) | |
20 | else: |
|
21 | else: | |
21 | c.Global.exec_lines = [lines] |
|
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 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Displayhook for IPython. |
|
2 | """Displayhook for IPython. | |
3 |
|
3 | |||
|
4 | This defines a callable class that IPython uses for `sys.displayhook`. | |||
|
5 | ||||
4 | Authors: |
|
6 | Authors: | |
5 |
|
7 | |||
6 | * Fernando Perez |
|
8 | * Fernando Perez | |
7 | * Brian Granger |
|
9 | * Brian Granger | |
|
10 | * Robert Kern | |||
8 | """ |
|
11 | """ | |
9 |
|
12 | |||
10 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2008-2010 The IPython Development Team |
|
14 | # Copyright (C) 2008-2010 The IPython Development Team | |
12 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
13 | # |
|
16 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
18 | # the file COPYING, distributed as part of this software. | |
16 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
17 |
|
20 | |||
18 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
22 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
21 |
|
24 | |||
22 | import __builtin__ |
|
25 | import __builtin__ | |
23 |
|
26 | |||
24 | from IPython.config.configurable import Configurable |
|
27 | from IPython.config.configurable import Configurable | |
25 | from IPython.core import prompts |
|
28 | from IPython.core import prompts | |
26 | import IPython.utils.generics |
|
29 | import IPython.utils.generics | |
27 | import IPython.utils.io |
|
30 | import IPython.utils.io | |
28 | from IPython.utils.traitlets import Instance, List |
|
31 | from IPython.utils.traitlets import Instance, List | |
29 | from IPython.utils.warn import warn |
|
32 | from IPython.utils.warn import warn | |
30 | from IPython.core.formatters import DefaultFormatter |
|
|||
31 |
|
33 | |||
32 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
33 | # Main displayhook class |
|
35 | # Main displayhook class | |
34 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
35 |
|
37 | |||
36 | # TODO: The DisplayHook class should be split into two classes, one that |
|
38 | # TODO: The DisplayHook class should be split into two classes, one that | |
37 | # manages the prompts and their synchronization and another that just does the |
|
39 | # manages the prompts and their synchronization and another that just does the | |
38 | # displayhook logic and calls into the prompt manager. |
|
40 | # displayhook logic and calls into the prompt manager. | |
39 |
|
41 | |||
40 | # TODO: Move the various attributes (cache_size, colors, input_sep, |
|
42 | # TODO: Move the various attributes (cache_size, colors, input_sep, | |
41 | # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also |
|
43 | # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also | |
42 | # attributes of InteractiveShell. They should be on ONE object only and the |
|
44 | # attributes of InteractiveShell. They should be on ONE object only and the | |
43 | # other objects should ask that one object for their values. |
|
45 | # other objects should ask that one object for their values. | |
44 |
|
46 | |||
45 | class DisplayHook(Configurable): |
|
47 | class DisplayHook(Configurable): | |
46 | """The custom IPython displayhook to replace sys.displayhook. |
|
48 | """The custom IPython displayhook to replace sys.displayhook. | |
47 |
|
49 | |||
48 | This class does many things, but the basic idea is that it is a callable |
|
50 | This class does many things, but the basic idea is that it is a callable | |
49 | that gets called anytime user code returns a value. |
|
51 | that gets called anytime user code returns a value. | |
50 |
|
52 | |||
51 | Currently this class does more than just the displayhook logic and that |
|
53 | Currently this class does more than just the displayhook logic and that | |
52 | extra logic should eventually be moved out of here. |
|
54 | extra logic should eventually be moved out of here. | |
53 | """ |
|
55 | """ | |
54 |
|
56 | |||
55 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
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 | def __init__(self, shell=None, cache_size=1000, |
|
59 | def __init__(self, shell=None, cache_size=1000, | |
71 | colors='NoColor', input_sep='\n', |
|
60 | colors='NoColor', input_sep='\n', | |
72 | output_sep='\n', output_sep2='', |
|
61 | output_sep='\n', output_sep2='', | |
73 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, |
|
62 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, | |
74 | config=None): |
|
63 | config=None): | |
75 | super(DisplayHook, self).__init__(shell=shell, config=config) |
|
64 | super(DisplayHook, self).__init__(shell=shell, config=config) | |
76 |
|
65 | |||
77 | cache_size_min = 3 |
|
66 | cache_size_min = 3 | |
78 | if cache_size <= 0: |
|
67 | if cache_size <= 0: | |
79 | self.do_full_cache = 0 |
|
68 | self.do_full_cache = 0 | |
80 | cache_size = 0 |
|
69 | cache_size = 0 | |
81 | elif cache_size < cache_size_min: |
|
70 | elif cache_size < cache_size_min: | |
82 | self.do_full_cache = 0 |
|
71 | self.do_full_cache = 0 | |
83 | cache_size = 0 |
|
72 | cache_size = 0 | |
84 | warn('caching was disabled (min value for cache size is %s).' % |
|
73 | warn('caching was disabled (min value for cache size is %s).' % | |
85 | cache_size_min,level=3) |
|
74 | cache_size_min,level=3) | |
86 | else: |
|
75 | else: | |
87 | self.do_full_cache = 1 |
|
76 | self.do_full_cache = 1 | |
88 |
|
77 | |||
89 | self.cache_size = cache_size |
|
78 | self.cache_size = cache_size | |
90 | self.input_sep = input_sep |
|
79 | self.input_sep = input_sep | |
91 |
|
80 | |||
92 | # we need a reference to the user-level namespace |
|
81 | # we need a reference to the user-level namespace | |
93 | self.shell = shell |
|
82 | self.shell = shell | |
94 |
|
83 | |||
95 | # Set input prompt strings and colors |
|
84 | # Set input prompt strings and colors | |
96 | if cache_size == 0: |
|
85 | if cache_size == 0: | |
97 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ |
|
86 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ | |
98 | or ps1.find(r'\N') > -1: |
|
87 | or ps1.find(r'\N') > -1: | |
99 | ps1 = '>>> ' |
|
88 | ps1 = '>>> ' | |
100 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ |
|
89 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ | |
101 | or ps2.find(r'\N') > -1: |
|
90 | or ps2.find(r'\N') > -1: | |
102 | ps2 = '... ' |
|
91 | ps2 = '... ' | |
103 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') |
|
92 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') | |
104 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') |
|
93 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') | |
105 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') |
|
94 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') | |
106 |
|
95 | |||
107 | self.color_table = prompts.PromptColors |
|
96 | self.color_table = prompts.PromptColors | |
108 | self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str, |
|
97 | self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str, | |
109 | pad_left=pad_left) |
|
98 | pad_left=pad_left) | |
110 | self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) |
|
99 | self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) | |
111 | self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str, |
|
100 | self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str, | |
112 | pad_left=pad_left) |
|
101 | pad_left=pad_left) | |
113 | self.set_colors(colors) |
|
102 | self.set_colors(colors) | |
114 |
|
103 | |||
115 | # Store the last prompt string each time, we need it for aligning |
|
104 | # Store the last prompt string each time, we need it for aligning | |
116 | # continuation and auto-rewrite prompts |
|
105 | # continuation and auto-rewrite prompts | |
117 | self.last_prompt = '' |
|
106 | self.last_prompt = '' | |
118 | self.output_sep = output_sep |
|
107 | self.output_sep = output_sep | |
119 | self.output_sep2 = output_sep2 |
|
108 | self.output_sep2 = output_sep2 | |
120 | self._,self.__,self.___ = '','','' |
|
109 | self._,self.__,self.___ = '','','' | |
121 |
|
110 | |||
122 | # these are deliberately global: |
|
111 | # these are deliberately global: | |
123 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
112 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} | |
124 | self.shell.user_ns.update(to_user_ns) |
|
113 | self.shell.user_ns.update(to_user_ns) | |
125 |
|
114 | |||
126 | @property |
|
115 | @property | |
127 | def prompt_count(self): |
|
116 | def prompt_count(self): | |
128 | return self.shell.execution_count |
|
117 | return self.shell.execution_count | |
129 |
|
118 | |||
130 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): |
|
119 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): | |
131 | if p_str is None: |
|
120 | if p_str is None: | |
132 | if self.do_full_cache: |
|
121 | if self.do_full_cache: | |
133 | return cache_def |
|
122 | return cache_def | |
134 | else: |
|
123 | else: | |
135 | return no_cache_def |
|
124 | return no_cache_def | |
136 | else: |
|
125 | else: | |
137 | return p_str |
|
126 | return p_str | |
138 |
|
127 | |||
139 | def set_colors(self, colors): |
|
128 | def set_colors(self, colors): | |
140 | """Set the active color scheme and configure colors for the three |
|
129 | """Set the active color scheme and configure colors for the three | |
141 | prompt subsystems.""" |
|
130 | prompt subsystems.""" | |
142 |
|
131 | |||
143 | # FIXME: This modifying of the global prompts.prompt_specials needs |
|
132 | # FIXME: This modifying of the global prompts.prompt_specials needs | |
144 | # to be fixed. We need to refactor all of the prompts stuff to use |
|
133 | # to be fixed. We need to refactor all of the prompts stuff to use | |
145 | # proper configuration and traits notifications. |
|
134 | # proper configuration and traits notifications. | |
146 | if colors.lower()=='nocolor': |
|
135 | if colors.lower()=='nocolor': | |
147 | prompts.prompt_specials = prompts.prompt_specials_nocolor |
|
136 | prompts.prompt_specials = prompts.prompt_specials_nocolor | |
148 | else: |
|
137 | else: | |
149 | prompts.prompt_specials = prompts.prompt_specials_color |
|
138 | prompts.prompt_specials = prompts.prompt_specials_color | |
150 |
|
139 | |||
151 | self.color_table.set_active_scheme(colors) |
|
140 | self.color_table.set_active_scheme(colors) | |
152 | self.prompt1.set_colors() |
|
141 | self.prompt1.set_colors() | |
153 | self.prompt2.set_colors() |
|
142 | self.prompt2.set_colors() | |
154 | self.prompt_out.set_colors() |
|
143 | self.prompt_out.set_colors() | |
155 |
|
144 | |||
156 | #------------------------------------------------------------------------- |
|
145 | #------------------------------------------------------------------------- | |
157 | # Methods used in __call__. Override these methods to modify the behavior |
|
146 | # Methods used in __call__. Override these methods to modify the behavior | |
158 | # of the displayhook. |
|
147 | # of the displayhook. | |
159 | #------------------------------------------------------------------------- |
|
148 | #------------------------------------------------------------------------- | |
160 |
|
149 | |||
161 | def check_for_underscore(self): |
|
150 | def check_for_underscore(self): | |
162 | """Check if the user has set the '_' variable by hand.""" |
|
151 | """Check if the user has set the '_' variable by hand.""" | |
163 | # If something injected a '_' variable in __builtin__, delete |
|
152 | # If something injected a '_' variable in __builtin__, delete | |
164 | # ipython's automatic one so we don't clobber that. gettext() in |
|
153 | # ipython's automatic one so we don't clobber that. gettext() in | |
165 | # particular uses _, so we need to stay away from it. |
|
154 | # particular uses _, so we need to stay away from it. | |
166 | if '_' in __builtin__.__dict__: |
|
155 | if '_' in __builtin__.__dict__: | |
167 | try: |
|
156 | try: | |
168 | del self.shell.user_ns['_'] |
|
157 | del self.shell.user_ns['_'] | |
169 | except KeyError: |
|
158 | except KeyError: | |
170 | pass |
|
159 | pass | |
171 |
|
160 | |||
172 | def quiet(self): |
|
161 | def quiet(self): | |
173 | """Should we silence the display hook because of ';'?""" |
|
162 | """Should we silence the display hook because of ';'?""" | |
174 | # do not print output if input ends in ';' |
|
163 | # do not print output if input ends in ';' | |
175 | try: |
|
164 | try: | |
176 | if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'): |
|
165 | if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'): | |
177 | return True |
|
166 | return True | |
178 | except IndexError: |
|
167 | except IndexError: | |
179 | # some uses of ipshellembed may fail here |
|
168 | # some uses of ipshellembed may fail here | |
180 | pass |
|
169 | pass | |
181 | return False |
|
170 | return False | |
182 |
|
171 | |||
183 | def start_displayhook(self): |
|
172 | def start_displayhook(self): | |
184 | """Start the displayhook, initializing resources.""" |
|
173 | """Start the displayhook, initializing resources.""" | |
185 | pass |
|
174 | pass | |
186 |
|
175 | |||
187 | def write_output_prompt(self): |
|
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 | # Use write, not print which adds an extra space. |
|
182 | # Use write, not print which adds an extra space. | |
190 | IPython.utils.io.Term.cout.write(self.output_sep) |
|
183 | IPython.utils.io.Term.cout.write(self.output_sep) | |
191 | outprompt = str(self.prompt_out) |
|
184 | outprompt = str(self.prompt_out) | |
192 | if self.do_full_cache: |
|
185 | if self.do_full_cache: | |
193 | IPython.utils.io.Term.cout.write(outprompt) |
|
186 | IPython.utils.io.Term.cout.write(outprompt) | |
194 |
|
187 | |||
195 |
def compute_ |
|
188 | def compute_format_data(self, result): | |
196 |
"""Compute |
|
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 | actually print or write that to a stream. |
|
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 |
|
|
215 | format_dict = self.shell.display_formatter.format(result) | |
202 |
|
|
216 | return format_dict | |
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)) |
|
|||
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 | # We want to print because we want to always make sure we have a |
|
231 | # We want to print because we want to always make sure we have a | |
216 | # newline, even if all the prompt separators are ''. This is the |
|
232 | # newline, even if all the prompt separators are ''. This is the | |
217 | # standard IPython behavior. |
|
233 | # standard IPython behavior. | |
|
234 | result_repr = format_dict['text/plain'] | |||
218 | if '\n' in result_repr: |
|
235 | if '\n' in result_repr: | |
219 | # So that multi-line strings line up with the left column of |
|
236 | # So that multi-line strings line up with the left column of | |
220 | # the screen, instead of having the output prompt mess up |
|
237 | # the screen, instead of having the output prompt mess up | |
221 | # their first line. |
|
238 | # their first line. | |
222 | # We use the ps_out_str template instead of the expanded prompt |
|
239 | # We use the ps_out_str template instead of the expanded prompt | |
223 | # because the expansion may add ANSI escapes that will interfere |
|
240 | # because the expansion may add ANSI escapes that will interfere | |
224 | # with our ability to determine whether or not we should add |
|
241 | # with our ability to determine whether or not we should add | |
225 | # a newline. |
|
242 | # a newline. | |
226 | if self.ps_out_str and not self.ps_out_str.endswith('\n'): |
|
243 | if self.ps_out_str and not self.ps_out_str.endswith('\n'): | |
227 | # But avoid extraneous empty lines. |
|
244 | # But avoid extraneous empty lines. | |
228 | result_repr = '\n' + result_repr |
|
245 | result_repr = '\n' + result_repr | |
229 |
|
246 | |||
230 | print >>IPython.utils.io.Term.cout, result_repr |
|
247 | print >>IPython.utils.io.Term.cout, result_repr | |
231 |
|
248 | |||
232 | def update_user_ns(self, result): |
|
249 | def update_user_ns(self, result): | |
233 | """Update user_ns with various things like _, __, _1, etc.""" |
|
250 | """Update user_ns with various things like _, __, _1, etc.""" | |
234 |
|
251 | |||
235 | # Avoid recursive reference when displaying _oh/Out |
|
252 | # Avoid recursive reference when displaying _oh/Out | |
236 | if result is not self.shell.user_ns['_oh']: |
|
253 | if result is not self.shell.user_ns['_oh']: | |
237 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
254 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: | |
238 | warn('Output cache limit (currently '+ |
|
255 | warn('Output cache limit (currently '+ | |
239 | `self.cache_size`+' entries) hit.\n' |
|
256 | `self.cache_size`+' entries) hit.\n' | |
240 | 'Flushing cache and resetting history counter...\n' |
|
257 | 'Flushing cache and resetting history counter...\n' | |
241 | 'The only history variables available will be _,__,___ and _1\n' |
|
258 | 'The only history variables available will be _,__,___ and _1\n' | |
242 | 'with the current result.') |
|
259 | 'with the current result.') | |
243 |
|
260 | |||
244 | self.flush() |
|
261 | self.flush() | |
245 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
262 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise | |
246 | # we cause buggy behavior for things like gettext). |
|
263 | # we cause buggy behavior for things like gettext). | |
247 | if '_' not in __builtin__.__dict__: |
|
264 | if '_' not in __builtin__.__dict__: | |
248 | self.___ = self.__ |
|
265 | self.___ = self.__ | |
249 | self.__ = self._ |
|
266 | self.__ = self._ | |
250 | self._ = result |
|
267 | self._ = result | |
251 | self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) |
|
268 | self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) | |
252 |
|
269 | |||
253 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
270 | # hackish access to top-level namespace to create _1,_2... dynamically | |
254 | to_main = {} |
|
271 | to_main = {} | |
255 | if self.do_full_cache: |
|
272 | if self.do_full_cache: | |
256 | new_result = '_'+`self.prompt_count` |
|
273 | new_result = '_'+`self.prompt_count` | |
257 | to_main[new_result] = result |
|
274 | to_main[new_result] = result | |
258 | self.shell.user_ns.update(to_main) |
|
275 | self.shell.user_ns.update(to_main) | |
259 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
276 | self.shell.user_ns['_oh'][self.prompt_count] = result | |
260 |
|
277 | |||
261 | def log_output(self, result): |
|
278 | def log_output(self, result): | |
262 | """Log the output.""" |
|
279 | """Log the output.""" | |
263 | if self.shell.logger.log_output: |
|
280 | if self.shell.logger.log_output: | |
264 | self.shell.logger.log_write(repr(result), 'output') |
|
281 | self.shell.logger.log_write(repr(result), 'output') | |
265 |
|
282 | |||
266 | def finish_displayhook(self): |
|
283 | def finish_displayhook(self): | |
267 | """Finish up all displayhook activities.""" |
|
284 | """Finish up all displayhook activities.""" | |
268 | IPython.utils.io.Term.cout.write(self.output_sep2) |
|
285 | IPython.utils.io.Term.cout.write(self.output_sep2) | |
269 | IPython.utils.io.Term.cout.flush() |
|
286 | IPython.utils.io.Term.cout.flush() | |
270 |
|
287 | |||
271 | def __call__(self, result=None): |
|
288 | def __call__(self, result=None): | |
272 | """Printing with history cache management. |
|
289 | """Printing with history cache management. | |
273 |
|
290 | |||
274 | This is invoked everytime the interpreter needs to print, and is |
|
291 | This is invoked everytime the interpreter needs to print, and is | |
275 | activated by setting the variable sys.displayhook to it. |
|
292 | activated by setting the variable sys.displayhook to it. | |
276 | """ |
|
293 | """ | |
277 | self.check_for_underscore() |
|
294 | self.check_for_underscore() | |
278 | if result is not None and not self.quiet(): |
|
295 | if result is not None and not self.quiet(): | |
279 | self.start_displayhook() |
|
296 | self.start_displayhook() | |
280 | self.write_output_prompt() |
|
297 | self.write_output_prompt() | |
281 |
|
|
298 | format_dict = self.compute_format_data(result) | |
282 | self.write_result_repr(result_repr, extra_formats) |
|
299 | self.write_format_data(format_dict) | |
283 | self.update_user_ns(result) |
|
300 | self.update_user_ns(result) | |
284 | self.log_output(result) |
|
301 | self.log_output(result) | |
285 | self.finish_displayhook() |
|
302 | self.finish_displayhook() | |
286 |
|
303 | |||
287 | def flush(self): |
|
304 | def flush(self): | |
288 | if not self.do_full_cache: |
|
305 | if not self.do_full_cache: | |
289 | raise ValueError,"You shouldn't have reached the cache flush "\ |
|
306 | raise ValueError,"You shouldn't have reached the cache flush "\ | |
290 | "if full caching is not enabled!" |
|
307 | "if full caching is not enabled!" | |
291 | # delete auto-generated vars from global namespace |
|
308 | # delete auto-generated vars from global namespace | |
292 |
|
309 | |||
293 | for n in range(1,self.prompt_count + 1): |
|
310 | for n in range(1,self.prompt_count + 1): | |
294 | key = '_'+`n` |
|
311 | key = '_'+`n` | |
295 | try: |
|
312 | try: | |
296 | del self.shell.user_ns[key] |
|
313 | del self.shell.user_ns[key] | |
297 | except: pass |
|
314 | except: pass | |
298 | self.shell.user_ns['_oh'].clear() |
|
315 | self.shell.user_ns['_oh'].clear() | |
299 |
|
316 | |||
300 | if '_' not in __builtin__.__dict__: |
|
317 | if '_' not in __builtin__.__dict__: | |
301 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
318 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) | |
302 | import gc |
|
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 | """An interface for publishing rich data to frontends. | |
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 | Authors: |
|
14 | Authors: | |
5 |
|
15 | |||
6 | * Brian Granger |
|
16 | * Brian Granger | |
7 | """ |
|
17 | """ | |
8 |
|
18 | |||
9 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
10 | # Copyright (C) 2008-2010 The IPython Development Team |
|
20 | # Copyright (C) 2008-2010 The IPython Development Team | |
11 | # |
|
21 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
22 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
23 | # the file COPYING, distributed as part of this software. | |
14 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
15 |
|
25 | |||
16 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
17 | # Imports |
|
27 | # Imports | |
18 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
19 |
|
29 | |||
20 | from IPython.config.configurable import Configurable |
|
30 | from IPython.config.configurable import Configurable | |
21 |
|
31 | |||
22 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
23 | # Main payload class |
|
33 | # Main payload class | |
24 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
25 |
|
35 | |||
26 | class DisplayPublisher(Configurable): |
|
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 | def _validate_data(self, source, data, metadata=None): |
|
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 | if not isinstance(source, str): |
|
57 | if not isinstance(source, str): | |
30 | raise TypeError('source must be a str, got: %r' % source) |
|
58 | raise TypeError('source must be a str, got: %r' % source) | |
31 | if not isinstance(data, dict): |
|
59 | if not isinstance(data, dict): | |
32 | raise TypeError('data must be a dict, got: %r' % data) |
|
60 | raise TypeError('data must be a dict, got: %r' % data) | |
33 | if metadata is not None: |
|
61 | if metadata is not None: | |
34 | if not isinstance(metadata, dict): |
|
62 | if not isinstance(metadata, dict): | |
35 | raise TypeError('metadata must be a dict, got: %r' % data) |
|
63 | raise TypeError('metadata must be a dict, got: %r' % data) | |
36 |
|
64 | |||
37 | def publish(self, source, data, metadata=None): |
|
65 | def publish(self, source, data, metadata=None): | |
38 | """Publish data and metadata to all frontends. |
|
66 | """Publish data and metadata to all frontends. | |
39 |
|
67 | |||
40 | See the ``display_data`` message in the messaging documentation for |
|
68 | See the ``display_data`` message in the messaging documentation for | |
41 | more details about this message type. |
|
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 | Parameters |
|
80 | Parameters | |
44 | ---------- |
|
81 | ---------- | |
45 | source : str |
|
82 | source : str | |
46 | A string that give the function or method that created the data, |
|
83 | A string that give the function or method that created the data, | |
47 | such as 'IPython.core.page'. |
|
84 | such as 'IPython.core.page'. | |
48 | data : dict |
|
85 | data : dict | |
49 | A dictionary having keys that are valid MIME types (like |
|
86 | A dictionary having keys that are valid MIME types (like | |
50 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
87 | 'text/plain' or 'image/svg+xml') and values that are the data for | |
51 | that MIME type. The data itself must be a JSON'able data |
|
88 | that MIME type. The data itself must be a JSON'able data | |
52 | structure. Minimally all data should have the 'text/plain' data, |
|
89 | structure. Minimally all data should have the 'text/plain' data, | |
53 | which can be displayed by all frontends. If more than the plain |
|
90 | which can be displayed by all frontends. If more than the plain | |
54 | text is given, it is up to the frontend to decide which |
|
91 | text is given, it is up to the frontend to decide which | |
55 | representation to use. |
|
92 | representation to use. | |
56 | metadata : dict |
|
93 | metadata : dict | |
57 | A dictionary for metadata related to the data. This can contain |
|
94 | A dictionary for metadata related to the data. This can contain | |
58 | arbitrary key, value pairs that frontends can use to interpret |
|
95 | arbitrary key, value pairs that frontends can use to interpret | |
59 | the data. |
|
96 | the data. | |
60 | """ |
|
97 | """ | |
61 | from IPython.utils import io |
|
98 | from IPython.utils import io | |
62 | # The default is to simply write the plain text data using io.Term. |
|
99 | # The default is to simply write the plain text data using io.Term. | |
63 | if data.has_key('text/plain'): |
|
100 | if data.has_key('text/plain'): | |
64 | print >>io.Term.cout, data['text/plain'] |
|
101 | print >>io.Term.cout, data['text/plain'] | |
65 |
|
102 | |||
66 |
|
103 | |||
67 |
def publish_display_data(source, |
|
104 | def publish_display_data(self, source, data, metadata=None): | |
68 | html=None, metadata=None): |
|
105 | """Publish data and metadata to all frontends. | |
69 | """Publish a display data to the frontends. |
|
|||
70 |
|
106 | |||
71 | This function is a high level helper for the publishing of display data. |
|
107 | See the ``display_data`` message in the messaging documentation for | |
72 | It handle a number of common MIME types in a clean API. For other MIME |
|
108 | more details about this message type. | |
73 | types, use ``get_ipython().display_pub.publish`` directly. |
|
|||
74 |
|
109 | |||
75 | Parameters |
|
110 | The following MIME types are currently implemented: | |
76 | ---------- |
|
|||
77 | text : str/unicode |
|
|||
78 | The string representation of the plot. |
|
|||
79 |
|
111 | |||
80 | svn : str/unicode |
|
112 | * text/plain | |
81 | The raw svg data of the plot. |
|
113 | * text/html | |
|
114 | * text/latex | |||
|
115 | * application/json | |||
|
116 | * image/png | |||
|
117 | * immage/svg+xml | |||
82 |
|
118 | |||
83 | png : ??? |
|
119 | Parameters | |
84 | The raw png data of the plot. |
|
120 | ---------- | |
85 |
|
121 | source : str | ||
86 | metadata : dict, optional [default empty] |
|
122 | A string that give the function or method that created the data, | |
87 | Allows for specification of additional information about the plot 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 | from IPython.core.interactiveshell import InteractiveShell |
|
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 | InteractiveShell.instance().display_pub.publish( |
|
138 | InteractiveShell.instance().display_pub.publish( | |
100 | source, |
|
139 | source, | |
101 |
data |
|
140 | data, | |
102 | metadata |
|
141 | metadata | |
103 | ) |
|
142 | ) | |
|
143 |
@@ -1,169 +1,453 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
"""Display |
|
2 | """Display formatters. | |
3 |
|
3 | |||
4 | The DefaultFormatter is always present and may be configured from the |
|
4 | ||
5 | ipython_config.py file. For example, to add a pretty-printer for a numpy.dtype |
|
5 | Authors: | |
6 | object:: |
|
6 | ||
7 |
|
7 | * Robert Kern | ||
8 | def dtype_pprinter(obj, p, cycle): |
|
8 | * Brian Granger | |
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. |
|
|||
34 | """ |
|
9 | """ | |
35 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
36 | # Copyright (c) 2010, IPython Development Team. |
|
11 | # Copyright (c) 2010, IPython Development Team. | |
37 | # |
|
12 | # | |
38 | # Distributed under the terms of the Modified BSD License. |
|
13 | # Distributed under the terms of the Modified BSD License. | |
39 | # |
|
14 | # | |
40 | # The full license is in the file COPYING.txt, distributed with this software. |
|
15 | # The full license is in the file COPYING.txt, distributed with this software. | |
41 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
42 |
|
17 | |||
43 | # Stdlib imports |
|
18 | # Stdlib imports | |
44 | import abc |
|
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 | # Our own imports |
|
23 | # Our own imports | |
48 | from IPython.config.configurable import Configurable |
|
24 | from IPython.config.configurable import Configurable | |
49 | from IPython.external import pretty |
|
25 | from IPython.external import pretty | |
50 | from IPython.utils.traitlets import Bool, Dict, Int, Str |
|
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): |
|
33 | ||
58 | """ The default pretty-printer. |
|
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. |
|
129 | # The format type of the data returned, usually a MIME type. | |
62 | id = Str('default') |
|
130 | format_type = 'text/plain' | |
63 |
|
131 | |||
64 | # The kind of data returned. |
|
132 | @abc.abstractmethod | |
65 | # This is often, but not always a MIME type. |
|
133 | def __call__(self, obj): | |
66 | format = Str('text/plain') |
|
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 | # Whether to pretty-print or not. |
|
293 | # Whether to pretty-print or not. | |
69 | pprint = Bool(True, config=True) |
|
294 | pprint = Bool(True, config=True) | |
70 |
|
295 | |||
71 | # Whether to be verbose or not. |
|
296 | # Whether to be verbose or not. | |
72 | verbose = Bool(False, config=True) |
|
297 | verbose = Bool(False, config=True) | |
73 |
|
298 | |||
74 | # The maximum width. |
|
299 | # The maximum width. | |
75 | max_width = Int(79, config=True) |
|
300 | max_width = Int(79, config=True) | |
76 |
|
301 | |||
77 | # The newline character. |
|
302 | # The newline character. | |
78 | newline = Str('\n', config=True) |
|
303 | newline = Str('\n', config=True) | |
79 |
|
304 | |||
80 | # The singleton prettyprinters. |
|
305 | # Use the default pretty printers from IPython.external.pretty. | |
81 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
306 | def _singleton_printers_default(self): | |
82 | singleton_pprinters = Dict(config=True) |
|
|||
83 | def _singleton_pprinters_default(self): |
|
|||
84 | return pretty._singleton_pprinters.copy() |
|
307 | return pretty._singleton_pprinters.copy() | |
85 |
|
308 | |||
86 | # The type-specific prettyprinters. |
|
309 | def _type_printers_default(self): | |
87 | # Map type objects to the format functions. |
|
|||
88 | type_pprinters = Dict(config=True) |
|
|||
89 | def _type_pprinters_default(self): |
|
|||
90 | return pretty._type_pprinters.copy() |
|
310 | return pretty._type_pprinters.copy() | |
91 |
|
311 | |||
92 | # The deferred-import type-specific prettyprinters. |
|
312 | def _deferred_printers_default(self): | |
93 | # Map (modulename, classname) pairs to the format functions. |
|
|||
94 | deferred_pprinters = Dict(config=True) |
|
|||
95 | def _deferred_pprinters_default(self): |
|
|||
96 | return pretty._deferred_type_pprinters.copy() |
|
313 | return pretty._deferred_type_pprinters.copy() | |
97 |
|
314 | |||
98 | #### FormatterABC interface #### |
|
315 | #### FormatterABC interface #### | |
99 |
|
316 | |||
100 | def __call__(self, obj): |
|
317 | def __call__(self, obj): | |
101 | """ Format the object. |
|
318 | """Compute the pretty representation of the object.""" | |
102 | """ |
|
|||
103 | if not self.pprint: |
|
319 | if not self.pprint: | |
104 | try: |
|
320 | try: | |
105 | return repr(obj) |
|
321 | return repr(obj) | |
106 | except TypeError: |
|
322 | except TypeError: | |
107 | return '' |
|
323 | return '' | |
108 | else: |
|
324 | else: | |
|
325 | # This uses use StringIO, as cStringIO doesn't handle unicode. | |||
109 | stream = StringIO() |
|
326 | stream = StringIO() | |
110 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
327 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
111 | self.max_width, self.newline, |
|
328 | self.max_width, self.newline, | |
112 |
singleton_pprinters=self.singleton_p |
|
329 | singleton_pprinters=self.singleton_printers, | |
113 |
type_pprinters=self.type_p |
|
330 | type_pprinters=self.type_printers, | |
114 |
deferred_pprinters=self.deferred_p |
|
331 | deferred_pprinters=self.deferred_printers) | |
115 | printer.pretty(obj) |
|
332 | printer.pretty(obj) | |
116 | printer.flush() |
|
333 | printer.flush() | |
117 | return stream.getvalue() |
|
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): |
|
340 | To define the callables that compute the HTML representation of your | |
123 | """ |
|
341 | objects, define a :meth:`__html__` method or use the :meth:`for_type` | |
124 | Add a pretty printer for a given type. |
|
342 | or :meth:`for_type_by_name` methods to register functions that handle | |
125 | """ |
|
343 | this. | |
126 | oldfunc = self.type_pprinters.get(typ, None) |
|
344 | """ | |
127 | if func is not None: |
|
345 | format_type = Str('text/html') | |
128 | # To support easy restoration of old pprinters, we need to ignore |
|
|||
129 | # Nones. |
|
|||
130 | self.type_pprinters[typ] = func |
|
|||
131 | return oldfunc |
|
|||
132 |
|
346 | |||
133 | def for_type_by_name(self, type_module, type_name, func): |
|
347 | print_method = Str('__html__') | |
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 |
|
|||
145 |
|
348 | |||
146 |
|
349 | |||
147 |
class Formatter |
|
350 | class SVGFormatter(BaseFormatter): | |
148 | """ Abstract base class for Formatters. |
|
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. |
|
360 | print_method = Str('__svg__') | |
153 | id = 'abstract' |
|
|||
154 |
|
361 | |||
155 | # The kind of data returned. |
|
|||
156 | format = 'text/plain' |
|
|||
157 |
|
362 | |||
158 | @abc.abstractmethod |
|
363 | class PNGFormatter(BaseFormatter): | |
159 | def __call__(self, obj): |
|
364 | """A PNG formatter. | |
160 | """ Return a JSONable representation of the object. |
|
|||
161 |
|
365 | |||
162 | If the object cannot be formatted by this formatter, then return None |
|
366 | To define the callables that compute the PNG representation of your | |
163 | """ |
|
367 | objects, define a :meth:`__svg__` method or use the :meth:`for_type` | |
164 | try: |
|
368 | or :meth:`for_type_by_name` methods to register functions that handle | |
165 | return repr(obj) |
|
369 | this. The raw data should be the base64 encoded raw png data. | |
166 | except TypeError: |
|
370 | """ | |
167 | return None |
|
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 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | from __future__ import with_statement |
|
17 | from __future__ import with_statement | |
18 | from __future__ import absolute_import |
|
18 | from __future__ import absolute_import | |
19 |
|
19 | |||
20 | import __builtin__ |
|
20 | import __builtin__ | |
21 | import __future__ |
|
21 | import __future__ | |
22 | import abc |
|
22 | import abc | |
23 | import atexit |
|
23 | import atexit | |
24 | import codeop |
|
24 | import codeop | |
25 | import os |
|
25 | import os | |
26 | import re |
|
26 | import re | |
27 | import sys |
|
27 | import sys | |
28 | import tempfile |
|
28 | import tempfile | |
29 | import types |
|
29 | import types | |
30 | from contextlib import nested |
|
30 | from contextlib import nested | |
31 |
|
31 | |||
32 | from IPython.config.configurable import Configurable |
|
32 | from IPython.config.configurable import Configurable | |
33 | from IPython.core import debugger, oinspect |
|
33 | from IPython.core import debugger, oinspect | |
34 | from IPython.core import history as ipcorehist |
|
34 | from IPython.core import history as ipcorehist | |
35 | from IPython.core import page |
|
35 | from IPython.core import page | |
36 | from IPython.core import prefilter |
|
36 | from IPython.core import prefilter | |
37 | from IPython.core import shadowns |
|
37 | from IPython.core import shadowns | |
38 | from IPython.core import ultratb |
|
38 | from IPython.core import ultratb | |
39 | from IPython.core.alias import AliasManager |
|
39 | from IPython.core.alias import AliasManager | |
40 | from IPython.core.builtin_trap import BuiltinTrap |
|
40 | from IPython.core.builtin_trap import BuiltinTrap | |
41 | from IPython.core.compilerop import CachingCompiler |
|
41 | from IPython.core.compilerop import CachingCompiler | |
42 | from IPython.core.display_trap import DisplayTrap |
|
42 | from IPython.core.display_trap import DisplayTrap | |
43 | from IPython.core.displayhook import DisplayHook |
|
43 | from IPython.core.displayhook import DisplayHook | |
44 | from IPython.core.displaypub import DisplayPublisher |
|
44 | from IPython.core.displaypub import DisplayPublisher | |
45 | from IPython.core.error import TryNext, UsageError |
|
45 | from IPython.core.error import TryNext, UsageError | |
46 | from IPython.core.extensions import ExtensionManager |
|
46 | from IPython.core.extensions import ExtensionManager | |
47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
|
48 | from IPython.core.formatters import DisplayFormatter | |||
48 | from IPython.core.history import HistoryManager |
|
49 | from IPython.core.history import HistoryManager | |
49 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
50 | from IPython.core.inputsplitter import IPythonInputSplitter | |
50 | from IPython.core.logger import Logger |
|
51 | from IPython.core.logger import Logger | |
51 | from IPython.core.magic import Magic |
|
52 | from IPython.core.magic import Magic | |
52 | from IPython.core.payload import PayloadManager |
|
53 | from IPython.core.payload import PayloadManager | |
53 | from IPython.core.plugin import PluginManager |
|
54 | from IPython.core.plugin import PluginManager | |
54 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
55 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
55 | from IPython.external.Itpl import ItplNS |
|
56 | from IPython.external.Itpl import ItplNS | |
56 | from IPython.utils import PyColorize |
|
57 | from IPython.utils import PyColorize | |
57 | from IPython.utils import io |
|
58 | from IPython.utils import io | |
58 | from IPython.utils import pickleshare |
|
59 | from IPython.utils import pickleshare | |
59 | from IPython.utils.doctestreload import doctest_reload |
|
60 | from IPython.utils.doctestreload import doctest_reload | |
60 | from IPython.utils.io import ask_yes_no, rprint |
|
61 | from IPython.utils.io import ask_yes_no, rprint | |
61 | from IPython.utils.ipstruct import Struct |
|
62 | from IPython.utils.ipstruct import Struct | |
62 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
63 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
63 | from IPython.utils.process import system, getoutput |
|
64 | from IPython.utils.process import system, getoutput | |
64 | from IPython.utils.strdispatch import StrDispatch |
|
65 | from IPython.utils.strdispatch import StrDispatch | |
65 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
66 | from IPython.utils.syspathcontext import prepended_to_syspath | |
66 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
67 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList | |
67 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
68 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
68 | List, Unicode, Instance, Type) |
|
69 | List, Unicode, Instance, Type) | |
69 | from IPython.utils.warn import warn, error, fatal |
|
70 | from IPython.utils.warn import warn, error, fatal | |
70 | import IPython.core.hooks |
|
71 | import IPython.core.hooks | |
71 |
|
72 | |||
72 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
73 | # Globals |
|
74 | # Globals | |
74 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
75 |
|
76 | |||
76 | # compiled regexps for autoindent management |
|
77 | # compiled regexps for autoindent management | |
77 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
78 |
|
79 | |||
79 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
80 | # Utilities |
|
81 | # Utilities | |
81 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
82 |
|
83 | |||
83 | # store the builtin raw_input globally, and use this always, in case user code |
|
84 | # store the builtin raw_input globally, and use this always, in case user code | |
84 | # overwrites it (like wx.py.PyShell does) |
|
85 | # overwrites it (like wx.py.PyShell does) | |
85 | raw_input_original = raw_input |
|
86 | raw_input_original = raw_input | |
86 |
|
87 | |||
87 | def softspace(file, newvalue): |
|
88 | def softspace(file, newvalue): | |
88 | """Copied from code.py, to remove the dependency""" |
|
89 | """Copied from code.py, to remove the dependency""" | |
89 |
|
90 | |||
90 | oldvalue = 0 |
|
91 | oldvalue = 0 | |
91 | try: |
|
92 | try: | |
92 | oldvalue = file.softspace |
|
93 | oldvalue = file.softspace | |
93 | except AttributeError: |
|
94 | except AttributeError: | |
94 | pass |
|
95 | pass | |
95 | try: |
|
96 | try: | |
96 | file.softspace = newvalue |
|
97 | file.softspace = newvalue | |
97 | except (AttributeError, TypeError): |
|
98 | except (AttributeError, TypeError): | |
98 | # "attribute-less object" or "read-only attributes" |
|
99 | # "attribute-less object" or "read-only attributes" | |
99 | pass |
|
100 | pass | |
100 | return oldvalue |
|
101 | return oldvalue | |
101 |
|
102 | |||
102 |
|
103 | |||
103 | def no_op(*a, **kw): pass |
|
104 | def no_op(*a, **kw): pass | |
104 |
|
105 | |||
105 | class SpaceInInput(Exception): pass |
|
106 | class SpaceInInput(Exception): pass | |
106 |
|
107 | |||
107 | class Bunch: pass |
|
108 | class Bunch: pass | |
108 |
|
109 | |||
109 |
|
110 | |||
110 | def get_default_colors(): |
|
111 | def get_default_colors(): | |
111 | if sys.platform=='darwin': |
|
112 | if sys.platform=='darwin': | |
112 | return "LightBG" |
|
113 | return "LightBG" | |
113 | elif os.name=='nt': |
|
114 | elif os.name=='nt': | |
114 | return 'Linux' |
|
115 | return 'Linux' | |
115 | else: |
|
116 | else: | |
116 | return 'Linux' |
|
117 | return 'Linux' | |
117 |
|
118 | |||
118 |
|
119 | |||
119 | class SeparateStr(Str): |
|
120 | class SeparateStr(Str): | |
120 | """A Str subclass to validate separate_in, separate_out, etc. |
|
121 | """A Str subclass to validate separate_in, separate_out, etc. | |
121 |
|
122 | |||
122 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
123 | """ |
|
124 | """ | |
124 |
|
125 | |||
125 | def validate(self, obj, value): |
|
126 | def validate(self, obj, value): | |
126 | if value == '0': value = '' |
|
127 | if value == '0': value = '' | |
127 | value = value.replace('\\n','\n') |
|
128 | value = value.replace('\\n','\n') | |
128 | return super(SeparateStr, self).validate(obj, value) |
|
129 | return super(SeparateStr, self).validate(obj, value) | |
129 |
|
130 | |||
130 | class MultipleInstanceError(Exception): |
|
131 | class MultipleInstanceError(Exception): | |
131 | pass |
|
132 | pass | |
132 |
|
133 | |||
133 |
|
134 | |||
134 | #----------------------------------------------------------------------------- |
|
135 | #----------------------------------------------------------------------------- | |
135 | # Main IPython class |
|
136 | # Main IPython class | |
136 | #----------------------------------------------------------------------------- |
|
137 | #----------------------------------------------------------------------------- | |
137 |
|
138 | |||
138 | class InteractiveShell(Configurable, Magic): |
|
139 | class InteractiveShell(Configurable, Magic): | |
139 | """An enhanced, interactive shell for Python.""" |
|
140 | """An enhanced, interactive shell for Python.""" | |
140 |
|
141 | |||
141 | _instance = None |
|
142 | _instance = None | |
142 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
143 | autocall = Enum((0,1,2), default_value=1, config=True) | |
143 | # TODO: remove all autoindent logic and put into frontends. |
|
144 | # TODO: remove all autoindent logic and put into frontends. | |
144 | # We can't do this yet because even runlines uses the autoindent. |
|
145 | # We can't do this yet because even runlines uses the autoindent. | |
145 | autoindent = CBool(True, config=True) |
|
146 | autoindent = CBool(True, config=True) | |
146 | automagic = CBool(True, config=True) |
|
147 | automagic = CBool(True, config=True) | |
147 | cache_size = Int(1000, config=True) |
|
148 | cache_size = Int(1000, config=True) | |
148 | color_info = CBool(True, config=True) |
|
149 | color_info = CBool(True, config=True) | |
149 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
150 | default_value=get_default_colors(), config=True) |
|
151 | default_value=get_default_colors(), config=True) | |
151 | debug = CBool(False, config=True) |
|
152 | debug = CBool(False, config=True) | |
152 | deep_reload = CBool(False, config=True) |
|
153 | deep_reload = CBool(False, config=True) | |
|
154 | display_formatter = Instance(DisplayFormatter) | |||
153 | displayhook_class = Type(DisplayHook) |
|
155 | displayhook_class = Type(DisplayHook) | |
154 | display_pub_class = Type(DisplayPublisher) |
|
156 | display_pub_class = Type(DisplayPublisher) | |
155 |
|
157 | |||
156 | exit_now = CBool(False) |
|
158 | exit_now = CBool(False) | |
157 | # Monotonically increasing execution counter |
|
159 | # Monotonically increasing execution counter | |
158 | execution_count = Int(1) |
|
160 | execution_count = Int(1) | |
159 | filename = Str("<ipython console>") |
|
161 | filename = Str("<ipython console>") | |
160 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
162 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
161 |
|
163 | |||
162 | # Input splitter, to split entire cells of input into either individual |
|
164 | # Input splitter, to split entire cells of input into either individual | |
163 | # interactive statements or whole blocks. |
|
165 | # interactive statements or whole blocks. | |
164 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
166 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
165 | (), {}) |
|
167 | (), {}) | |
166 | logstart = CBool(False, config=True) |
|
168 | logstart = CBool(False, config=True) | |
167 | logfile = Str('', config=True) |
|
169 | logfile = Str('', config=True) | |
168 | logappend = Str('', config=True) |
|
170 | logappend = Str('', config=True) | |
169 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
171 | object_info_string_level = Enum((0,1,2), default_value=0, | |
170 | config=True) |
|
172 | config=True) | |
171 | pdb = CBool(False, config=True) |
|
173 | pdb = CBool(False, config=True) | |
172 |
|
174 | |||
173 | pprint = CBool(True, config=True) |
|
175 | pprint = CBool(True, config=True) | |
174 | profile = Str('', config=True) |
|
176 | profile = Str('', config=True) | |
175 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
177 | prompt_in1 = Str('In [\\#]: ', config=True) | |
176 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
178 | prompt_in2 = Str(' .\\D.: ', config=True) | |
177 | prompt_out = Str('Out[\\#]: ', config=True) |
|
179 | prompt_out = Str('Out[\\#]: ', config=True) | |
178 | prompts_pad_left = CBool(True, config=True) |
|
180 | prompts_pad_left = CBool(True, config=True) | |
179 | quiet = CBool(False, config=True) |
|
181 | quiet = CBool(False, config=True) | |
180 |
|
182 | |||
181 | history_length = Int(10000, config=True) |
|
183 | history_length = Int(10000, config=True) | |
182 |
|
184 | |||
183 | # The readline stuff will eventually be moved to the terminal subclass |
|
185 | # The readline stuff will eventually be moved to the terminal subclass | |
184 | # but for now, we can't do that as readline is welded in everywhere. |
|
186 | # but for now, we can't do that as readline is welded in everywhere. | |
185 | readline_use = CBool(True, config=True) |
|
187 | readline_use = CBool(True, config=True) | |
186 | readline_merge_completions = CBool(True, config=True) |
|
188 | readline_merge_completions = CBool(True, config=True) | |
187 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
189 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) | |
188 | readline_remove_delims = Str('-/~', config=True) |
|
190 | readline_remove_delims = Str('-/~', config=True) | |
189 | readline_parse_and_bind = List([ |
|
191 | readline_parse_and_bind = List([ | |
190 | 'tab: complete', |
|
192 | 'tab: complete', | |
191 | '"\C-l": clear-screen', |
|
193 | '"\C-l": clear-screen', | |
192 | 'set show-all-if-ambiguous on', |
|
194 | 'set show-all-if-ambiguous on', | |
193 | '"\C-o": tab-insert', |
|
195 | '"\C-o": tab-insert', | |
194 | '"\M-i": " "', |
|
196 | '"\M-i": " "', | |
195 | '"\M-o": "\d\d\d\d"', |
|
197 | '"\M-o": "\d\d\d\d"', | |
196 | '"\M-I": "\d\d\d\d"', |
|
198 | '"\M-I": "\d\d\d\d"', | |
197 | '"\C-r": reverse-search-history', |
|
199 | '"\C-r": reverse-search-history', | |
198 | '"\C-s": forward-search-history', |
|
200 | '"\C-s": forward-search-history', | |
199 | '"\C-p": history-search-backward', |
|
201 | '"\C-p": history-search-backward', | |
200 | '"\C-n": history-search-forward', |
|
202 | '"\C-n": history-search-forward', | |
201 | '"\e[A": history-search-backward', |
|
203 | '"\e[A": history-search-backward', | |
202 | '"\e[B": history-search-forward', |
|
204 | '"\e[B": history-search-forward', | |
203 | '"\C-k": kill-line', |
|
205 | '"\C-k": kill-line', | |
204 | '"\C-u": unix-line-discard', |
|
206 | '"\C-u": unix-line-discard', | |
205 | ], allow_none=False, config=True) |
|
207 | ], allow_none=False, config=True) | |
206 |
|
208 | |||
207 | # TODO: this part of prompt management should be moved to the frontends. |
|
209 | # TODO: this part of prompt management should be moved to the frontends. | |
208 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
210 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
209 | separate_in = SeparateStr('\n', config=True) |
|
211 | separate_in = SeparateStr('\n', config=True) | |
210 | separate_out = SeparateStr('', config=True) |
|
212 | separate_out = SeparateStr('', config=True) | |
211 | separate_out2 = SeparateStr('', config=True) |
|
213 | separate_out2 = SeparateStr('', config=True) | |
212 | wildcards_case_sensitive = CBool(True, config=True) |
|
214 | wildcards_case_sensitive = CBool(True, config=True) | |
213 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
215 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
214 | default_value='Context', config=True) |
|
216 | default_value='Context', config=True) | |
215 |
|
217 | |||
216 | # Subcomponents of InteractiveShell |
|
218 | # Subcomponents of InteractiveShell | |
217 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
219 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
218 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
220 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
219 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
221 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
220 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
222 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
221 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
223 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
222 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
224 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
223 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
225 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
224 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
226 | history_manager = Instance('IPython.core.history.HistoryManager') | |
225 |
|
227 | |||
226 | # Private interface |
|
228 | # Private interface | |
227 | _post_execute = set() |
|
229 | _post_execute = set() | |
228 |
|
230 | |||
229 | def __init__(self, config=None, ipython_dir=None, |
|
231 | def __init__(self, config=None, ipython_dir=None, | |
230 | user_ns=None, user_global_ns=None, |
|
232 | user_ns=None, user_global_ns=None, | |
231 | custom_exceptions=((), None)): |
|
233 | custom_exceptions=((), None)): | |
232 |
|
234 | |||
233 | # This is where traits with a config_key argument are updated |
|
235 | # This is where traits with a config_key argument are updated | |
234 | # from the values on config. |
|
236 | # from the values on config. | |
235 | super(InteractiveShell, self).__init__(config=config) |
|
237 | super(InteractiveShell, self).__init__(config=config) | |
236 |
|
238 | |||
237 | # These are relatively independent and stateless |
|
239 | # These are relatively independent and stateless | |
238 | self.init_ipython_dir(ipython_dir) |
|
240 | self.init_ipython_dir(ipython_dir) | |
239 | self.init_instance_attrs() |
|
241 | self.init_instance_attrs() | |
240 | self.init_environment() |
|
242 | self.init_environment() | |
241 |
|
243 | |||
242 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
244 | # Create namespaces (user_ns, user_global_ns, etc.) | |
243 | self.init_create_namespaces(user_ns, user_global_ns) |
|
245 | self.init_create_namespaces(user_ns, user_global_ns) | |
244 | # This has to be done after init_create_namespaces because it uses |
|
246 | # This has to be done after init_create_namespaces because it uses | |
245 | # something in self.user_ns, but before init_sys_modules, which |
|
247 | # something in self.user_ns, but before init_sys_modules, which | |
246 | # is the first thing to modify sys. |
|
248 | # is the first thing to modify sys. | |
247 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
249 | # TODO: When we override sys.stdout and sys.stderr before this class | |
248 | # is created, we are saving the overridden ones here. Not sure if this |
|
250 | # is created, we are saving the overridden ones here. Not sure if this | |
249 | # is what we want to do. |
|
251 | # is what we want to do. | |
250 | self.save_sys_module_state() |
|
252 | self.save_sys_module_state() | |
251 | self.init_sys_modules() |
|
253 | self.init_sys_modules() | |
252 |
|
254 | |||
253 | self.init_history() |
|
255 | self.init_history() | |
254 | self.init_encoding() |
|
256 | self.init_encoding() | |
255 | self.init_prefilter() |
|
257 | self.init_prefilter() | |
256 |
|
258 | |||
257 | Magic.__init__(self, self) |
|
259 | Magic.__init__(self, self) | |
258 |
|
260 | |||
259 | self.init_syntax_highlighting() |
|
261 | self.init_syntax_highlighting() | |
260 | self.init_hooks() |
|
262 | self.init_hooks() | |
261 | self.init_pushd_popd_magic() |
|
263 | self.init_pushd_popd_magic() | |
262 | # self.init_traceback_handlers use to be here, but we moved it below |
|
264 | # self.init_traceback_handlers use to be here, but we moved it below | |
263 | # because it and init_io have to come after init_readline. |
|
265 | # because it and init_io have to come after init_readline. | |
264 | self.init_user_ns() |
|
266 | self.init_user_ns() | |
265 | self.init_logger() |
|
267 | self.init_logger() | |
266 | self.init_alias() |
|
268 | self.init_alias() | |
267 | self.init_builtins() |
|
269 | self.init_builtins() | |
268 |
|
270 | |||
269 | # pre_config_initialization |
|
271 | # pre_config_initialization | |
270 |
|
272 | |||
271 | # The next section should contain everything that was in ipmaker. |
|
273 | # The next section should contain everything that was in ipmaker. | |
272 | self.init_logstart() |
|
274 | self.init_logstart() | |
273 |
|
275 | |||
274 | # The following was in post_config_initialization |
|
276 | # The following was in post_config_initialization | |
275 | self.init_inspector() |
|
277 | self.init_inspector() | |
276 | # init_readline() must come before init_io(), because init_io uses |
|
278 | # init_readline() must come before init_io(), because init_io uses | |
277 | # readline related things. |
|
279 | # readline related things. | |
278 | self.init_readline() |
|
280 | self.init_readline() | |
279 | # init_completer must come after init_readline, because it needs to |
|
281 | # init_completer must come after init_readline, because it needs to | |
280 | # know whether readline is present or not system-wide to configure the |
|
282 | # know whether readline is present or not system-wide to configure the | |
281 | # completers, since the completion machinery can now operate |
|
283 | # completers, since the completion machinery can now operate | |
282 | # independently of readline (e.g. over the network) |
|
284 | # independently of readline (e.g. over the network) | |
283 | self.init_completer() |
|
285 | self.init_completer() | |
284 | # TODO: init_io() needs to happen before init_traceback handlers |
|
286 | # TODO: init_io() needs to happen before init_traceback handlers | |
285 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
287 | # because the traceback handlers hardcode the stdout/stderr streams. | |
286 | # This logic in in debugger.Pdb and should eventually be changed. |
|
288 | # This logic in in debugger.Pdb and should eventually be changed. | |
287 | self.init_io() |
|
289 | self.init_io() | |
288 | self.init_traceback_handlers(custom_exceptions) |
|
290 | self.init_traceback_handlers(custom_exceptions) | |
289 | self.init_prompts() |
|
291 | self.init_prompts() | |
|
292 | self.init_display_formatter() | |||
290 | self.init_display_pub() |
|
293 | self.init_display_pub() | |
291 | self.init_displayhook() |
|
294 | self.init_displayhook() | |
292 | self.init_reload_doctest() |
|
295 | self.init_reload_doctest() | |
293 | self.init_magics() |
|
296 | self.init_magics() | |
294 | self.init_pdb() |
|
297 | self.init_pdb() | |
295 | self.init_extension_manager() |
|
298 | self.init_extension_manager() | |
296 | self.init_plugin_manager() |
|
299 | self.init_plugin_manager() | |
297 | self.init_payload() |
|
300 | self.init_payload() | |
298 | self.hooks.late_startup_hook() |
|
301 | self.hooks.late_startup_hook() | |
299 | atexit.register(self.atexit_operations) |
|
302 | atexit.register(self.atexit_operations) | |
300 |
|
303 | |||
301 | # While we're trying to have each part of the code directly access what it |
|
304 | # While we're trying to have each part of the code directly access what it | |
302 | # needs without keeping redundant references to objects, we have too much |
|
305 | # needs without keeping redundant references to objects, we have too much | |
303 | # legacy code that expects ip.db to exist, so let's make it a property that |
|
306 | # legacy code that expects ip.db to exist, so let's make it a property that | |
304 | # retrieves the underlying object from our new history manager. |
|
307 | # retrieves the underlying object from our new history manager. | |
305 | @property |
|
308 | @property | |
306 | def db(self): |
|
309 | def db(self): | |
307 | return self.history_manager.shadow_db |
|
310 | return self.history_manager.shadow_db | |
308 |
|
311 | |||
309 | @classmethod |
|
312 | @classmethod | |
310 | def instance(cls, *args, **kwargs): |
|
313 | def instance(cls, *args, **kwargs): | |
311 | """Returns a global InteractiveShell instance.""" |
|
314 | """Returns a global InteractiveShell instance.""" | |
312 | if cls._instance is None: |
|
315 | if cls._instance is None: | |
313 | inst = cls(*args, **kwargs) |
|
316 | inst = cls(*args, **kwargs) | |
314 | # Now make sure that the instance will also be returned by |
|
317 | # Now make sure that the instance will also be returned by | |
315 | # the subclasses instance attribute. |
|
318 | # the subclasses instance attribute. | |
316 | for subclass in cls.mro(): |
|
319 | for subclass in cls.mro(): | |
317 | if issubclass(cls, subclass) and \ |
|
320 | if issubclass(cls, subclass) and \ | |
318 | issubclass(subclass, InteractiveShell): |
|
321 | issubclass(subclass, InteractiveShell): | |
319 | subclass._instance = inst |
|
322 | subclass._instance = inst | |
320 | else: |
|
323 | else: | |
321 | break |
|
324 | break | |
322 | if isinstance(cls._instance, cls): |
|
325 | if isinstance(cls._instance, cls): | |
323 | return cls._instance |
|
326 | return cls._instance | |
324 | else: |
|
327 | else: | |
325 | raise MultipleInstanceError( |
|
328 | raise MultipleInstanceError( | |
326 | 'Multiple incompatible subclass instances of ' |
|
329 | 'Multiple incompatible subclass instances of ' | |
327 | 'InteractiveShell are being created.' |
|
330 | 'InteractiveShell are being created.' | |
328 | ) |
|
331 | ) | |
329 |
|
332 | |||
330 | @classmethod |
|
333 | @classmethod | |
331 | def initialized(cls): |
|
334 | def initialized(cls): | |
332 | return hasattr(cls, "_instance") |
|
335 | return hasattr(cls, "_instance") | |
333 |
|
336 | |||
334 | def get_ipython(self): |
|
337 | def get_ipython(self): | |
335 | """Return the currently running IPython instance.""" |
|
338 | """Return the currently running IPython instance.""" | |
336 | return self |
|
339 | return self | |
337 |
|
340 | |||
338 | #------------------------------------------------------------------------- |
|
341 | #------------------------------------------------------------------------- | |
339 | # Trait changed handlers |
|
342 | # Trait changed handlers | |
340 | #------------------------------------------------------------------------- |
|
343 | #------------------------------------------------------------------------- | |
341 |
|
344 | |||
342 | def _ipython_dir_changed(self, name, new): |
|
345 | def _ipython_dir_changed(self, name, new): | |
343 | if not os.path.isdir(new): |
|
346 | if not os.path.isdir(new): | |
344 | os.makedirs(new, mode = 0777) |
|
347 | os.makedirs(new, mode = 0777) | |
345 |
|
348 | |||
346 | def set_autoindent(self,value=None): |
|
349 | def set_autoindent(self,value=None): | |
347 | """Set the autoindent flag, checking for readline support. |
|
350 | """Set the autoindent flag, checking for readline support. | |
348 |
|
351 | |||
349 | If called with no arguments, it acts as a toggle.""" |
|
352 | If called with no arguments, it acts as a toggle.""" | |
350 |
|
353 | |||
351 | if not self.has_readline: |
|
354 | if not self.has_readline: | |
352 | if os.name == 'posix': |
|
355 | if os.name == 'posix': | |
353 | warn("The auto-indent feature requires the readline library") |
|
356 | warn("The auto-indent feature requires the readline library") | |
354 | self.autoindent = 0 |
|
357 | self.autoindent = 0 | |
355 | return |
|
358 | return | |
356 | if value is None: |
|
359 | if value is None: | |
357 | self.autoindent = not self.autoindent |
|
360 | self.autoindent = not self.autoindent | |
358 | else: |
|
361 | else: | |
359 | self.autoindent = value |
|
362 | self.autoindent = value | |
360 |
|
363 | |||
361 | #------------------------------------------------------------------------- |
|
364 | #------------------------------------------------------------------------- | |
362 | # init_* methods called by __init__ |
|
365 | # init_* methods called by __init__ | |
363 | #------------------------------------------------------------------------- |
|
366 | #------------------------------------------------------------------------- | |
364 |
|
367 | |||
365 | def init_ipython_dir(self, ipython_dir): |
|
368 | def init_ipython_dir(self, ipython_dir): | |
366 | if ipython_dir is not None: |
|
369 | if ipython_dir is not None: | |
367 | self.ipython_dir = ipython_dir |
|
370 | self.ipython_dir = ipython_dir | |
368 | self.config.Global.ipython_dir = self.ipython_dir |
|
371 | self.config.Global.ipython_dir = self.ipython_dir | |
369 | return |
|
372 | return | |
370 |
|
373 | |||
371 | if hasattr(self.config.Global, 'ipython_dir'): |
|
374 | if hasattr(self.config.Global, 'ipython_dir'): | |
372 | self.ipython_dir = self.config.Global.ipython_dir |
|
375 | self.ipython_dir = self.config.Global.ipython_dir | |
373 | else: |
|
376 | else: | |
374 | self.ipython_dir = get_ipython_dir() |
|
377 | self.ipython_dir = get_ipython_dir() | |
375 |
|
378 | |||
376 | # All children can just read this |
|
379 | # All children can just read this | |
377 | self.config.Global.ipython_dir = self.ipython_dir |
|
380 | self.config.Global.ipython_dir = self.ipython_dir | |
378 |
|
381 | |||
379 | def init_instance_attrs(self): |
|
382 | def init_instance_attrs(self): | |
380 | self.more = False |
|
383 | self.more = False | |
381 |
|
384 | |||
382 | # command compiler |
|
385 | # command compiler | |
383 | self.compile = CachingCompiler() |
|
386 | self.compile = CachingCompiler() | |
384 |
|
387 | |||
385 | # User input buffers |
|
388 | # User input buffers | |
386 | # NOTE: these variables are slated for full removal, once we are 100% |
|
389 | # NOTE: these variables are slated for full removal, once we are 100% | |
387 | # sure that the new execution logic is solid. We will delte runlines, |
|
390 | # sure that the new execution logic is solid. We will delte runlines, | |
388 | # push_line and these buffers, as all input will be managed by the |
|
391 | # push_line and these buffers, as all input will be managed by the | |
389 | # frontends via an inputsplitter instance. |
|
392 | # frontends via an inputsplitter instance. | |
390 | self.buffer = [] |
|
393 | self.buffer = [] | |
391 | self.buffer_raw = [] |
|
394 | self.buffer_raw = [] | |
392 |
|
395 | |||
393 | # Make an empty namespace, which extension writers can rely on both |
|
396 | # Make an empty namespace, which extension writers can rely on both | |
394 | # existing and NEVER being used by ipython itself. This gives them a |
|
397 | # existing and NEVER being used by ipython itself. This gives them a | |
395 | # convenient location for storing additional information and state |
|
398 | # convenient location for storing additional information and state | |
396 | # their extensions may require, without fear of collisions with other |
|
399 | # their extensions may require, without fear of collisions with other | |
397 | # ipython names that may develop later. |
|
400 | # ipython names that may develop later. | |
398 | self.meta = Struct() |
|
401 | self.meta = Struct() | |
399 |
|
402 | |||
400 | # Object variable to store code object waiting execution. This is |
|
403 | # Object variable to store code object waiting execution. This is | |
401 | # used mainly by the multithreaded shells, but it can come in handy in |
|
404 | # used mainly by the multithreaded shells, but it can come in handy in | |
402 | # other situations. No need to use a Queue here, since it's a single |
|
405 | # other situations. No need to use a Queue here, since it's a single | |
403 | # item which gets cleared once run. |
|
406 | # item which gets cleared once run. | |
404 | self.code_to_run = None |
|
407 | self.code_to_run = None | |
405 |
|
408 | |||
406 | # Temporary files used for various purposes. Deleted at exit. |
|
409 | # Temporary files used for various purposes. Deleted at exit. | |
407 | self.tempfiles = [] |
|
410 | self.tempfiles = [] | |
408 |
|
411 | |||
409 | # Keep track of readline usage (later set by init_readline) |
|
412 | # Keep track of readline usage (later set by init_readline) | |
410 | self.has_readline = False |
|
413 | self.has_readline = False | |
411 |
|
414 | |||
412 | # keep track of where we started running (mainly for crash post-mortem) |
|
415 | # keep track of where we started running (mainly for crash post-mortem) | |
413 | # This is not being used anywhere currently. |
|
416 | # This is not being used anywhere currently. | |
414 | self.starting_dir = os.getcwd() |
|
417 | self.starting_dir = os.getcwd() | |
415 |
|
418 | |||
416 | # Indentation management |
|
419 | # Indentation management | |
417 | self.indent_current_nsp = 0 |
|
420 | self.indent_current_nsp = 0 | |
418 |
|
421 | |||
419 | def init_environment(self): |
|
422 | def init_environment(self): | |
420 | """Any changes we need to make to the user's environment.""" |
|
423 | """Any changes we need to make to the user's environment.""" | |
421 | pass |
|
424 | pass | |
422 |
|
425 | |||
423 | def init_encoding(self): |
|
426 | def init_encoding(self): | |
424 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
427 | # Get system encoding at startup time. Certain terminals (like Emacs | |
425 | # under Win32 have it set to None, and we need to have a known valid |
|
428 | # under Win32 have it set to None, and we need to have a known valid | |
426 | # encoding to use in the raw_input() method |
|
429 | # encoding to use in the raw_input() method | |
427 | try: |
|
430 | try: | |
428 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
431 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
429 | except AttributeError: |
|
432 | except AttributeError: | |
430 | self.stdin_encoding = 'ascii' |
|
433 | self.stdin_encoding = 'ascii' | |
431 |
|
434 | |||
432 | def init_syntax_highlighting(self): |
|
435 | def init_syntax_highlighting(self): | |
433 | # Python source parser/formatter for syntax highlighting |
|
436 | # Python source parser/formatter for syntax highlighting | |
434 | pyformat = PyColorize.Parser().format |
|
437 | pyformat = PyColorize.Parser().format | |
435 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
438 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
436 |
|
439 | |||
437 | def init_pushd_popd_magic(self): |
|
440 | def init_pushd_popd_magic(self): | |
438 | # for pushd/popd management |
|
441 | # for pushd/popd management | |
439 | try: |
|
442 | try: | |
440 | self.home_dir = get_home_dir() |
|
443 | self.home_dir = get_home_dir() | |
441 | except HomeDirError, msg: |
|
444 | except HomeDirError, msg: | |
442 | fatal(msg) |
|
445 | fatal(msg) | |
443 |
|
446 | |||
444 | self.dir_stack = [] |
|
447 | self.dir_stack = [] | |
445 |
|
448 | |||
446 | def init_logger(self): |
|
449 | def init_logger(self): | |
447 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
450 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
448 | logmode='rotate') |
|
451 | logmode='rotate') | |
449 |
|
452 | |||
450 | def init_logstart(self): |
|
453 | def init_logstart(self): | |
451 | """Initialize logging in case it was requested at the command line. |
|
454 | """Initialize logging in case it was requested at the command line. | |
452 | """ |
|
455 | """ | |
453 | if self.logappend: |
|
456 | if self.logappend: | |
454 | self.magic_logstart(self.logappend + ' append') |
|
457 | self.magic_logstart(self.logappend + ' append') | |
455 | elif self.logfile: |
|
458 | elif self.logfile: | |
456 | self.magic_logstart(self.logfile) |
|
459 | self.magic_logstart(self.logfile) | |
457 | elif self.logstart: |
|
460 | elif self.logstart: | |
458 | self.magic_logstart() |
|
461 | self.magic_logstart() | |
459 |
|
462 | |||
460 | def init_builtins(self): |
|
463 | def init_builtins(self): | |
461 | self.builtin_trap = BuiltinTrap(shell=self) |
|
464 | self.builtin_trap = BuiltinTrap(shell=self) | |
462 |
|
465 | |||
463 | def init_inspector(self): |
|
466 | def init_inspector(self): | |
464 | # Object inspector |
|
467 | # Object inspector | |
465 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
468 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
466 | PyColorize.ANSICodeColors, |
|
469 | PyColorize.ANSICodeColors, | |
467 | 'NoColor', |
|
470 | 'NoColor', | |
468 | self.object_info_string_level) |
|
471 | self.object_info_string_level) | |
469 |
|
472 | |||
470 | def init_io(self): |
|
473 | def init_io(self): | |
471 | # This will just use sys.stdout and sys.stderr. If you want to |
|
474 | # This will just use sys.stdout and sys.stderr. If you want to | |
472 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
475 | # override sys.stdout and sys.stderr themselves, you need to do that | |
473 | # *before* instantiating this class, because Term holds onto |
|
476 | # *before* instantiating this class, because Term holds onto | |
474 | # references to the underlying streams. |
|
477 | # references to the underlying streams. | |
475 | if sys.platform == 'win32' and self.has_readline: |
|
478 | if sys.platform == 'win32' and self.has_readline: | |
476 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
479 | Term = io.IOTerm(cout=self.readline._outputfile, | |
477 | cerr=self.readline._outputfile) |
|
480 | cerr=self.readline._outputfile) | |
478 | else: |
|
481 | else: | |
479 | Term = io.IOTerm() |
|
482 | Term = io.IOTerm() | |
480 | io.Term = Term |
|
483 | io.Term = Term | |
481 |
|
484 | |||
482 | def init_prompts(self): |
|
485 | def init_prompts(self): | |
483 | # TODO: This is a pass for now because the prompts are managed inside |
|
486 | # TODO: This is a pass for now because the prompts are managed inside | |
484 | # the DisplayHook. Once there is a separate prompt manager, this |
|
487 | # the DisplayHook. Once there is a separate prompt manager, this | |
485 | # will initialize that object and all prompt related information. |
|
488 | # will initialize that object and all prompt related information. | |
486 | pass |
|
489 | pass | |
487 |
|
490 | |||
|
491 | def init_display_formatter(self): | |||
|
492 | self.display_formatter = DisplayFormatter(config=self.config) | |||
|
493 | ||||
488 | def init_display_pub(self): |
|
494 | def init_display_pub(self): | |
489 | self.display_pub = self.display_pub_class(config=self.config) |
|
495 | self.display_pub = self.display_pub_class(config=self.config) | |
490 |
|
496 | |||
491 | def init_displayhook(self): |
|
497 | def init_displayhook(self): | |
492 | # Initialize displayhook, set in/out prompts and printing system |
|
498 | # Initialize displayhook, set in/out prompts and printing system | |
493 | self.displayhook = self.displayhook_class( |
|
499 | self.displayhook = self.displayhook_class( | |
494 | config=self.config, |
|
500 | config=self.config, | |
495 | shell=self, |
|
501 | shell=self, | |
496 | cache_size=self.cache_size, |
|
502 | cache_size=self.cache_size, | |
497 | input_sep = self.separate_in, |
|
503 | input_sep = self.separate_in, | |
498 | output_sep = self.separate_out, |
|
504 | output_sep = self.separate_out, | |
499 | output_sep2 = self.separate_out2, |
|
505 | output_sep2 = self.separate_out2, | |
500 | ps1 = self.prompt_in1, |
|
506 | ps1 = self.prompt_in1, | |
501 | ps2 = self.prompt_in2, |
|
507 | ps2 = self.prompt_in2, | |
502 | ps_out = self.prompt_out, |
|
508 | ps_out = self.prompt_out, | |
503 | pad_left = self.prompts_pad_left |
|
509 | pad_left = self.prompts_pad_left | |
504 | ) |
|
510 | ) | |
505 | # This is a context manager that installs/revmoes the displayhook at |
|
511 | # This is a context manager that installs/revmoes the displayhook at | |
506 | # the appropriate time. |
|
512 | # the appropriate time. | |
507 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
513 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
508 |
|
514 | |||
509 | def init_reload_doctest(self): |
|
515 | def init_reload_doctest(self): | |
510 | # Do a proper resetting of doctest, including the necessary displayhook |
|
516 | # Do a proper resetting of doctest, including the necessary displayhook | |
511 | # monkeypatching |
|
517 | # monkeypatching | |
512 | try: |
|
518 | try: | |
513 | doctest_reload() |
|
519 | doctest_reload() | |
514 | except ImportError: |
|
520 | except ImportError: | |
515 | warn("doctest module does not exist.") |
|
521 | warn("doctest module does not exist.") | |
516 |
|
522 | |||
517 | #------------------------------------------------------------------------- |
|
523 | #------------------------------------------------------------------------- | |
518 | # Things related to injections into the sys module |
|
524 | # Things related to injections into the sys module | |
519 | #------------------------------------------------------------------------- |
|
525 | #------------------------------------------------------------------------- | |
520 |
|
526 | |||
521 | def save_sys_module_state(self): |
|
527 | def save_sys_module_state(self): | |
522 | """Save the state of hooks in the sys module. |
|
528 | """Save the state of hooks in the sys module. | |
523 |
|
529 | |||
524 | This has to be called after self.user_ns is created. |
|
530 | This has to be called after self.user_ns is created. | |
525 | """ |
|
531 | """ | |
526 | self._orig_sys_module_state = {} |
|
532 | self._orig_sys_module_state = {} | |
527 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
533 | self._orig_sys_module_state['stdin'] = sys.stdin | |
528 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
534 | self._orig_sys_module_state['stdout'] = sys.stdout | |
529 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
535 | self._orig_sys_module_state['stderr'] = sys.stderr | |
530 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
536 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
531 | try: |
|
537 | try: | |
532 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
538 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
533 | except KeyError: |
|
539 | except KeyError: | |
534 | pass |
|
540 | pass | |
535 |
|
541 | |||
536 | def restore_sys_module_state(self): |
|
542 | def restore_sys_module_state(self): | |
537 | """Restore the state of the sys module.""" |
|
543 | """Restore the state of the sys module.""" | |
538 | try: |
|
544 | try: | |
539 | for k, v in self._orig_sys_module_state.iteritems(): |
|
545 | for k, v in self._orig_sys_module_state.iteritems(): | |
540 | setattr(sys, k, v) |
|
546 | setattr(sys, k, v) | |
541 | except AttributeError: |
|
547 | except AttributeError: | |
542 | pass |
|
548 | pass | |
543 | # Reset what what done in self.init_sys_modules |
|
549 | # Reset what what done in self.init_sys_modules | |
544 | try: |
|
550 | try: | |
545 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
551 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
546 | except (AttributeError, KeyError): |
|
552 | except (AttributeError, KeyError): | |
547 | pass |
|
553 | pass | |
548 |
|
554 | |||
549 | #------------------------------------------------------------------------- |
|
555 | #------------------------------------------------------------------------- | |
550 | # Things related to hooks |
|
556 | # Things related to hooks | |
551 | #------------------------------------------------------------------------- |
|
557 | #------------------------------------------------------------------------- | |
552 |
|
558 | |||
553 | def init_hooks(self): |
|
559 | def init_hooks(self): | |
554 | # hooks holds pointers used for user-side customizations |
|
560 | # hooks holds pointers used for user-side customizations | |
555 | self.hooks = Struct() |
|
561 | self.hooks = Struct() | |
556 |
|
562 | |||
557 | self.strdispatchers = {} |
|
563 | self.strdispatchers = {} | |
558 |
|
564 | |||
559 | # Set all default hooks, defined in the IPython.hooks module. |
|
565 | # Set all default hooks, defined in the IPython.hooks module. | |
560 | hooks = IPython.core.hooks |
|
566 | hooks = IPython.core.hooks | |
561 | for hook_name in hooks.__all__: |
|
567 | for hook_name in hooks.__all__: | |
562 | # default hooks have priority 100, i.e. low; user hooks should have |
|
568 | # default hooks have priority 100, i.e. low; user hooks should have | |
563 | # 0-100 priority |
|
569 | # 0-100 priority | |
564 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
570 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
565 |
|
571 | |||
566 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
572 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
567 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
573 | """set_hook(name,hook) -> sets an internal IPython hook. | |
568 |
|
574 | |||
569 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
575 | IPython exposes some of its internal API as user-modifiable hooks. By | |
570 | adding your function to one of these hooks, you can modify IPython's |
|
576 | adding your function to one of these hooks, you can modify IPython's | |
571 | behavior to call at runtime your own routines.""" |
|
577 | behavior to call at runtime your own routines.""" | |
572 |
|
578 | |||
573 | # At some point in the future, this should validate the hook before it |
|
579 | # At some point in the future, this should validate the hook before it | |
574 | # accepts it. Probably at least check that the hook takes the number |
|
580 | # accepts it. Probably at least check that the hook takes the number | |
575 | # of args it's supposed to. |
|
581 | # of args it's supposed to. | |
576 |
|
582 | |||
577 | f = types.MethodType(hook,self) |
|
583 | f = types.MethodType(hook,self) | |
578 |
|
584 | |||
579 | # check if the hook is for strdispatcher first |
|
585 | # check if the hook is for strdispatcher first | |
580 | if str_key is not None: |
|
586 | if str_key is not None: | |
581 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
587 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
582 | sdp.add_s(str_key, f, priority ) |
|
588 | sdp.add_s(str_key, f, priority ) | |
583 | self.strdispatchers[name] = sdp |
|
589 | self.strdispatchers[name] = sdp | |
584 | return |
|
590 | return | |
585 | if re_key is not None: |
|
591 | if re_key is not None: | |
586 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
592 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
587 | sdp.add_re(re.compile(re_key), f, priority ) |
|
593 | sdp.add_re(re.compile(re_key), f, priority ) | |
588 | self.strdispatchers[name] = sdp |
|
594 | self.strdispatchers[name] = sdp | |
589 | return |
|
595 | return | |
590 |
|
596 | |||
591 | dp = getattr(self.hooks, name, None) |
|
597 | dp = getattr(self.hooks, name, None) | |
592 | if name not in IPython.core.hooks.__all__: |
|
598 | if name not in IPython.core.hooks.__all__: | |
593 | print "Warning! Hook '%s' is not one of %s" % \ |
|
599 | print "Warning! Hook '%s' is not one of %s" % \ | |
594 | (name, IPython.core.hooks.__all__ ) |
|
600 | (name, IPython.core.hooks.__all__ ) | |
595 | if not dp: |
|
601 | if not dp: | |
596 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
602 | dp = IPython.core.hooks.CommandChainDispatcher() | |
597 |
|
603 | |||
598 | try: |
|
604 | try: | |
599 | dp.add(f,priority) |
|
605 | dp.add(f,priority) | |
600 | except AttributeError: |
|
606 | except AttributeError: | |
601 | # it was not commandchain, plain old func - replace |
|
607 | # it was not commandchain, plain old func - replace | |
602 | dp = f |
|
608 | dp = f | |
603 |
|
609 | |||
604 | setattr(self.hooks,name, dp) |
|
610 | setattr(self.hooks,name, dp) | |
605 |
|
611 | |||
606 | def register_post_execute(self, func): |
|
612 | def register_post_execute(self, func): | |
607 | """Register a function for calling after code execution. |
|
613 | """Register a function for calling after code execution. | |
608 | """ |
|
614 | """ | |
609 | if not callable(func): |
|
615 | if not callable(func): | |
610 | raise ValueError('argument %s must be callable' % func) |
|
616 | raise ValueError('argument %s must be callable' % func) | |
611 | self._post_execute.add(func) |
|
617 | self._post_execute.add(func) | |
612 |
|
618 | |||
613 | #------------------------------------------------------------------------- |
|
619 | #------------------------------------------------------------------------- | |
614 | # Things related to the "main" module |
|
620 | # Things related to the "main" module | |
615 | #------------------------------------------------------------------------- |
|
621 | #------------------------------------------------------------------------- | |
616 |
|
622 | |||
617 | def new_main_mod(self,ns=None): |
|
623 | def new_main_mod(self,ns=None): | |
618 | """Return a new 'main' module object for user code execution. |
|
624 | """Return a new 'main' module object for user code execution. | |
619 | """ |
|
625 | """ | |
620 | main_mod = self._user_main_module |
|
626 | main_mod = self._user_main_module | |
621 | init_fakemod_dict(main_mod,ns) |
|
627 | init_fakemod_dict(main_mod,ns) | |
622 | return main_mod |
|
628 | return main_mod | |
623 |
|
629 | |||
624 | def cache_main_mod(self,ns,fname): |
|
630 | def cache_main_mod(self,ns,fname): | |
625 | """Cache a main module's namespace. |
|
631 | """Cache a main module's namespace. | |
626 |
|
632 | |||
627 | When scripts are executed via %run, we must keep a reference to the |
|
633 | When scripts are executed via %run, we must keep a reference to the | |
628 | namespace of their __main__ module (a FakeModule instance) around so |
|
634 | namespace of their __main__ module (a FakeModule instance) around so | |
629 | that Python doesn't clear it, rendering objects defined therein |
|
635 | that Python doesn't clear it, rendering objects defined therein | |
630 | useless. |
|
636 | useless. | |
631 |
|
637 | |||
632 | This method keeps said reference in a private dict, keyed by the |
|
638 | This method keeps said reference in a private dict, keyed by the | |
633 | absolute path of the module object (which corresponds to the script |
|
639 | absolute path of the module object (which corresponds to the script | |
634 | path). This way, for multiple executions of the same script we only |
|
640 | path). This way, for multiple executions of the same script we only | |
635 | keep one copy of the namespace (the last one), thus preventing memory |
|
641 | keep one copy of the namespace (the last one), thus preventing memory | |
636 | leaks from old references while allowing the objects from the last |
|
642 | leaks from old references while allowing the objects from the last | |
637 | execution to be accessible. |
|
643 | execution to be accessible. | |
638 |
|
644 | |||
639 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
645 | Note: we can not allow the actual FakeModule instances to be deleted, | |
640 | because of how Python tears down modules (it hard-sets all their |
|
646 | because of how Python tears down modules (it hard-sets all their | |
641 | references to None without regard for reference counts). This method |
|
647 | references to None without regard for reference counts). This method | |
642 | must therefore make a *copy* of the given namespace, to allow the |
|
648 | must therefore make a *copy* of the given namespace, to allow the | |
643 | original module's __dict__ to be cleared and reused. |
|
649 | original module's __dict__ to be cleared and reused. | |
644 |
|
650 | |||
645 |
|
651 | |||
646 | Parameters |
|
652 | Parameters | |
647 | ---------- |
|
653 | ---------- | |
648 | ns : a namespace (a dict, typically) |
|
654 | ns : a namespace (a dict, typically) | |
649 |
|
655 | |||
650 | fname : str |
|
656 | fname : str | |
651 | Filename associated with the namespace. |
|
657 | Filename associated with the namespace. | |
652 |
|
658 | |||
653 | Examples |
|
659 | Examples | |
654 | -------- |
|
660 | -------- | |
655 |
|
661 | |||
656 | In [10]: import IPython |
|
662 | In [10]: import IPython | |
657 |
|
663 | |||
658 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
664 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
659 |
|
665 | |||
660 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
666 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
661 | Out[12]: True |
|
667 | Out[12]: True | |
662 | """ |
|
668 | """ | |
663 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
669 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
664 |
|
670 | |||
665 | def clear_main_mod_cache(self): |
|
671 | def clear_main_mod_cache(self): | |
666 | """Clear the cache of main modules. |
|
672 | """Clear the cache of main modules. | |
667 |
|
673 | |||
668 | Mainly for use by utilities like %reset. |
|
674 | Mainly for use by utilities like %reset. | |
669 |
|
675 | |||
670 | Examples |
|
676 | Examples | |
671 | -------- |
|
677 | -------- | |
672 |
|
678 | |||
673 | In [15]: import IPython |
|
679 | In [15]: import IPython | |
674 |
|
680 | |||
675 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
681 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
676 |
|
682 | |||
677 | In [17]: len(_ip._main_ns_cache) > 0 |
|
683 | In [17]: len(_ip._main_ns_cache) > 0 | |
678 | Out[17]: True |
|
684 | Out[17]: True | |
679 |
|
685 | |||
680 | In [18]: _ip.clear_main_mod_cache() |
|
686 | In [18]: _ip.clear_main_mod_cache() | |
681 |
|
687 | |||
682 | In [19]: len(_ip._main_ns_cache) == 0 |
|
688 | In [19]: len(_ip._main_ns_cache) == 0 | |
683 | Out[19]: True |
|
689 | Out[19]: True | |
684 | """ |
|
690 | """ | |
685 | self._main_ns_cache.clear() |
|
691 | self._main_ns_cache.clear() | |
686 |
|
692 | |||
687 | #------------------------------------------------------------------------- |
|
693 | #------------------------------------------------------------------------- | |
688 | # Things related to debugging |
|
694 | # Things related to debugging | |
689 | #------------------------------------------------------------------------- |
|
695 | #------------------------------------------------------------------------- | |
690 |
|
696 | |||
691 | def init_pdb(self): |
|
697 | def init_pdb(self): | |
692 | # Set calling of pdb on exceptions |
|
698 | # Set calling of pdb on exceptions | |
693 | # self.call_pdb is a property |
|
699 | # self.call_pdb is a property | |
694 | self.call_pdb = self.pdb |
|
700 | self.call_pdb = self.pdb | |
695 |
|
701 | |||
696 | def _get_call_pdb(self): |
|
702 | def _get_call_pdb(self): | |
697 | return self._call_pdb |
|
703 | return self._call_pdb | |
698 |
|
704 | |||
699 | def _set_call_pdb(self,val): |
|
705 | def _set_call_pdb(self,val): | |
700 |
|
706 | |||
701 | if val not in (0,1,False,True): |
|
707 | if val not in (0,1,False,True): | |
702 | raise ValueError,'new call_pdb value must be boolean' |
|
708 | raise ValueError,'new call_pdb value must be boolean' | |
703 |
|
709 | |||
704 | # store value in instance |
|
710 | # store value in instance | |
705 | self._call_pdb = val |
|
711 | self._call_pdb = val | |
706 |
|
712 | |||
707 | # notify the actual exception handlers |
|
713 | # notify the actual exception handlers | |
708 | self.InteractiveTB.call_pdb = val |
|
714 | self.InteractiveTB.call_pdb = val | |
709 |
|
715 | |||
710 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
716 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
711 | 'Control auto-activation of pdb at exceptions') |
|
717 | 'Control auto-activation of pdb at exceptions') | |
712 |
|
718 | |||
713 | def debugger(self,force=False): |
|
719 | def debugger(self,force=False): | |
714 | """Call the pydb/pdb debugger. |
|
720 | """Call the pydb/pdb debugger. | |
715 |
|
721 | |||
716 | Keywords: |
|
722 | Keywords: | |
717 |
|
723 | |||
718 | - force(False): by default, this routine checks the instance call_pdb |
|
724 | - force(False): by default, this routine checks the instance call_pdb | |
719 | flag and does not actually invoke the debugger if the flag is false. |
|
725 | flag and does not actually invoke the debugger if the flag is false. | |
720 | The 'force' option forces the debugger to activate even if the flag |
|
726 | The 'force' option forces the debugger to activate even if the flag | |
721 | is false. |
|
727 | is false. | |
722 | """ |
|
728 | """ | |
723 |
|
729 | |||
724 | if not (force or self.call_pdb): |
|
730 | if not (force or self.call_pdb): | |
725 | return |
|
731 | return | |
726 |
|
732 | |||
727 | if not hasattr(sys,'last_traceback'): |
|
733 | if not hasattr(sys,'last_traceback'): | |
728 | error('No traceback has been produced, nothing to debug.') |
|
734 | error('No traceback has been produced, nothing to debug.') | |
729 | return |
|
735 | return | |
730 |
|
736 | |||
731 | # use pydb if available |
|
737 | # use pydb if available | |
732 | if debugger.has_pydb: |
|
738 | if debugger.has_pydb: | |
733 | from pydb import pm |
|
739 | from pydb import pm | |
734 | else: |
|
740 | else: | |
735 | # fallback to our internal debugger |
|
741 | # fallback to our internal debugger | |
736 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
742 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
737 | self.history_saving_wrapper(pm)() |
|
743 | self.history_saving_wrapper(pm)() | |
738 |
|
744 | |||
739 | #------------------------------------------------------------------------- |
|
745 | #------------------------------------------------------------------------- | |
740 | # Things related to IPython's various namespaces |
|
746 | # Things related to IPython's various namespaces | |
741 | #------------------------------------------------------------------------- |
|
747 | #------------------------------------------------------------------------- | |
742 |
|
748 | |||
743 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
749 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
744 | # Create the namespace where the user will operate. user_ns is |
|
750 | # Create the namespace where the user will operate. user_ns is | |
745 | # normally the only one used, and it is passed to the exec calls as |
|
751 | # normally the only one used, and it is passed to the exec calls as | |
746 | # the locals argument. But we do carry a user_global_ns namespace |
|
752 | # the locals argument. But we do carry a user_global_ns namespace | |
747 | # given as the exec 'globals' argument, This is useful in embedding |
|
753 | # given as the exec 'globals' argument, This is useful in embedding | |
748 | # situations where the ipython shell opens in a context where the |
|
754 | # situations where the ipython shell opens in a context where the | |
749 | # distinction between locals and globals is meaningful. For |
|
755 | # distinction between locals and globals is meaningful. For | |
750 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
756 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
751 |
|
757 | |||
752 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
758 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
753 | # level as a dict instead of a module. This is a manual fix, but I |
|
759 | # level as a dict instead of a module. This is a manual fix, but I | |
754 | # should really track down where the problem is coming from. Alex |
|
760 | # should really track down where the problem is coming from. Alex | |
755 | # Schmolck reported this problem first. |
|
761 | # Schmolck reported this problem first. | |
756 |
|
762 | |||
757 | # A useful post by Alex Martelli on this topic: |
|
763 | # A useful post by Alex Martelli on this topic: | |
758 | # Re: inconsistent value from __builtins__ |
|
764 | # Re: inconsistent value from __builtins__ | |
759 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
765 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
760 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
766 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
761 | # Gruppen: comp.lang.python |
|
767 | # Gruppen: comp.lang.python | |
762 |
|
768 | |||
763 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
769 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
764 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
770 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
765 | # > <type 'dict'> |
|
771 | # > <type 'dict'> | |
766 | # > >>> print type(__builtins__) |
|
772 | # > >>> print type(__builtins__) | |
767 | # > <type 'module'> |
|
773 | # > <type 'module'> | |
768 | # > Is this difference in return value intentional? |
|
774 | # > Is this difference in return value intentional? | |
769 |
|
775 | |||
770 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
776 | # Well, it's documented that '__builtins__' can be either a dictionary | |
771 | # or a module, and it's been that way for a long time. Whether it's |
|
777 | # or a module, and it's been that way for a long time. Whether it's | |
772 | # intentional (or sensible), I don't know. In any case, the idea is |
|
778 | # intentional (or sensible), I don't know. In any case, the idea is | |
773 | # that if you need to access the built-in namespace directly, you |
|
779 | # that if you need to access the built-in namespace directly, you | |
774 | # should start with "import __builtin__" (note, no 's') which will |
|
780 | # should start with "import __builtin__" (note, no 's') which will | |
775 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
781 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
776 |
|
782 | |||
777 | # These routines return properly built dicts as needed by the rest of |
|
783 | # These routines return properly built dicts as needed by the rest of | |
778 | # the code, and can also be used by extension writers to generate |
|
784 | # the code, and can also be used by extension writers to generate | |
779 | # properly initialized namespaces. |
|
785 | # properly initialized namespaces. | |
780 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
786 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
781 | user_global_ns) |
|
787 | user_global_ns) | |
782 |
|
788 | |||
783 | # Assign namespaces |
|
789 | # Assign namespaces | |
784 | # This is the namespace where all normal user variables live |
|
790 | # This is the namespace where all normal user variables live | |
785 | self.user_ns = user_ns |
|
791 | self.user_ns = user_ns | |
786 | self.user_global_ns = user_global_ns |
|
792 | self.user_global_ns = user_global_ns | |
787 |
|
793 | |||
788 | # An auxiliary namespace that checks what parts of the user_ns were |
|
794 | # An auxiliary namespace that checks what parts of the user_ns were | |
789 | # loaded at startup, so we can list later only variables defined in |
|
795 | # loaded at startup, so we can list later only variables defined in | |
790 | # actual interactive use. Since it is always a subset of user_ns, it |
|
796 | # actual interactive use. Since it is always a subset of user_ns, it | |
791 | # doesn't need to be separately tracked in the ns_table. |
|
797 | # doesn't need to be separately tracked in the ns_table. | |
792 | self.user_ns_hidden = {} |
|
798 | self.user_ns_hidden = {} | |
793 |
|
799 | |||
794 | # A namespace to keep track of internal data structures to prevent |
|
800 | # A namespace to keep track of internal data structures to prevent | |
795 | # them from cluttering user-visible stuff. Will be updated later |
|
801 | # them from cluttering user-visible stuff. Will be updated later | |
796 | self.internal_ns = {} |
|
802 | self.internal_ns = {} | |
797 |
|
803 | |||
798 | # Now that FakeModule produces a real module, we've run into a nasty |
|
804 | # Now that FakeModule produces a real module, we've run into a nasty | |
799 | # problem: after script execution (via %run), the module where the user |
|
805 | # problem: after script execution (via %run), the module where the user | |
800 | # code ran is deleted. Now that this object is a true module (needed |
|
806 | # code ran is deleted. Now that this object is a true module (needed | |
801 | # so docetst and other tools work correctly), the Python module |
|
807 | # so docetst and other tools work correctly), the Python module | |
802 | # teardown mechanism runs over it, and sets to None every variable |
|
808 | # teardown mechanism runs over it, and sets to None every variable | |
803 | # present in that module. Top-level references to objects from the |
|
809 | # present in that module. Top-level references to objects from the | |
804 | # script survive, because the user_ns is updated with them. However, |
|
810 | # script survive, because the user_ns is updated with them. However, | |
805 | # calling functions defined in the script that use other things from |
|
811 | # calling functions defined in the script that use other things from | |
806 | # the script will fail, because the function's closure had references |
|
812 | # the script will fail, because the function's closure had references | |
807 | # to the original objects, which are now all None. So we must protect |
|
813 | # to the original objects, which are now all None. So we must protect | |
808 | # these modules from deletion by keeping a cache. |
|
814 | # these modules from deletion by keeping a cache. | |
809 | # |
|
815 | # | |
810 | # To avoid keeping stale modules around (we only need the one from the |
|
816 | # To avoid keeping stale modules around (we only need the one from the | |
811 | # last run), we use a dict keyed with the full path to the script, so |
|
817 | # last run), we use a dict keyed with the full path to the script, so | |
812 | # only the last version of the module is held in the cache. Note, |
|
818 | # only the last version of the module is held in the cache. Note, | |
813 | # however, that we must cache the module *namespace contents* (their |
|
819 | # however, that we must cache the module *namespace contents* (their | |
814 | # __dict__). Because if we try to cache the actual modules, old ones |
|
820 | # __dict__). Because if we try to cache the actual modules, old ones | |
815 | # (uncached) could be destroyed while still holding references (such as |
|
821 | # (uncached) could be destroyed while still holding references (such as | |
816 | # those held by GUI objects that tend to be long-lived)> |
|
822 | # those held by GUI objects that tend to be long-lived)> | |
817 | # |
|
823 | # | |
818 | # The %reset command will flush this cache. See the cache_main_mod() |
|
824 | # The %reset command will flush this cache. See the cache_main_mod() | |
819 | # and clear_main_mod_cache() methods for details on use. |
|
825 | # and clear_main_mod_cache() methods for details on use. | |
820 |
|
826 | |||
821 | # This is the cache used for 'main' namespaces |
|
827 | # This is the cache used for 'main' namespaces | |
822 | self._main_ns_cache = {} |
|
828 | self._main_ns_cache = {} | |
823 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
829 | # And this is the single instance of FakeModule whose __dict__ we keep | |
824 | # copying and clearing for reuse on each %run |
|
830 | # copying and clearing for reuse on each %run | |
825 | self._user_main_module = FakeModule() |
|
831 | self._user_main_module = FakeModule() | |
826 |
|
832 | |||
827 | # A table holding all the namespaces IPython deals with, so that |
|
833 | # A table holding all the namespaces IPython deals with, so that | |
828 | # introspection facilities can search easily. |
|
834 | # introspection facilities can search easily. | |
829 | self.ns_table = {'user':user_ns, |
|
835 | self.ns_table = {'user':user_ns, | |
830 | 'user_global':user_global_ns, |
|
836 | 'user_global':user_global_ns, | |
831 | 'internal':self.internal_ns, |
|
837 | 'internal':self.internal_ns, | |
832 | 'builtin':__builtin__.__dict__ |
|
838 | 'builtin':__builtin__.__dict__ | |
833 | } |
|
839 | } | |
834 |
|
840 | |||
835 | # Similarly, track all namespaces where references can be held and that |
|
841 | # Similarly, track all namespaces where references can be held and that | |
836 | # we can safely clear (so it can NOT include builtin). This one can be |
|
842 | # we can safely clear (so it can NOT include builtin). This one can be | |
837 | # a simple list. Note that the main execution namespaces, user_ns and |
|
843 | # a simple list. Note that the main execution namespaces, user_ns and | |
838 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
844 | # user_global_ns, can NOT be listed here, as clearing them blindly | |
839 | # causes errors in object __del__ methods. Instead, the reset() method |
|
845 | # causes errors in object __del__ methods. Instead, the reset() method | |
840 | # clears them manually and carefully. |
|
846 | # clears them manually and carefully. | |
841 | self.ns_refs_table = [ self.user_ns_hidden, |
|
847 | self.ns_refs_table = [ self.user_ns_hidden, | |
842 | self.internal_ns, self._main_ns_cache ] |
|
848 | self.internal_ns, self._main_ns_cache ] | |
843 |
|
849 | |||
844 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
850 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
845 | """Return a valid local and global user interactive namespaces. |
|
851 | """Return a valid local and global user interactive namespaces. | |
846 |
|
852 | |||
847 | This builds a dict with the minimal information needed to operate as a |
|
853 | This builds a dict with the minimal information needed to operate as a | |
848 | valid IPython user namespace, which you can pass to the various |
|
854 | valid IPython user namespace, which you can pass to the various | |
849 | embedding classes in ipython. The default implementation returns the |
|
855 | embedding classes in ipython. The default implementation returns the | |
850 | same dict for both the locals and the globals to allow functions to |
|
856 | same dict for both the locals and the globals to allow functions to | |
851 | refer to variables in the namespace. Customized implementations can |
|
857 | refer to variables in the namespace. Customized implementations can | |
852 | return different dicts. The locals dictionary can actually be anything |
|
858 | return different dicts. The locals dictionary can actually be anything | |
853 | following the basic mapping protocol of a dict, but the globals dict |
|
859 | following the basic mapping protocol of a dict, but the globals dict | |
854 | must be a true dict, not even a subclass. It is recommended that any |
|
860 | must be a true dict, not even a subclass. It is recommended that any | |
855 | custom object for the locals namespace synchronize with the globals |
|
861 | custom object for the locals namespace synchronize with the globals | |
856 | dict somehow. |
|
862 | dict somehow. | |
857 |
|
863 | |||
858 | Raises TypeError if the provided globals namespace is not a true dict. |
|
864 | Raises TypeError if the provided globals namespace is not a true dict. | |
859 |
|
865 | |||
860 | Parameters |
|
866 | Parameters | |
861 | ---------- |
|
867 | ---------- | |
862 | user_ns : dict-like, optional |
|
868 | user_ns : dict-like, optional | |
863 | The current user namespace. The items in this namespace should |
|
869 | The current user namespace. The items in this namespace should | |
864 | be included in the output. If None, an appropriate blank |
|
870 | be included in the output. If None, an appropriate blank | |
865 | namespace should be created. |
|
871 | namespace should be created. | |
866 | user_global_ns : dict, optional |
|
872 | user_global_ns : dict, optional | |
867 | The current user global namespace. The items in this namespace |
|
873 | The current user global namespace. The items in this namespace | |
868 | should be included in the output. If None, an appropriate |
|
874 | should be included in the output. If None, an appropriate | |
869 | blank namespace should be created. |
|
875 | blank namespace should be created. | |
870 |
|
876 | |||
871 | Returns |
|
877 | Returns | |
872 | ------- |
|
878 | ------- | |
873 | A pair of dictionary-like object to be used as the local namespace |
|
879 | A pair of dictionary-like object to be used as the local namespace | |
874 | of the interpreter and a dict to be used as the global namespace. |
|
880 | of the interpreter and a dict to be used as the global namespace. | |
875 | """ |
|
881 | """ | |
876 |
|
882 | |||
877 |
|
883 | |||
878 | # We must ensure that __builtin__ (without the final 's') is always |
|
884 | # We must ensure that __builtin__ (without the final 's') is always | |
879 | # available and pointing to the __builtin__ *module*. For more details: |
|
885 | # available and pointing to the __builtin__ *module*. For more details: | |
880 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
886 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
881 |
|
887 | |||
882 | if user_ns is None: |
|
888 | if user_ns is None: | |
883 | # Set __name__ to __main__ to better match the behavior of the |
|
889 | # Set __name__ to __main__ to better match the behavior of the | |
884 | # normal interpreter. |
|
890 | # normal interpreter. | |
885 | user_ns = {'__name__' :'__main__', |
|
891 | user_ns = {'__name__' :'__main__', | |
886 | '__builtin__' : __builtin__, |
|
892 | '__builtin__' : __builtin__, | |
887 | '__builtins__' : __builtin__, |
|
893 | '__builtins__' : __builtin__, | |
888 | } |
|
894 | } | |
889 | else: |
|
895 | else: | |
890 | user_ns.setdefault('__name__','__main__') |
|
896 | user_ns.setdefault('__name__','__main__') | |
891 | user_ns.setdefault('__builtin__',__builtin__) |
|
897 | user_ns.setdefault('__builtin__',__builtin__) | |
892 | user_ns.setdefault('__builtins__',__builtin__) |
|
898 | user_ns.setdefault('__builtins__',__builtin__) | |
893 |
|
899 | |||
894 | if user_global_ns is None: |
|
900 | if user_global_ns is None: | |
895 | user_global_ns = user_ns |
|
901 | user_global_ns = user_ns | |
896 | if type(user_global_ns) is not dict: |
|
902 | if type(user_global_ns) is not dict: | |
897 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
903 | raise TypeError("user_global_ns must be a true dict; got %r" | |
898 | % type(user_global_ns)) |
|
904 | % type(user_global_ns)) | |
899 |
|
905 | |||
900 | return user_ns, user_global_ns |
|
906 | return user_ns, user_global_ns | |
901 |
|
907 | |||
902 | def init_sys_modules(self): |
|
908 | def init_sys_modules(self): | |
903 | # We need to insert into sys.modules something that looks like a |
|
909 | # We need to insert into sys.modules something that looks like a | |
904 | # module but which accesses the IPython namespace, for shelve and |
|
910 | # module but which accesses the IPython namespace, for shelve and | |
905 | # pickle to work interactively. Normally they rely on getting |
|
911 | # pickle to work interactively. Normally they rely on getting | |
906 | # everything out of __main__, but for embedding purposes each IPython |
|
912 | # everything out of __main__, but for embedding purposes each IPython | |
907 | # instance has its own private namespace, so we can't go shoving |
|
913 | # instance has its own private namespace, so we can't go shoving | |
908 | # everything into __main__. |
|
914 | # everything into __main__. | |
909 |
|
915 | |||
910 | # note, however, that we should only do this for non-embedded |
|
916 | # note, however, that we should only do this for non-embedded | |
911 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
917 | # ipythons, which really mimic the __main__.__dict__ with their own | |
912 | # namespace. Embedded instances, on the other hand, should not do |
|
918 | # namespace. Embedded instances, on the other hand, should not do | |
913 | # this because they need to manage the user local/global namespaces |
|
919 | # this because they need to manage the user local/global namespaces | |
914 | # only, but they live within a 'normal' __main__ (meaning, they |
|
920 | # only, but they live within a 'normal' __main__ (meaning, they | |
915 | # shouldn't overtake the execution environment of the script they're |
|
921 | # shouldn't overtake the execution environment of the script they're | |
916 | # embedded in). |
|
922 | # embedded in). | |
917 |
|
923 | |||
918 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
924 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
919 |
|
925 | |||
920 | try: |
|
926 | try: | |
921 | main_name = self.user_ns['__name__'] |
|
927 | main_name = self.user_ns['__name__'] | |
922 | except KeyError: |
|
928 | except KeyError: | |
923 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
929 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
924 | else: |
|
930 | else: | |
925 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
931 | sys.modules[main_name] = FakeModule(self.user_ns) | |
926 |
|
932 | |||
927 | def init_user_ns(self): |
|
933 | def init_user_ns(self): | |
928 | """Initialize all user-visible namespaces to their minimum defaults. |
|
934 | """Initialize all user-visible namespaces to their minimum defaults. | |
929 |
|
935 | |||
930 | Certain history lists are also initialized here, as they effectively |
|
936 | Certain history lists are also initialized here, as they effectively | |
931 | act as user namespaces. |
|
937 | act as user namespaces. | |
932 |
|
938 | |||
933 | Notes |
|
939 | Notes | |
934 | ----- |
|
940 | ----- | |
935 | All data structures here are only filled in, they are NOT reset by this |
|
941 | All data structures here are only filled in, they are NOT reset by this | |
936 | method. If they were not empty before, data will simply be added to |
|
942 | method. If they were not empty before, data will simply be added to | |
937 | therm. |
|
943 | therm. | |
938 | """ |
|
944 | """ | |
939 | # This function works in two parts: first we put a few things in |
|
945 | # This function works in two parts: first we put a few things in | |
940 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
946 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
941 | # initial variables aren't shown by %who. After the sync, we add the |
|
947 | # initial variables aren't shown by %who. After the sync, we add the | |
942 | # rest of what we *do* want the user to see with %who even on a new |
|
948 | # rest of what we *do* want the user to see with %who even on a new | |
943 | # session (probably nothing, so theye really only see their own stuff) |
|
949 | # session (probably nothing, so theye really only see their own stuff) | |
944 |
|
950 | |||
945 | # The user dict must *always* have a __builtin__ reference to the |
|
951 | # The user dict must *always* have a __builtin__ reference to the | |
946 | # Python standard __builtin__ namespace, which must be imported. |
|
952 | # Python standard __builtin__ namespace, which must be imported. | |
947 | # This is so that certain operations in prompt evaluation can be |
|
953 | # This is so that certain operations in prompt evaluation can be | |
948 | # reliably executed with builtins. Note that we can NOT use |
|
954 | # reliably executed with builtins. Note that we can NOT use | |
949 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
955 | # __builtins__ (note the 's'), because that can either be a dict or a | |
950 | # module, and can even mutate at runtime, depending on the context |
|
956 | # module, and can even mutate at runtime, depending on the context | |
951 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
957 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
952 | # always a module object, though it must be explicitly imported. |
|
958 | # always a module object, though it must be explicitly imported. | |
953 |
|
959 | |||
954 | # For more details: |
|
960 | # For more details: | |
955 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
961 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
956 | ns = dict(__builtin__ = __builtin__) |
|
962 | ns = dict(__builtin__ = __builtin__) | |
957 |
|
963 | |||
958 | # Put 'help' in the user namespace |
|
964 | # Put 'help' in the user namespace | |
959 | try: |
|
965 | try: | |
960 | from site import _Helper |
|
966 | from site import _Helper | |
961 | ns['help'] = _Helper() |
|
967 | ns['help'] = _Helper() | |
962 | except ImportError: |
|
968 | except ImportError: | |
963 | warn('help() not available - check site.py') |
|
969 | warn('help() not available - check site.py') | |
964 |
|
970 | |||
965 | # make global variables for user access to the histories |
|
971 | # make global variables for user access to the histories | |
966 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
972 | ns['_ih'] = self.history_manager.input_hist_parsed | |
967 | ns['_oh'] = self.history_manager.output_hist |
|
973 | ns['_oh'] = self.history_manager.output_hist | |
968 | ns['_dh'] = self.history_manager.dir_hist |
|
974 | ns['_dh'] = self.history_manager.dir_hist | |
969 |
|
975 | |||
970 | ns['_sh'] = shadowns |
|
976 | ns['_sh'] = shadowns | |
971 |
|
977 | |||
972 | # user aliases to input and output histories. These shouldn't show up |
|
978 | # user aliases to input and output histories. These shouldn't show up | |
973 | # in %who, as they can have very large reprs. |
|
979 | # in %who, as they can have very large reprs. | |
974 | ns['In'] = self.history_manager.input_hist_parsed |
|
980 | ns['In'] = self.history_manager.input_hist_parsed | |
975 | ns['Out'] = self.history_manager.output_hist |
|
981 | ns['Out'] = self.history_manager.output_hist | |
976 |
|
982 | |||
977 | # Store myself as the public api!!! |
|
983 | # Store myself as the public api!!! | |
978 | ns['get_ipython'] = self.get_ipython |
|
984 | ns['get_ipython'] = self.get_ipython | |
979 |
|
985 | |||
980 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
986 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
981 | # by %who |
|
987 | # by %who | |
982 | self.user_ns_hidden.update(ns) |
|
988 | self.user_ns_hidden.update(ns) | |
983 |
|
989 | |||
984 | # Anything put into ns now would show up in %who. Think twice before |
|
990 | # Anything put into ns now would show up in %who. Think twice before | |
985 | # putting anything here, as we really want %who to show the user their |
|
991 | # putting anything here, as we really want %who to show the user their | |
986 | # stuff, not our variables. |
|
992 | # stuff, not our variables. | |
987 |
|
993 | |||
988 | # Finally, update the real user's namespace |
|
994 | # Finally, update the real user's namespace | |
989 | self.user_ns.update(ns) |
|
995 | self.user_ns.update(ns) | |
990 |
|
996 | |||
991 | def reset(self): |
|
997 | def reset(self): | |
992 | """Clear all internal namespaces. |
|
998 | """Clear all internal namespaces. | |
993 |
|
999 | |||
994 | Note that this is much more aggressive than %reset, since it clears |
|
1000 | Note that this is much more aggressive than %reset, since it clears | |
995 | fully all namespaces, as well as all input/output lists. |
|
1001 | fully all namespaces, as well as all input/output lists. | |
996 | """ |
|
1002 | """ | |
997 | # Clear histories |
|
1003 | # Clear histories | |
998 | self.history_manager.reset() |
|
1004 | self.history_manager.reset() | |
999 |
|
1005 | |||
1000 | # Reset counter used to index all histories |
|
1006 | # Reset counter used to index all histories | |
1001 | self.execution_count = 0 |
|
1007 | self.execution_count = 0 | |
1002 |
|
1008 | |||
1003 | # Restore the user namespaces to minimal usability |
|
1009 | # Restore the user namespaces to minimal usability | |
1004 | for ns in self.ns_refs_table: |
|
1010 | for ns in self.ns_refs_table: | |
1005 | ns.clear() |
|
1011 | ns.clear() | |
1006 |
|
1012 | |||
1007 | # The main execution namespaces must be cleared very carefully, |
|
1013 | # The main execution namespaces must be cleared very carefully, | |
1008 | # skipping the deletion of the builtin-related keys, because doing so |
|
1014 | # skipping the deletion of the builtin-related keys, because doing so | |
1009 | # would cause errors in many object's __del__ methods. |
|
1015 | # would cause errors in many object's __del__ methods. | |
1010 | for ns in [self.user_ns, self.user_global_ns]: |
|
1016 | for ns in [self.user_ns, self.user_global_ns]: | |
1011 | drop_keys = set(ns.keys()) |
|
1017 | drop_keys = set(ns.keys()) | |
1012 | drop_keys.discard('__builtin__') |
|
1018 | drop_keys.discard('__builtin__') | |
1013 | drop_keys.discard('__builtins__') |
|
1019 | drop_keys.discard('__builtins__') | |
1014 | for k in drop_keys: |
|
1020 | for k in drop_keys: | |
1015 | del ns[k] |
|
1021 | del ns[k] | |
1016 |
|
1022 | |||
1017 | # Restore the user namespaces to minimal usability |
|
1023 | # Restore the user namespaces to minimal usability | |
1018 | self.init_user_ns() |
|
1024 | self.init_user_ns() | |
1019 |
|
1025 | |||
1020 | # Restore the default and user aliases |
|
1026 | # Restore the default and user aliases | |
1021 | self.alias_manager.clear_aliases() |
|
1027 | self.alias_manager.clear_aliases() | |
1022 | self.alias_manager.init_aliases() |
|
1028 | self.alias_manager.init_aliases() | |
1023 |
|
1029 | |||
1024 | def reset_selective(self, regex=None): |
|
1030 | def reset_selective(self, regex=None): | |
1025 | """Clear selective variables from internal namespaces based on a |
|
1031 | """Clear selective variables from internal namespaces based on a | |
1026 | specified regular expression. |
|
1032 | specified regular expression. | |
1027 |
|
1033 | |||
1028 | Parameters |
|
1034 | Parameters | |
1029 | ---------- |
|
1035 | ---------- | |
1030 | regex : string or compiled pattern, optional |
|
1036 | regex : string or compiled pattern, optional | |
1031 | A regular expression pattern that will be used in searching |
|
1037 | A regular expression pattern that will be used in searching | |
1032 | variable names in the users namespaces. |
|
1038 | variable names in the users namespaces. | |
1033 | """ |
|
1039 | """ | |
1034 | if regex is not None: |
|
1040 | if regex is not None: | |
1035 | try: |
|
1041 | try: | |
1036 | m = re.compile(regex) |
|
1042 | m = re.compile(regex) | |
1037 | except TypeError: |
|
1043 | except TypeError: | |
1038 | raise TypeError('regex must be a string or compiled pattern') |
|
1044 | raise TypeError('regex must be a string or compiled pattern') | |
1039 | # Search for keys in each namespace that match the given regex |
|
1045 | # Search for keys in each namespace that match the given regex | |
1040 | # If a match is found, delete the key/value pair. |
|
1046 | # If a match is found, delete the key/value pair. | |
1041 | for ns in self.ns_refs_table: |
|
1047 | for ns in self.ns_refs_table: | |
1042 | for var in ns: |
|
1048 | for var in ns: | |
1043 | if m.search(var): |
|
1049 | if m.search(var): | |
1044 | del ns[var] |
|
1050 | del ns[var] | |
1045 |
|
1051 | |||
1046 | def push(self, variables, interactive=True): |
|
1052 | def push(self, variables, interactive=True): | |
1047 | """Inject a group of variables into the IPython user namespace. |
|
1053 | """Inject a group of variables into the IPython user namespace. | |
1048 |
|
1054 | |||
1049 | Parameters |
|
1055 | Parameters | |
1050 | ---------- |
|
1056 | ---------- | |
1051 | variables : dict, str or list/tuple of str |
|
1057 | variables : dict, str or list/tuple of str | |
1052 | The variables to inject into the user's namespace. If a dict, a |
|
1058 | The variables to inject into the user's namespace. If a dict, a | |
1053 | simple update is done. If a str, the string is assumed to have |
|
1059 | simple update is done. If a str, the string is assumed to have | |
1054 | variable names separated by spaces. A list/tuple of str can also |
|
1060 | variable names separated by spaces. A list/tuple of str can also | |
1055 | be used to give the variable names. If just the variable names are |
|
1061 | be used to give the variable names. If just the variable names are | |
1056 | give (list/tuple/str) then the variable values looked up in the |
|
1062 | give (list/tuple/str) then the variable values looked up in the | |
1057 | callers frame. |
|
1063 | callers frame. | |
1058 | interactive : bool |
|
1064 | interactive : bool | |
1059 | If True (default), the variables will be listed with the ``who`` |
|
1065 | If True (default), the variables will be listed with the ``who`` | |
1060 | magic. |
|
1066 | magic. | |
1061 | """ |
|
1067 | """ | |
1062 | vdict = None |
|
1068 | vdict = None | |
1063 |
|
1069 | |||
1064 | # We need a dict of name/value pairs to do namespace updates. |
|
1070 | # We need a dict of name/value pairs to do namespace updates. | |
1065 | if isinstance(variables, dict): |
|
1071 | if isinstance(variables, dict): | |
1066 | vdict = variables |
|
1072 | vdict = variables | |
1067 | elif isinstance(variables, (basestring, list, tuple)): |
|
1073 | elif isinstance(variables, (basestring, list, tuple)): | |
1068 | if isinstance(variables, basestring): |
|
1074 | if isinstance(variables, basestring): | |
1069 | vlist = variables.split() |
|
1075 | vlist = variables.split() | |
1070 | else: |
|
1076 | else: | |
1071 | vlist = variables |
|
1077 | vlist = variables | |
1072 | vdict = {} |
|
1078 | vdict = {} | |
1073 | cf = sys._getframe(1) |
|
1079 | cf = sys._getframe(1) | |
1074 | for name in vlist: |
|
1080 | for name in vlist: | |
1075 | try: |
|
1081 | try: | |
1076 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1082 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1077 | except: |
|
1083 | except: | |
1078 | print ('Could not get variable %s from %s' % |
|
1084 | print ('Could not get variable %s from %s' % | |
1079 | (name,cf.f_code.co_name)) |
|
1085 | (name,cf.f_code.co_name)) | |
1080 | else: |
|
1086 | else: | |
1081 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1087 | raise ValueError('variables must be a dict/str/list/tuple') | |
1082 |
|
1088 | |||
1083 | # Propagate variables to user namespace |
|
1089 | # Propagate variables to user namespace | |
1084 | self.user_ns.update(vdict) |
|
1090 | self.user_ns.update(vdict) | |
1085 |
|
1091 | |||
1086 | # And configure interactive visibility |
|
1092 | # And configure interactive visibility | |
1087 | config_ns = self.user_ns_hidden |
|
1093 | config_ns = self.user_ns_hidden | |
1088 | if interactive: |
|
1094 | if interactive: | |
1089 | for name, val in vdict.iteritems(): |
|
1095 | for name, val in vdict.iteritems(): | |
1090 | config_ns.pop(name, None) |
|
1096 | config_ns.pop(name, None) | |
1091 | else: |
|
1097 | else: | |
1092 | for name,val in vdict.iteritems(): |
|
1098 | for name,val in vdict.iteritems(): | |
1093 | config_ns[name] = val |
|
1099 | config_ns[name] = val | |
1094 |
|
1100 | |||
1095 | #------------------------------------------------------------------------- |
|
1101 | #------------------------------------------------------------------------- | |
1096 | # Things related to object introspection |
|
1102 | # Things related to object introspection | |
1097 | #------------------------------------------------------------------------- |
|
1103 | #------------------------------------------------------------------------- | |
1098 |
|
1104 | |||
1099 | def _ofind(self, oname, namespaces=None): |
|
1105 | def _ofind(self, oname, namespaces=None): | |
1100 | """Find an object in the available namespaces. |
|
1106 | """Find an object in the available namespaces. | |
1101 |
|
1107 | |||
1102 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1108 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1103 |
|
1109 | |||
1104 | Has special code to detect magic functions. |
|
1110 | Has special code to detect magic functions. | |
1105 | """ |
|
1111 | """ | |
1106 | #oname = oname.strip() |
|
1112 | #oname = oname.strip() | |
1107 | #print '1- oname: <%r>' % oname # dbg |
|
1113 | #print '1- oname: <%r>' % oname # dbg | |
1108 | try: |
|
1114 | try: | |
1109 | oname = oname.strip().encode('ascii') |
|
1115 | oname = oname.strip().encode('ascii') | |
1110 | #print '2- oname: <%r>' % oname # dbg |
|
1116 | #print '2- oname: <%r>' % oname # dbg | |
1111 | except UnicodeEncodeError: |
|
1117 | except UnicodeEncodeError: | |
1112 | print 'Python identifiers can only contain ascii characters.' |
|
1118 | print 'Python identifiers can only contain ascii characters.' | |
1113 | return dict(found=False) |
|
1119 | return dict(found=False) | |
1114 |
|
1120 | |||
1115 | alias_ns = None |
|
1121 | alias_ns = None | |
1116 | if namespaces is None: |
|
1122 | if namespaces is None: | |
1117 | # Namespaces to search in: |
|
1123 | # Namespaces to search in: | |
1118 | # Put them in a list. The order is important so that we |
|
1124 | # Put them in a list. The order is important so that we | |
1119 | # find things in the same order that Python finds them. |
|
1125 | # find things in the same order that Python finds them. | |
1120 | namespaces = [ ('Interactive', self.user_ns), |
|
1126 | namespaces = [ ('Interactive', self.user_ns), | |
1121 | ('IPython internal', self.internal_ns), |
|
1127 | ('IPython internal', self.internal_ns), | |
1122 | ('Python builtin', __builtin__.__dict__), |
|
1128 | ('Python builtin', __builtin__.__dict__), | |
1123 | ('Alias', self.alias_manager.alias_table), |
|
1129 | ('Alias', self.alias_manager.alias_table), | |
1124 | ] |
|
1130 | ] | |
1125 | alias_ns = self.alias_manager.alias_table |
|
1131 | alias_ns = self.alias_manager.alias_table | |
1126 |
|
1132 | |||
1127 | # initialize results to 'null' |
|
1133 | # initialize results to 'null' | |
1128 | found = False; obj = None; ospace = None; ds = None; |
|
1134 | found = False; obj = None; ospace = None; ds = None; | |
1129 | ismagic = False; isalias = False; parent = None |
|
1135 | ismagic = False; isalias = False; parent = None | |
1130 |
|
1136 | |||
1131 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1137 | # We need to special-case 'print', which as of python2.6 registers as a | |
1132 | # function but should only be treated as one if print_function was |
|
1138 | # function but should only be treated as one if print_function was | |
1133 | # loaded with a future import. In this case, just bail. |
|
1139 | # loaded with a future import. In this case, just bail. | |
1134 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1140 | if (oname == 'print' and not (self.compile.compiler_flags & | |
1135 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1141 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1136 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1142 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1137 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1143 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1138 |
|
1144 | |||
1139 | # Look for the given name by splitting it in parts. If the head is |
|
1145 | # Look for the given name by splitting it in parts. If the head is | |
1140 | # found, then we look for all the remaining parts as members, and only |
|
1146 | # found, then we look for all the remaining parts as members, and only | |
1141 | # declare success if we can find them all. |
|
1147 | # declare success if we can find them all. | |
1142 | oname_parts = oname.split('.') |
|
1148 | oname_parts = oname.split('.') | |
1143 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1149 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1144 | for nsname,ns in namespaces: |
|
1150 | for nsname,ns in namespaces: | |
1145 | try: |
|
1151 | try: | |
1146 | obj = ns[oname_head] |
|
1152 | obj = ns[oname_head] | |
1147 | except KeyError: |
|
1153 | except KeyError: | |
1148 | continue |
|
1154 | continue | |
1149 | else: |
|
1155 | else: | |
1150 | #print 'oname_rest:', oname_rest # dbg |
|
1156 | #print 'oname_rest:', oname_rest # dbg | |
1151 | for part in oname_rest: |
|
1157 | for part in oname_rest: | |
1152 | try: |
|
1158 | try: | |
1153 | parent = obj |
|
1159 | parent = obj | |
1154 | obj = getattr(obj,part) |
|
1160 | obj = getattr(obj,part) | |
1155 | except: |
|
1161 | except: | |
1156 | # Blanket except b/c some badly implemented objects |
|
1162 | # Blanket except b/c some badly implemented objects | |
1157 | # allow __getattr__ to raise exceptions other than |
|
1163 | # allow __getattr__ to raise exceptions other than | |
1158 | # AttributeError, which then crashes IPython. |
|
1164 | # AttributeError, which then crashes IPython. | |
1159 | break |
|
1165 | break | |
1160 | else: |
|
1166 | else: | |
1161 | # If we finish the for loop (no break), we got all members |
|
1167 | # If we finish the for loop (no break), we got all members | |
1162 | found = True |
|
1168 | found = True | |
1163 | ospace = nsname |
|
1169 | ospace = nsname | |
1164 | if ns == alias_ns: |
|
1170 | if ns == alias_ns: | |
1165 | isalias = True |
|
1171 | isalias = True | |
1166 | break # namespace loop |
|
1172 | break # namespace loop | |
1167 |
|
1173 | |||
1168 | # Try to see if it's magic |
|
1174 | # Try to see if it's magic | |
1169 | if not found: |
|
1175 | if not found: | |
1170 | if oname.startswith(ESC_MAGIC): |
|
1176 | if oname.startswith(ESC_MAGIC): | |
1171 | oname = oname[1:] |
|
1177 | oname = oname[1:] | |
1172 | obj = getattr(self,'magic_'+oname,None) |
|
1178 | obj = getattr(self,'magic_'+oname,None) | |
1173 | if obj is not None: |
|
1179 | if obj is not None: | |
1174 | found = True |
|
1180 | found = True | |
1175 | ospace = 'IPython internal' |
|
1181 | ospace = 'IPython internal' | |
1176 | ismagic = True |
|
1182 | ismagic = True | |
1177 |
|
1183 | |||
1178 | # Last try: special-case some literals like '', [], {}, etc: |
|
1184 | # Last try: special-case some literals like '', [], {}, etc: | |
1179 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1185 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1180 | obj = eval(oname_head) |
|
1186 | obj = eval(oname_head) | |
1181 | found = True |
|
1187 | found = True | |
1182 | ospace = 'Interactive' |
|
1188 | ospace = 'Interactive' | |
1183 |
|
1189 | |||
1184 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1190 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1185 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1191 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1186 |
|
1192 | |||
1187 | def _ofind_property(self, oname, info): |
|
1193 | def _ofind_property(self, oname, info): | |
1188 | """Second part of object finding, to look for property details.""" |
|
1194 | """Second part of object finding, to look for property details.""" | |
1189 | if info.found: |
|
1195 | if info.found: | |
1190 | # Get the docstring of the class property if it exists. |
|
1196 | # Get the docstring of the class property if it exists. | |
1191 | path = oname.split('.') |
|
1197 | path = oname.split('.') | |
1192 | root = '.'.join(path[:-1]) |
|
1198 | root = '.'.join(path[:-1]) | |
1193 | if info.parent is not None: |
|
1199 | if info.parent is not None: | |
1194 | try: |
|
1200 | try: | |
1195 | target = getattr(info.parent, '__class__') |
|
1201 | target = getattr(info.parent, '__class__') | |
1196 | # The object belongs to a class instance. |
|
1202 | # The object belongs to a class instance. | |
1197 | try: |
|
1203 | try: | |
1198 | target = getattr(target, path[-1]) |
|
1204 | target = getattr(target, path[-1]) | |
1199 | # The class defines the object. |
|
1205 | # The class defines the object. | |
1200 | if isinstance(target, property): |
|
1206 | if isinstance(target, property): | |
1201 | oname = root + '.__class__.' + path[-1] |
|
1207 | oname = root + '.__class__.' + path[-1] | |
1202 | info = Struct(self._ofind(oname)) |
|
1208 | info = Struct(self._ofind(oname)) | |
1203 | except AttributeError: pass |
|
1209 | except AttributeError: pass | |
1204 | except AttributeError: pass |
|
1210 | except AttributeError: pass | |
1205 |
|
1211 | |||
1206 | # We return either the new info or the unmodified input if the object |
|
1212 | # We return either the new info or the unmodified input if the object | |
1207 | # hadn't been found |
|
1213 | # hadn't been found | |
1208 | return info |
|
1214 | return info | |
1209 |
|
1215 | |||
1210 | def _object_find(self, oname, namespaces=None): |
|
1216 | def _object_find(self, oname, namespaces=None): | |
1211 | """Find an object and return a struct with info about it.""" |
|
1217 | """Find an object and return a struct with info about it.""" | |
1212 | inf = Struct(self._ofind(oname, namespaces)) |
|
1218 | inf = Struct(self._ofind(oname, namespaces)) | |
1213 | return Struct(self._ofind_property(oname, inf)) |
|
1219 | return Struct(self._ofind_property(oname, inf)) | |
1214 |
|
1220 | |||
1215 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1221 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1216 | """Generic interface to the inspector system. |
|
1222 | """Generic interface to the inspector system. | |
1217 |
|
1223 | |||
1218 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1224 | This function is meant to be called by pdef, pdoc & friends.""" | |
1219 | info = self._object_find(oname) |
|
1225 | info = self._object_find(oname) | |
1220 | if info.found: |
|
1226 | if info.found: | |
1221 | pmethod = getattr(self.inspector, meth) |
|
1227 | pmethod = getattr(self.inspector, meth) | |
1222 | formatter = format_screen if info.ismagic else None |
|
1228 | formatter = format_screen if info.ismagic else None | |
1223 | if meth == 'pdoc': |
|
1229 | if meth == 'pdoc': | |
1224 | pmethod(info.obj, oname, formatter) |
|
1230 | pmethod(info.obj, oname, formatter) | |
1225 | elif meth == 'pinfo': |
|
1231 | elif meth == 'pinfo': | |
1226 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1232 | pmethod(info.obj, oname, formatter, info, **kw) | |
1227 | else: |
|
1233 | else: | |
1228 | pmethod(info.obj, oname) |
|
1234 | pmethod(info.obj, oname) | |
1229 | else: |
|
1235 | else: | |
1230 | print 'Object `%s` not found.' % oname |
|
1236 | print 'Object `%s` not found.' % oname | |
1231 | return 'not found' # so callers can take other action |
|
1237 | return 'not found' # so callers can take other action | |
1232 |
|
1238 | |||
1233 | def object_inspect(self, oname): |
|
1239 | def object_inspect(self, oname): | |
1234 | info = self._object_find(oname) |
|
1240 | info = self._object_find(oname) | |
1235 | if info.found: |
|
1241 | if info.found: | |
1236 | return self.inspector.info(info.obj, oname, info=info) |
|
1242 | return self.inspector.info(info.obj, oname, info=info) | |
1237 | else: |
|
1243 | else: | |
1238 | return oinspect.object_info(name=oname, found=False) |
|
1244 | return oinspect.object_info(name=oname, found=False) | |
1239 |
|
1245 | |||
1240 | #------------------------------------------------------------------------- |
|
1246 | #------------------------------------------------------------------------- | |
1241 | # Things related to history management |
|
1247 | # Things related to history management | |
1242 | #------------------------------------------------------------------------- |
|
1248 | #------------------------------------------------------------------------- | |
1243 |
|
1249 | |||
1244 | def init_history(self): |
|
1250 | def init_history(self): | |
1245 | """Sets up the command history, and starts regular autosaves.""" |
|
1251 | """Sets up the command history, and starts regular autosaves.""" | |
1246 | self.history_manager = HistoryManager(shell=self) |
|
1252 | self.history_manager = HistoryManager(shell=self) | |
1247 |
|
1253 | |||
1248 | def save_history(self): |
|
1254 | def save_history(self): | |
1249 | """Save input history to a file (via readline library).""" |
|
1255 | """Save input history to a file (via readline library).""" | |
1250 | self.history_manager.save_history() |
|
1256 | self.history_manager.save_history() | |
1251 |
|
1257 | |||
1252 | def reload_history(self): |
|
1258 | def reload_history(self): | |
1253 | """Reload the input history from disk file.""" |
|
1259 | """Reload the input history from disk file.""" | |
1254 | self.history_manager.reload_history() |
|
1260 | self.history_manager.reload_history() | |
1255 |
|
1261 | |||
1256 | def history_saving_wrapper(self, func): |
|
1262 | def history_saving_wrapper(self, func): | |
1257 | """ Wrap func for readline history saving |
|
1263 | """ Wrap func for readline history saving | |
1258 |
|
1264 | |||
1259 | Convert func into callable that saves & restores |
|
1265 | Convert func into callable that saves & restores | |
1260 | history around the call """ |
|
1266 | history around the call """ | |
1261 |
|
1267 | |||
1262 | if self.has_readline: |
|
1268 | if self.has_readline: | |
1263 | from IPython.utils import rlineimpl as readline |
|
1269 | from IPython.utils import rlineimpl as readline | |
1264 | else: |
|
1270 | else: | |
1265 | return func |
|
1271 | return func | |
1266 |
|
1272 | |||
1267 | def wrapper(): |
|
1273 | def wrapper(): | |
1268 | self.save_history() |
|
1274 | self.save_history() | |
1269 | try: |
|
1275 | try: | |
1270 | func() |
|
1276 | func() | |
1271 | finally: |
|
1277 | finally: | |
1272 | self.reload_history() |
|
1278 | self.reload_history() | |
1273 | return wrapper |
|
1279 | return wrapper | |
1274 |
|
1280 | |||
1275 | def get_history(self, index=None, raw=False, output=True): |
|
1281 | def get_history(self, index=None, raw=False, output=True): | |
1276 | return self.history_manager.get_history(index, raw, output) |
|
1282 | return self.history_manager.get_history(index, raw, output) | |
1277 |
|
1283 | |||
1278 |
|
1284 | |||
1279 | #------------------------------------------------------------------------- |
|
1285 | #------------------------------------------------------------------------- | |
1280 | # Things related to exception handling and tracebacks (not debugging) |
|
1286 | # Things related to exception handling and tracebacks (not debugging) | |
1281 | #------------------------------------------------------------------------- |
|
1287 | #------------------------------------------------------------------------- | |
1282 |
|
1288 | |||
1283 | def init_traceback_handlers(self, custom_exceptions): |
|
1289 | def init_traceback_handlers(self, custom_exceptions): | |
1284 | # Syntax error handler. |
|
1290 | # Syntax error handler. | |
1285 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1291 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1286 |
|
1292 | |||
1287 | # The interactive one is initialized with an offset, meaning we always |
|
1293 | # The interactive one is initialized with an offset, meaning we always | |
1288 | # want to remove the topmost item in the traceback, which is our own |
|
1294 | # want to remove the topmost item in the traceback, which is our own | |
1289 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1295 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1290 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1296 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1291 | color_scheme='NoColor', |
|
1297 | color_scheme='NoColor', | |
1292 | tb_offset = 1, |
|
1298 | tb_offset = 1, | |
1293 | check_cache=self.compile.check_cache) |
|
1299 | check_cache=self.compile.check_cache) | |
1294 |
|
1300 | |||
1295 | # The instance will store a pointer to the system-wide exception hook, |
|
1301 | # The instance will store a pointer to the system-wide exception hook, | |
1296 | # so that runtime code (such as magics) can access it. This is because |
|
1302 | # so that runtime code (such as magics) can access it. This is because | |
1297 | # during the read-eval loop, it may get temporarily overwritten. |
|
1303 | # during the read-eval loop, it may get temporarily overwritten. | |
1298 | self.sys_excepthook = sys.excepthook |
|
1304 | self.sys_excepthook = sys.excepthook | |
1299 |
|
1305 | |||
1300 | # and add any custom exception handlers the user may have specified |
|
1306 | # and add any custom exception handlers the user may have specified | |
1301 | self.set_custom_exc(*custom_exceptions) |
|
1307 | self.set_custom_exc(*custom_exceptions) | |
1302 |
|
1308 | |||
1303 | # Set the exception mode |
|
1309 | # Set the exception mode | |
1304 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1310 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1305 |
|
1311 | |||
1306 | def set_custom_exc(self, exc_tuple, handler): |
|
1312 | def set_custom_exc(self, exc_tuple, handler): | |
1307 | """set_custom_exc(exc_tuple,handler) |
|
1313 | """set_custom_exc(exc_tuple,handler) | |
1308 |
|
1314 | |||
1309 | Set a custom exception handler, which will be called if any of the |
|
1315 | Set a custom exception handler, which will be called if any of the | |
1310 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1316 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1311 | run_code() method. |
|
1317 | run_code() method. | |
1312 |
|
1318 | |||
1313 | Inputs: |
|
1319 | Inputs: | |
1314 |
|
1320 | |||
1315 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1321 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1316 | handler for. It is very important that you use a tuple, and NOT A |
|
1322 | handler for. It is very important that you use a tuple, and NOT A | |
1317 | LIST here, because of the way Python's except statement works. If |
|
1323 | LIST here, because of the way Python's except statement works. If | |
1318 | you only want to trap a single exception, use a singleton tuple: |
|
1324 | you only want to trap a single exception, use a singleton tuple: | |
1319 |
|
1325 | |||
1320 | exc_tuple == (MyCustomException,) |
|
1326 | exc_tuple == (MyCustomException,) | |
1321 |
|
1327 | |||
1322 | - handler: this must be defined as a function with the following |
|
1328 | - handler: this must be defined as a function with the following | |
1323 | basic interface:: |
|
1329 | basic interface:: | |
1324 |
|
1330 | |||
1325 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1331 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1326 | ... |
|
1332 | ... | |
1327 | # The return value must be |
|
1333 | # The return value must be | |
1328 | return structured_traceback |
|
1334 | return structured_traceback | |
1329 |
|
1335 | |||
1330 | This will be made into an instance method (via types.MethodType) |
|
1336 | This will be made into an instance method (via types.MethodType) | |
1331 | of IPython itself, and it will be called if any of the exceptions |
|
1337 | of IPython itself, and it will be called if any of the exceptions | |
1332 | listed in the exc_tuple are caught. If the handler is None, an |
|
1338 | listed in the exc_tuple are caught. If the handler is None, an | |
1333 | internal basic one is used, which just prints basic info. |
|
1339 | internal basic one is used, which just prints basic info. | |
1334 |
|
1340 | |||
1335 | WARNING: by putting in your own exception handler into IPython's main |
|
1341 | WARNING: by putting in your own exception handler into IPython's main | |
1336 | execution loop, you run a very good chance of nasty crashes. This |
|
1342 | execution loop, you run a very good chance of nasty crashes. This | |
1337 | facility should only be used if you really know what you are doing.""" |
|
1343 | facility should only be used if you really know what you are doing.""" | |
1338 |
|
1344 | |||
1339 | assert type(exc_tuple)==type(()) , \ |
|
1345 | assert type(exc_tuple)==type(()) , \ | |
1340 | "The custom exceptions must be given AS A TUPLE." |
|
1346 | "The custom exceptions must be given AS A TUPLE." | |
1341 |
|
1347 | |||
1342 | def dummy_handler(self,etype,value,tb): |
|
1348 | def dummy_handler(self,etype,value,tb): | |
1343 | print '*** Simple custom exception handler ***' |
|
1349 | print '*** Simple custom exception handler ***' | |
1344 | print 'Exception type :',etype |
|
1350 | print 'Exception type :',etype | |
1345 | print 'Exception value:',value |
|
1351 | print 'Exception value:',value | |
1346 | print 'Traceback :',tb |
|
1352 | print 'Traceback :',tb | |
1347 | print 'Source code :','\n'.join(self.buffer) |
|
1353 | print 'Source code :','\n'.join(self.buffer) | |
1348 |
|
1354 | |||
1349 | if handler is None: handler = dummy_handler |
|
1355 | if handler is None: handler = dummy_handler | |
1350 |
|
1356 | |||
1351 | self.CustomTB = types.MethodType(handler,self) |
|
1357 | self.CustomTB = types.MethodType(handler,self) | |
1352 | self.custom_exceptions = exc_tuple |
|
1358 | self.custom_exceptions = exc_tuple | |
1353 |
|
1359 | |||
1354 | def excepthook(self, etype, value, tb): |
|
1360 | def excepthook(self, etype, value, tb): | |
1355 | """One more defense for GUI apps that call sys.excepthook. |
|
1361 | """One more defense for GUI apps that call sys.excepthook. | |
1356 |
|
1362 | |||
1357 | GUI frameworks like wxPython trap exceptions and call |
|
1363 | GUI frameworks like wxPython trap exceptions and call | |
1358 | sys.excepthook themselves. I guess this is a feature that |
|
1364 | sys.excepthook themselves. I guess this is a feature that | |
1359 | enables them to keep running after exceptions that would |
|
1365 | enables them to keep running after exceptions that would | |
1360 | otherwise kill their mainloop. This is a bother for IPython |
|
1366 | otherwise kill their mainloop. This is a bother for IPython | |
1361 | which excepts to catch all of the program exceptions with a try: |
|
1367 | which excepts to catch all of the program exceptions with a try: | |
1362 | except: statement. |
|
1368 | except: statement. | |
1363 |
|
1369 | |||
1364 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1370 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1365 | any app directly invokes sys.excepthook, it will look to the user like |
|
1371 | any app directly invokes sys.excepthook, it will look to the user like | |
1366 | IPython crashed. In order to work around this, we can disable the |
|
1372 | IPython crashed. In order to work around this, we can disable the | |
1367 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1373 | CrashHandler and replace it with this excepthook instead, which prints a | |
1368 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1374 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1369 | call sys.excepthook will generate a regular-looking exception from |
|
1375 | call sys.excepthook will generate a regular-looking exception from | |
1370 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1376 | IPython, and the CrashHandler will only be triggered by real IPython | |
1371 | crashes. |
|
1377 | crashes. | |
1372 |
|
1378 | |||
1373 | This hook should be used sparingly, only in places which are not likely |
|
1379 | This hook should be used sparingly, only in places which are not likely | |
1374 | to be true IPython errors. |
|
1380 | to be true IPython errors. | |
1375 | """ |
|
1381 | """ | |
1376 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1382 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1377 |
|
1383 | |||
1378 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1384 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1379 | exception_only=False): |
|
1385 | exception_only=False): | |
1380 | """Display the exception that just occurred. |
|
1386 | """Display the exception that just occurred. | |
1381 |
|
1387 | |||
1382 | If nothing is known about the exception, this is the method which |
|
1388 | If nothing is known about the exception, this is the method which | |
1383 | should be used throughout the code for presenting user tracebacks, |
|
1389 | should be used throughout the code for presenting user tracebacks, | |
1384 | rather than directly invoking the InteractiveTB object. |
|
1390 | rather than directly invoking the InteractiveTB object. | |
1385 |
|
1391 | |||
1386 | A specific showsyntaxerror() also exists, but this method can take |
|
1392 | A specific showsyntaxerror() also exists, but this method can take | |
1387 | care of calling it if needed, so unless you are explicitly catching a |
|
1393 | care of calling it if needed, so unless you are explicitly catching a | |
1388 | SyntaxError exception, don't try to analyze the stack manually and |
|
1394 | SyntaxError exception, don't try to analyze the stack manually and | |
1389 | simply call this method.""" |
|
1395 | simply call this method.""" | |
1390 |
|
1396 | |||
1391 | try: |
|
1397 | try: | |
1392 | if exc_tuple is None: |
|
1398 | if exc_tuple is None: | |
1393 | etype, value, tb = sys.exc_info() |
|
1399 | etype, value, tb = sys.exc_info() | |
1394 | else: |
|
1400 | else: | |
1395 | etype, value, tb = exc_tuple |
|
1401 | etype, value, tb = exc_tuple | |
1396 |
|
1402 | |||
1397 | if etype is None: |
|
1403 | if etype is None: | |
1398 | if hasattr(sys, 'last_type'): |
|
1404 | if hasattr(sys, 'last_type'): | |
1399 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1405 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1400 | sys.last_traceback |
|
1406 | sys.last_traceback | |
1401 | else: |
|
1407 | else: | |
1402 | self.write_err('No traceback available to show.\n') |
|
1408 | self.write_err('No traceback available to show.\n') | |
1403 | return |
|
1409 | return | |
1404 |
|
1410 | |||
1405 | if etype is SyntaxError: |
|
1411 | if etype is SyntaxError: | |
1406 | # Though this won't be called by syntax errors in the input |
|
1412 | # Though this won't be called by syntax errors in the input | |
1407 | # line, there may be SyntaxError cases whith imported code. |
|
1413 | # line, there may be SyntaxError cases whith imported code. | |
1408 | self.showsyntaxerror(filename) |
|
1414 | self.showsyntaxerror(filename) | |
1409 | elif etype is UsageError: |
|
1415 | elif etype is UsageError: | |
1410 | print "UsageError:", value |
|
1416 | print "UsageError:", value | |
1411 | else: |
|
1417 | else: | |
1412 | # WARNING: these variables are somewhat deprecated and not |
|
1418 | # WARNING: these variables are somewhat deprecated and not | |
1413 | # necessarily safe to use in a threaded environment, but tools |
|
1419 | # necessarily safe to use in a threaded environment, but tools | |
1414 | # like pdb depend on their existence, so let's set them. If we |
|
1420 | # like pdb depend on their existence, so let's set them. If we | |
1415 | # find problems in the field, we'll need to revisit their use. |
|
1421 | # find problems in the field, we'll need to revisit their use. | |
1416 | sys.last_type = etype |
|
1422 | sys.last_type = etype | |
1417 | sys.last_value = value |
|
1423 | sys.last_value = value | |
1418 | sys.last_traceback = tb |
|
1424 | sys.last_traceback = tb | |
1419 |
|
1425 | |||
1420 | if etype in self.custom_exceptions: |
|
1426 | if etype in self.custom_exceptions: | |
1421 | # FIXME: Old custom traceback objects may just return a |
|
1427 | # FIXME: Old custom traceback objects may just return a | |
1422 | # string, in that case we just put it into a list |
|
1428 | # string, in that case we just put it into a list | |
1423 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1429 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1424 | if isinstance(ctb, basestring): |
|
1430 | if isinstance(ctb, basestring): | |
1425 | stb = [stb] |
|
1431 | stb = [stb] | |
1426 | else: |
|
1432 | else: | |
1427 | if exception_only: |
|
1433 | if exception_only: | |
1428 | stb = ['An exception has occurred, use %tb to see ' |
|
1434 | stb = ['An exception has occurred, use %tb to see ' | |
1429 | 'the full traceback.\n'] |
|
1435 | 'the full traceback.\n'] | |
1430 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1436 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1431 | value)) |
|
1437 | value)) | |
1432 | else: |
|
1438 | else: | |
1433 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1439 | stb = self.InteractiveTB.structured_traceback(etype, | |
1434 | value, tb, tb_offset=tb_offset) |
|
1440 | value, tb, tb_offset=tb_offset) | |
1435 | # FIXME: the pdb calling should be done by us, not by |
|
1441 | # FIXME: the pdb calling should be done by us, not by | |
1436 | # the code computing the traceback. |
|
1442 | # the code computing the traceback. | |
1437 | if self.InteractiveTB.call_pdb: |
|
1443 | if self.InteractiveTB.call_pdb: | |
1438 | # pdb mucks up readline, fix it back |
|
1444 | # pdb mucks up readline, fix it back | |
1439 | self.set_readline_completer() |
|
1445 | self.set_readline_completer() | |
1440 |
|
1446 | |||
1441 | # Actually show the traceback |
|
1447 | # Actually show the traceback | |
1442 | self._showtraceback(etype, value, stb) |
|
1448 | self._showtraceback(etype, value, stb) | |
1443 |
|
1449 | |||
1444 | except KeyboardInterrupt: |
|
1450 | except KeyboardInterrupt: | |
1445 | self.write_err("\nKeyboardInterrupt\n") |
|
1451 | self.write_err("\nKeyboardInterrupt\n") | |
1446 |
|
1452 | |||
1447 | def _showtraceback(self, etype, evalue, stb): |
|
1453 | def _showtraceback(self, etype, evalue, stb): | |
1448 | """Actually show a traceback. |
|
1454 | """Actually show a traceback. | |
1449 |
|
1455 | |||
1450 | Subclasses may override this method to put the traceback on a different |
|
1456 | Subclasses may override this method to put the traceback on a different | |
1451 | place, like a side channel. |
|
1457 | place, like a side channel. | |
1452 | """ |
|
1458 | """ | |
1453 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1459 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) | |
1454 |
|
1460 | |||
1455 | def showsyntaxerror(self, filename=None): |
|
1461 | def showsyntaxerror(self, filename=None): | |
1456 | """Display the syntax error that just occurred. |
|
1462 | """Display the syntax error that just occurred. | |
1457 |
|
1463 | |||
1458 | This doesn't display a stack trace because there isn't one. |
|
1464 | This doesn't display a stack trace because there isn't one. | |
1459 |
|
1465 | |||
1460 | If a filename is given, it is stuffed in the exception instead |
|
1466 | If a filename is given, it is stuffed in the exception instead | |
1461 | of what was there before (because Python's parser always uses |
|
1467 | of what was there before (because Python's parser always uses | |
1462 | "<string>" when reading from a string). |
|
1468 | "<string>" when reading from a string). | |
1463 | """ |
|
1469 | """ | |
1464 | etype, value, last_traceback = sys.exc_info() |
|
1470 | etype, value, last_traceback = sys.exc_info() | |
1465 |
|
1471 | |||
1466 | # See note about these variables in showtraceback() above |
|
1472 | # See note about these variables in showtraceback() above | |
1467 | sys.last_type = etype |
|
1473 | sys.last_type = etype | |
1468 | sys.last_value = value |
|
1474 | sys.last_value = value | |
1469 | sys.last_traceback = last_traceback |
|
1475 | sys.last_traceback = last_traceback | |
1470 |
|
1476 | |||
1471 | if filename and etype is SyntaxError: |
|
1477 | if filename and etype is SyntaxError: | |
1472 | # Work hard to stuff the correct filename in the exception |
|
1478 | # Work hard to stuff the correct filename in the exception | |
1473 | try: |
|
1479 | try: | |
1474 | msg, (dummy_filename, lineno, offset, line) = value |
|
1480 | msg, (dummy_filename, lineno, offset, line) = value | |
1475 | except: |
|
1481 | except: | |
1476 | # Not the format we expect; leave it alone |
|
1482 | # Not the format we expect; leave it alone | |
1477 | pass |
|
1483 | pass | |
1478 | else: |
|
1484 | else: | |
1479 | # Stuff in the right filename |
|
1485 | # Stuff in the right filename | |
1480 | try: |
|
1486 | try: | |
1481 | # Assume SyntaxError is a class exception |
|
1487 | # Assume SyntaxError is a class exception | |
1482 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1488 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1483 | except: |
|
1489 | except: | |
1484 | # If that failed, assume SyntaxError is a string |
|
1490 | # If that failed, assume SyntaxError is a string | |
1485 | value = msg, (filename, lineno, offset, line) |
|
1491 | value = msg, (filename, lineno, offset, line) | |
1486 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1492 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1487 | self._showtraceback(etype, value, stb) |
|
1493 | self._showtraceback(etype, value, stb) | |
1488 |
|
1494 | |||
1489 | #------------------------------------------------------------------------- |
|
1495 | #------------------------------------------------------------------------- | |
1490 | # Things related to readline |
|
1496 | # Things related to readline | |
1491 | #------------------------------------------------------------------------- |
|
1497 | #------------------------------------------------------------------------- | |
1492 |
|
1498 | |||
1493 | def init_readline(self): |
|
1499 | def init_readline(self): | |
1494 | """Command history completion/saving/reloading.""" |
|
1500 | """Command history completion/saving/reloading.""" | |
1495 |
|
1501 | |||
1496 | if self.readline_use: |
|
1502 | if self.readline_use: | |
1497 | import IPython.utils.rlineimpl as readline |
|
1503 | import IPython.utils.rlineimpl as readline | |
1498 |
|
1504 | |||
1499 | self.rl_next_input = None |
|
1505 | self.rl_next_input = None | |
1500 | self.rl_do_indent = False |
|
1506 | self.rl_do_indent = False | |
1501 |
|
1507 | |||
1502 | if not self.readline_use or not readline.have_readline: |
|
1508 | if not self.readline_use or not readline.have_readline: | |
1503 | self.has_readline = False |
|
1509 | self.has_readline = False | |
1504 | self.readline = None |
|
1510 | self.readline = None | |
1505 | # Set a number of methods that depend on readline to be no-op |
|
1511 | # Set a number of methods that depend on readline to be no-op | |
1506 | self.set_readline_completer = no_op |
|
1512 | self.set_readline_completer = no_op | |
1507 | self.set_custom_completer = no_op |
|
1513 | self.set_custom_completer = no_op | |
1508 | self.set_completer_frame = no_op |
|
1514 | self.set_completer_frame = no_op | |
1509 | warn('Readline services not available or not loaded.') |
|
1515 | warn('Readline services not available or not loaded.') | |
1510 | else: |
|
1516 | else: | |
1511 | self.has_readline = True |
|
1517 | self.has_readline = True | |
1512 | self.readline = readline |
|
1518 | self.readline = readline | |
1513 | sys.modules['readline'] = readline |
|
1519 | sys.modules['readline'] = readline | |
1514 |
|
1520 | |||
1515 | # Platform-specific configuration |
|
1521 | # Platform-specific configuration | |
1516 | if os.name == 'nt': |
|
1522 | if os.name == 'nt': | |
1517 | # FIXME - check with Frederick to see if we can harmonize |
|
1523 | # FIXME - check with Frederick to see if we can harmonize | |
1518 | # naming conventions with pyreadline to avoid this |
|
1524 | # naming conventions with pyreadline to avoid this | |
1519 | # platform-dependent check |
|
1525 | # platform-dependent check | |
1520 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1526 | self.readline_startup_hook = readline.set_pre_input_hook | |
1521 | else: |
|
1527 | else: | |
1522 | self.readline_startup_hook = readline.set_startup_hook |
|
1528 | self.readline_startup_hook = readline.set_startup_hook | |
1523 |
|
1529 | |||
1524 | # Load user's initrc file (readline config) |
|
1530 | # Load user's initrc file (readline config) | |
1525 | # Or if libedit is used, load editrc. |
|
1531 | # Or if libedit is used, load editrc. | |
1526 | inputrc_name = os.environ.get('INPUTRC') |
|
1532 | inputrc_name = os.environ.get('INPUTRC') | |
1527 | if inputrc_name is None: |
|
1533 | if inputrc_name is None: | |
1528 | home_dir = get_home_dir() |
|
1534 | home_dir = get_home_dir() | |
1529 | if home_dir is not None: |
|
1535 | if home_dir is not None: | |
1530 | inputrc_name = '.inputrc' |
|
1536 | inputrc_name = '.inputrc' | |
1531 | if readline.uses_libedit: |
|
1537 | if readline.uses_libedit: | |
1532 | inputrc_name = '.editrc' |
|
1538 | inputrc_name = '.editrc' | |
1533 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1539 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1534 | if os.path.isfile(inputrc_name): |
|
1540 | if os.path.isfile(inputrc_name): | |
1535 | try: |
|
1541 | try: | |
1536 | readline.read_init_file(inputrc_name) |
|
1542 | readline.read_init_file(inputrc_name) | |
1537 | except: |
|
1543 | except: | |
1538 | warn('Problems reading readline initialization file <%s>' |
|
1544 | warn('Problems reading readline initialization file <%s>' | |
1539 | % inputrc_name) |
|
1545 | % inputrc_name) | |
1540 |
|
1546 | |||
1541 | # Configure readline according to user's prefs |
|
1547 | # Configure readline according to user's prefs | |
1542 | # This is only done if GNU readline is being used. If libedit |
|
1548 | # This is only done if GNU readline is being used. If libedit | |
1543 | # is being used (as on Leopard) the readline config is |
|
1549 | # is being used (as on Leopard) the readline config is | |
1544 | # not run as the syntax for libedit is different. |
|
1550 | # not run as the syntax for libedit is different. | |
1545 | if not readline.uses_libedit: |
|
1551 | if not readline.uses_libedit: | |
1546 | for rlcommand in self.readline_parse_and_bind: |
|
1552 | for rlcommand in self.readline_parse_and_bind: | |
1547 | #print "loading rl:",rlcommand # dbg |
|
1553 | #print "loading rl:",rlcommand # dbg | |
1548 | readline.parse_and_bind(rlcommand) |
|
1554 | readline.parse_and_bind(rlcommand) | |
1549 |
|
1555 | |||
1550 | # Remove some chars from the delimiters list. If we encounter |
|
1556 | # Remove some chars from the delimiters list. If we encounter | |
1551 | # unicode chars, discard them. |
|
1557 | # unicode chars, discard them. | |
1552 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1558 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1553 | delims = delims.translate(None, self.readline_remove_delims) |
|
1559 | delims = delims.translate(None, self.readline_remove_delims) | |
1554 | delims = delims.replace(ESC_MAGIC, '') |
|
1560 | delims = delims.replace(ESC_MAGIC, '') | |
1555 | readline.set_completer_delims(delims) |
|
1561 | readline.set_completer_delims(delims) | |
1556 | # otherwise we end up with a monster history after a while: |
|
1562 | # otherwise we end up with a monster history after a while: | |
1557 | readline.set_history_length(self.history_length) |
|
1563 | readline.set_history_length(self.history_length) | |
1558 | try: |
|
1564 | try: | |
1559 | #print '*** Reading readline history' # dbg |
|
1565 | #print '*** Reading readline history' # dbg | |
1560 | self.reload_history() |
|
1566 | self.reload_history() | |
1561 | except IOError: |
|
1567 | except IOError: | |
1562 | pass # It doesn't exist yet. |
|
1568 | pass # It doesn't exist yet. | |
1563 |
|
1569 | |||
1564 | # Configure auto-indent for all platforms |
|
1570 | # Configure auto-indent for all platforms | |
1565 | self.set_autoindent(self.autoindent) |
|
1571 | self.set_autoindent(self.autoindent) | |
1566 |
|
1572 | |||
1567 | def set_next_input(self, s): |
|
1573 | def set_next_input(self, s): | |
1568 | """ Sets the 'default' input string for the next command line. |
|
1574 | """ Sets the 'default' input string for the next command line. | |
1569 |
|
1575 | |||
1570 | Requires readline. |
|
1576 | Requires readline. | |
1571 |
|
1577 | |||
1572 | Example: |
|
1578 | Example: | |
1573 |
|
1579 | |||
1574 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1580 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1575 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1581 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1576 | """ |
|
1582 | """ | |
1577 |
|
1583 | |||
1578 | self.rl_next_input = s |
|
1584 | self.rl_next_input = s | |
1579 |
|
1585 | |||
1580 | # Maybe move this to the terminal subclass? |
|
1586 | # Maybe move this to the terminal subclass? | |
1581 | def pre_readline(self): |
|
1587 | def pre_readline(self): | |
1582 | """readline hook to be used at the start of each line. |
|
1588 | """readline hook to be used at the start of each line. | |
1583 |
|
1589 | |||
1584 | Currently it handles auto-indent only.""" |
|
1590 | Currently it handles auto-indent only.""" | |
1585 |
|
1591 | |||
1586 | if self.rl_do_indent: |
|
1592 | if self.rl_do_indent: | |
1587 | self.readline.insert_text(self._indent_current_str()) |
|
1593 | self.readline.insert_text(self._indent_current_str()) | |
1588 | if self.rl_next_input is not None: |
|
1594 | if self.rl_next_input is not None: | |
1589 | self.readline.insert_text(self.rl_next_input) |
|
1595 | self.readline.insert_text(self.rl_next_input) | |
1590 | self.rl_next_input = None |
|
1596 | self.rl_next_input = None | |
1591 |
|
1597 | |||
1592 | def _indent_current_str(self): |
|
1598 | def _indent_current_str(self): | |
1593 | """return the current level of indentation as a string""" |
|
1599 | """return the current level of indentation as a string""" | |
1594 | return self.input_splitter.indent_spaces * ' ' |
|
1600 | return self.input_splitter.indent_spaces * ' ' | |
1595 |
|
1601 | |||
1596 | #------------------------------------------------------------------------- |
|
1602 | #------------------------------------------------------------------------- | |
1597 | # Things related to text completion |
|
1603 | # Things related to text completion | |
1598 | #------------------------------------------------------------------------- |
|
1604 | #------------------------------------------------------------------------- | |
1599 |
|
1605 | |||
1600 | def init_completer(self): |
|
1606 | def init_completer(self): | |
1601 | """Initialize the completion machinery. |
|
1607 | """Initialize the completion machinery. | |
1602 |
|
1608 | |||
1603 | This creates completion machinery that can be used by client code, |
|
1609 | This creates completion machinery that can be used by client code, | |
1604 | either interactively in-process (typically triggered by the readline |
|
1610 | either interactively in-process (typically triggered by the readline | |
1605 | library), programatically (such as in test suites) or out-of-prcess |
|
1611 | library), programatically (such as in test suites) or out-of-prcess | |
1606 | (typically over the network by remote frontends). |
|
1612 | (typically over the network by remote frontends). | |
1607 | """ |
|
1613 | """ | |
1608 | from IPython.core.completer import IPCompleter |
|
1614 | from IPython.core.completer import IPCompleter | |
1609 | from IPython.core.completerlib import (module_completer, |
|
1615 | from IPython.core.completerlib import (module_completer, | |
1610 | magic_run_completer, cd_completer) |
|
1616 | magic_run_completer, cd_completer) | |
1611 |
|
1617 | |||
1612 | self.Completer = IPCompleter(self, |
|
1618 | self.Completer = IPCompleter(self, | |
1613 | self.user_ns, |
|
1619 | self.user_ns, | |
1614 | self.user_global_ns, |
|
1620 | self.user_global_ns, | |
1615 | self.readline_omit__names, |
|
1621 | self.readline_omit__names, | |
1616 | self.alias_manager.alias_table, |
|
1622 | self.alias_manager.alias_table, | |
1617 | self.has_readline) |
|
1623 | self.has_readline) | |
1618 |
|
1624 | |||
1619 | # Add custom completers to the basic ones built into IPCompleter |
|
1625 | # Add custom completers to the basic ones built into IPCompleter | |
1620 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1626 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1621 | self.strdispatchers['complete_command'] = sdisp |
|
1627 | self.strdispatchers['complete_command'] = sdisp | |
1622 | self.Completer.custom_completers = sdisp |
|
1628 | self.Completer.custom_completers = sdisp | |
1623 |
|
1629 | |||
1624 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1630 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1625 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1631 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1626 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1632 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1627 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1633 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1628 |
|
1634 | |||
1629 | # Only configure readline if we truly are using readline. IPython can |
|
1635 | # Only configure readline if we truly are using readline. IPython can | |
1630 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1636 | # do tab-completion over the network, in GUIs, etc, where readline | |
1631 | # itself may be absent |
|
1637 | # itself may be absent | |
1632 | if self.has_readline: |
|
1638 | if self.has_readline: | |
1633 | self.set_readline_completer() |
|
1639 | self.set_readline_completer() | |
1634 |
|
1640 | |||
1635 | def complete(self, text, line=None, cursor_pos=None): |
|
1641 | def complete(self, text, line=None, cursor_pos=None): | |
1636 | """Return the completed text and a list of completions. |
|
1642 | """Return the completed text and a list of completions. | |
1637 |
|
1643 | |||
1638 | Parameters |
|
1644 | Parameters | |
1639 | ---------- |
|
1645 | ---------- | |
1640 |
|
1646 | |||
1641 | text : string |
|
1647 | text : string | |
1642 | A string of text to be completed on. It can be given as empty and |
|
1648 | A string of text to be completed on. It can be given as empty and | |
1643 | instead a line/position pair are given. In this case, the |
|
1649 | instead a line/position pair are given. In this case, the | |
1644 | completer itself will split the line like readline does. |
|
1650 | completer itself will split the line like readline does. | |
1645 |
|
1651 | |||
1646 | line : string, optional |
|
1652 | line : string, optional | |
1647 | The complete line that text is part of. |
|
1653 | The complete line that text is part of. | |
1648 |
|
1654 | |||
1649 | cursor_pos : int, optional |
|
1655 | cursor_pos : int, optional | |
1650 | The position of the cursor on the input line. |
|
1656 | The position of the cursor on the input line. | |
1651 |
|
1657 | |||
1652 | Returns |
|
1658 | Returns | |
1653 | ------- |
|
1659 | ------- | |
1654 | text : string |
|
1660 | text : string | |
1655 | The actual text that was completed. |
|
1661 | The actual text that was completed. | |
1656 |
|
1662 | |||
1657 | matches : list |
|
1663 | matches : list | |
1658 | A sorted list with all possible completions. |
|
1664 | A sorted list with all possible completions. | |
1659 |
|
1665 | |||
1660 | The optional arguments allow the completion to take more context into |
|
1666 | The optional arguments allow the completion to take more context into | |
1661 | account, and are part of the low-level completion API. |
|
1667 | account, and are part of the low-level completion API. | |
1662 |
|
1668 | |||
1663 | This is a wrapper around the completion mechanism, similar to what |
|
1669 | This is a wrapper around the completion mechanism, similar to what | |
1664 | readline does at the command line when the TAB key is hit. By |
|
1670 | readline does at the command line when the TAB key is hit. By | |
1665 | exposing it as a method, it can be used by other non-readline |
|
1671 | exposing it as a method, it can be used by other non-readline | |
1666 | environments (such as GUIs) for text completion. |
|
1672 | environments (such as GUIs) for text completion. | |
1667 |
|
1673 | |||
1668 | Simple usage example: |
|
1674 | Simple usage example: | |
1669 |
|
1675 | |||
1670 | In [1]: x = 'hello' |
|
1676 | In [1]: x = 'hello' | |
1671 |
|
1677 | |||
1672 | In [2]: _ip.complete('x.l') |
|
1678 | In [2]: _ip.complete('x.l') | |
1673 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1679 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1674 | """ |
|
1680 | """ | |
1675 |
|
1681 | |||
1676 | # Inject names into __builtin__ so we can complete on the added names. |
|
1682 | # Inject names into __builtin__ so we can complete on the added names. | |
1677 | with self.builtin_trap: |
|
1683 | with self.builtin_trap: | |
1678 | return self.Completer.complete(text, line, cursor_pos) |
|
1684 | return self.Completer.complete(text, line, cursor_pos) | |
1679 |
|
1685 | |||
1680 | def set_custom_completer(self, completer, pos=0): |
|
1686 | def set_custom_completer(self, completer, pos=0): | |
1681 | """Adds a new custom completer function. |
|
1687 | """Adds a new custom completer function. | |
1682 |
|
1688 | |||
1683 | The position argument (defaults to 0) is the index in the completers |
|
1689 | The position argument (defaults to 0) is the index in the completers | |
1684 | list where you want the completer to be inserted.""" |
|
1690 | list where you want the completer to be inserted.""" | |
1685 |
|
1691 | |||
1686 | newcomp = types.MethodType(completer,self.Completer) |
|
1692 | newcomp = types.MethodType(completer,self.Completer) | |
1687 | self.Completer.matchers.insert(pos,newcomp) |
|
1693 | self.Completer.matchers.insert(pos,newcomp) | |
1688 |
|
1694 | |||
1689 | def set_readline_completer(self): |
|
1695 | def set_readline_completer(self): | |
1690 | """Reset readline's completer to be our own.""" |
|
1696 | """Reset readline's completer to be our own.""" | |
1691 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1697 | self.readline.set_completer(self.Completer.rlcomplete) | |
1692 |
|
1698 | |||
1693 | def set_completer_frame(self, frame=None): |
|
1699 | def set_completer_frame(self, frame=None): | |
1694 | """Set the frame of the completer.""" |
|
1700 | """Set the frame of the completer.""" | |
1695 | if frame: |
|
1701 | if frame: | |
1696 | self.Completer.namespace = frame.f_locals |
|
1702 | self.Completer.namespace = frame.f_locals | |
1697 | self.Completer.global_namespace = frame.f_globals |
|
1703 | self.Completer.global_namespace = frame.f_globals | |
1698 | else: |
|
1704 | else: | |
1699 | self.Completer.namespace = self.user_ns |
|
1705 | self.Completer.namespace = self.user_ns | |
1700 | self.Completer.global_namespace = self.user_global_ns |
|
1706 | self.Completer.global_namespace = self.user_global_ns | |
1701 |
|
1707 | |||
1702 | #------------------------------------------------------------------------- |
|
1708 | #------------------------------------------------------------------------- | |
1703 | # Things related to magics |
|
1709 | # Things related to magics | |
1704 | #------------------------------------------------------------------------- |
|
1710 | #------------------------------------------------------------------------- | |
1705 |
|
1711 | |||
1706 | def init_magics(self): |
|
1712 | def init_magics(self): | |
1707 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1713 | # FIXME: Move the color initialization to the DisplayHook, which | |
1708 | # should be split into a prompt manager and displayhook. We probably |
|
1714 | # should be split into a prompt manager and displayhook. We probably | |
1709 | # even need a centralize colors management object. |
|
1715 | # even need a centralize colors management object. | |
1710 | self.magic_colors(self.colors) |
|
1716 | self.magic_colors(self.colors) | |
1711 | # History was moved to a separate module |
|
1717 | # History was moved to a separate module | |
1712 | from . import history |
|
1718 | from . import history | |
1713 | history.init_ipython(self) |
|
1719 | history.init_ipython(self) | |
1714 |
|
1720 | |||
1715 | def magic(self,arg_s): |
|
1721 | def magic(self,arg_s): | |
1716 | """Call a magic function by name. |
|
1722 | """Call a magic function by name. | |
1717 |
|
1723 | |||
1718 | Input: a string containing the name of the magic function to call and |
|
1724 | Input: a string containing the name of the magic function to call and | |
1719 | any additional arguments to be passed to the magic. |
|
1725 | any additional arguments to be passed to the magic. | |
1720 |
|
1726 | |||
1721 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1727 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1722 | prompt: |
|
1728 | prompt: | |
1723 |
|
1729 | |||
1724 | In[1]: %name -opt foo bar |
|
1730 | In[1]: %name -opt foo bar | |
1725 |
|
1731 | |||
1726 | To call a magic without arguments, simply use magic('name'). |
|
1732 | To call a magic without arguments, simply use magic('name'). | |
1727 |
|
1733 | |||
1728 | This provides a proper Python function to call IPython's magics in any |
|
1734 | This provides a proper Python function to call IPython's magics in any | |
1729 | valid Python code you can type at the interpreter, including loops and |
|
1735 | valid Python code you can type at the interpreter, including loops and | |
1730 | compound statements. |
|
1736 | compound statements. | |
1731 | """ |
|
1737 | """ | |
1732 | args = arg_s.split(' ',1) |
|
1738 | args = arg_s.split(' ',1) | |
1733 | magic_name = args[0] |
|
1739 | magic_name = args[0] | |
1734 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1740 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1735 |
|
1741 | |||
1736 | try: |
|
1742 | try: | |
1737 | magic_args = args[1] |
|
1743 | magic_args = args[1] | |
1738 | except IndexError: |
|
1744 | except IndexError: | |
1739 | magic_args = '' |
|
1745 | magic_args = '' | |
1740 | fn = getattr(self,'magic_'+magic_name,None) |
|
1746 | fn = getattr(self,'magic_'+magic_name,None) | |
1741 | if fn is None: |
|
1747 | if fn is None: | |
1742 | error("Magic function `%s` not found." % magic_name) |
|
1748 | error("Magic function `%s` not found." % magic_name) | |
1743 | else: |
|
1749 | else: | |
1744 | magic_args = self.var_expand(magic_args,1) |
|
1750 | magic_args = self.var_expand(magic_args,1) | |
1745 | with nested(self.builtin_trap,): |
|
1751 | with nested(self.builtin_trap,): | |
1746 | result = fn(magic_args) |
|
1752 | result = fn(magic_args) | |
1747 | return result |
|
1753 | return result | |
1748 |
|
1754 | |||
1749 | def define_magic(self, magicname, func): |
|
1755 | def define_magic(self, magicname, func): | |
1750 | """Expose own function as magic function for ipython |
|
1756 | """Expose own function as magic function for ipython | |
1751 |
|
1757 | |||
1752 | def foo_impl(self,parameter_s=''): |
|
1758 | def foo_impl(self,parameter_s=''): | |
1753 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1759 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1754 | print 'Magic function. Passed parameter is between < >:' |
|
1760 | print 'Magic function. Passed parameter is between < >:' | |
1755 | print '<%s>' % parameter_s |
|
1761 | print '<%s>' % parameter_s | |
1756 | print 'The self object is:',self |
|
1762 | print 'The self object is:',self | |
1757 |
|
1763 | |||
1758 | self.define_magic('foo',foo_impl) |
|
1764 | self.define_magic('foo',foo_impl) | |
1759 | """ |
|
1765 | """ | |
1760 |
|
1766 | |||
1761 | import new |
|
1767 | import new | |
1762 | im = types.MethodType(func,self) |
|
1768 | im = types.MethodType(func,self) | |
1763 | old = getattr(self, "magic_" + magicname, None) |
|
1769 | old = getattr(self, "magic_" + magicname, None) | |
1764 | setattr(self, "magic_" + magicname, im) |
|
1770 | setattr(self, "magic_" + magicname, im) | |
1765 | return old |
|
1771 | return old | |
1766 |
|
1772 | |||
1767 | #------------------------------------------------------------------------- |
|
1773 | #------------------------------------------------------------------------- | |
1768 | # Things related to macros |
|
1774 | # Things related to macros | |
1769 | #------------------------------------------------------------------------- |
|
1775 | #------------------------------------------------------------------------- | |
1770 |
|
1776 | |||
1771 | def define_macro(self, name, themacro): |
|
1777 | def define_macro(self, name, themacro): | |
1772 | """Define a new macro |
|
1778 | """Define a new macro | |
1773 |
|
1779 | |||
1774 | Parameters |
|
1780 | Parameters | |
1775 | ---------- |
|
1781 | ---------- | |
1776 | name : str |
|
1782 | name : str | |
1777 | The name of the macro. |
|
1783 | The name of the macro. | |
1778 | themacro : str or Macro |
|
1784 | themacro : str or Macro | |
1779 | The action to do upon invoking the macro. If a string, a new |
|
1785 | The action to do upon invoking the macro. If a string, a new | |
1780 | Macro object is created by passing the string to it. |
|
1786 | Macro object is created by passing the string to it. | |
1781 | """ |
|
1787 | """ | |
1782 |
|
1788 | |||
1783 | from IPython.core import macro |
|
1789 | from IPython.core import macro | |
1784 |
|
1790 | |||
1785 | if isinstance(themacro, basestring): |
|
1791 | if isinstance(themacro, basestring): | |
1786 | themacro = macro.Macro(themacro) |
|
1792 | themacro = macro.Macro(themacro) | |
1787 | if not isinstance(themacro, macro.Macro): |
|
1793 | if not isinstance(themacro, macro.Macro): | |
1788 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1794 | raise ValueError('A macro must be a string or a Macro instance.') | |
1789 | self.user_ns[name] = themacro |
|
1795 | self.user_ns[name] = themacro | |
1790 |
|
1796 | |||
1791 | #------------------------------------------------------------------------- |
|
1797 | #------------------------------------------------------------------------- | |
1792 | # Things related to the running of system commands |
|
1798 | # Things related to the running of system commands | |
1793 | #------------------------------------------------------------------------- |
|
1799 | #------------------------------------------------------------------------- | |
1794 |
|
1800 | |||
1795 | def system(self, cmd): |
|
1801 | def system(self, cmd): | |
1796 | """Call the given cmd in a subprocess. |
|
1802 | """Call the given cmd in a subprocess. | |
1797 |
|
1803 | |||
1798 | Parameters |
|
1804 | Parameters | |
1799 | ---------- |
|
1805 | ---------- | |
1800 | cmd : str |
|
1806 | cmd : str | |
1801 | Command to execute (can not end in '&', as bacground processes are |
|
1807 | Command to execute (can not end in '&', as bacground processes are | |
1802 | not supported. |
|
1808 | not supported. | |
1803 | """ |
|
1809 | """ | |
1804 | # We do not support backgrounding processes because we either use |
|
1810 | # We do not support backgrounding processes because we either use | |
1805 | # pexpect or pipes to read from. Users can always just call |
|
1811 | # pexpect or pipes to read from. Users can always just call | |
1806 | # os.system() if they really want a background process. |
|
1812 | # os.system() if they really want a background process. | |
1807 | if cmd.endswith('&'): |
|
1813 | if cmd.endswith('&'): | |
1808 | raise OSError("Background processes not supported.") |
|
1814 | raise OSError("Background processes not supported.") | |
1809 |
|
1815 | |||
1810 | return system(self.var_expand(cmd, depth=2)) |
|
1816 | return system(self.var_expand(cmd, depth=2)) | |
1811 |
|
1817 | |||
1812 | def getoutput(self, cmd, split=True): |
|
1818 | def getoutput(self, cmd, split=True): | |
1813 | """Get output (possibly including stderr) from a subprocess. |
|
1819 | """Get output (possibly including stderr) from a subprocess. | |
1814 |
|
1820 | |||
1815 | Parameters |
|
1821 | Parameters | |
1816 | ---------- |
|
1822 | ---------- | |
1817 | cmd : str |
|
1823 | cmd : str | |
1818 | Command to execute (can not end in '&', as background processes are |
|
1824 | Command to execute (can not end in '&', as background processes are | |
1819 | not supported. |
|
1825 | not supported. | |
1820 | split : bool, optional |
|
1826 | split : bool, optional | |
1821 |
|
1827 | |||
1822 | If True, split the output into an IPython SList. Otherwise, an |
|
1828 | If True, split the output into an IPython SList. Otherwise, an | |
1823 | IPython LSString is returned. These are objects similar to normal |
|
1829 | IPython LSString is returned. These are objects similar to normal | |
1824 | lists and strings, with a few convenience attributes for easier |
|
1830 | lists and strings, with a few convenience attributes for easier | |
1825 | manipulation of line-based output. You can use '?' on them for |
|
1831 | manipulation of line-based output. You can use '?' on them for | |
1826 | details. |
|
1832 | details. | |
1827 | """ |
|
1833 | """ | |
1828 | if cmd.endswith('&'): |
|
1834 | if cmd.endswith('&'): | |
1829 | raise OSError("Background processes not supported.") |
|
1835 | raise OSError("Background processes not supported.") | |
1830 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1836 | out = getoutput(self.var_expand(cmd, depth=2)) | |
1831 | if split: |
|
1837 | if split: | |
1832 | out = SList(out.splitlines()) |
|
1838 | out = SList(out.splitlines()) | |
1833 | else: |
|
1839 | else: | |
1834 | out = LSString(out) |
|
1840 | out = LSString(out) | |
1835 | return out |
|
1841 | return out | |
1836 |
|
1842 | |||
1837 | #------------------------------------------------------------------------- |
|
1843 | #------------------------------------------------------------------------- | |
1838 | # Things related to aliases |
|
1844 | # Things related to aliases | |
1839 | #------------------------------------------------------------------------- |
|
1845 | #------------------------------------------------------------------------- | |
1840 |
|
1846 | |||
1841 | def init_alias(self): |
|
1847 | def init_alias(self): | |
1842 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1848 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1843 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1849 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1844 |
|
1850 | |||
1845 | #------------------------------------------------------------------------- |
|
1851 | #------------------------------------------------------------------------- | |
1846 | # Things related to extensions and plugins |
|
1852 | # Things related to extensions and plugins | |
1847 | #------------------------------------------------------------------------- |
|
1853 | #------------------------------------------------------------------------- | |
1848 |
|
1854 | |||
1849 | def init_extension_manager(self): |
|
1855 | def init_extension_manager(self): | |
1850 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1856 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1851 |
|
1857 | |||
1852 | def init_plugin_manager(self): |
|
1858 | def init_plugin_manager(self): | |
1853 | self.plugin_manager = PluginManager(config=self.config) |
|
1859 | self.plugin_manager = PluginManager(config=self.config) | |
1854 |
|
1860 | |||
1855 | #------------------------------------------------------------------------- |
|
1861 | #------------------------------------------------------------------------- | |
1856 | # Things related to payloads |
|
1862 | # Things related to payloads | |
1857 | #------------------------------------------------------------------------- |
|
1863 | #------------------------------------------------------------------------- | |
1858 |
|
1864 | |||
1859 | def init_payload(self): |
|
1865 | def init_payload(self): | |
1860 | self.payload_manager = PayloadManager(config=self.config) |
|
1866 | self.payload_manager = PayloadManager(config=self.config) | |
1861 |
|
1867 | |||
1862 | #------------------------------------------------------------------------- |
|
1868 | #------------------------------------------------------------------------- | |
1863 | # Things related to the prefilter |
|
1869 | # Things related to the prefilter | |
1864 | #------------------------------------------------------------------------- |
|
1870 | #------------------------------------------------------------------------- | |
1865 |
|
1871 | |||
1866 | def init_prefilter(self): |
|
1872 | def init_prefilter(self): | |
1867 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1873 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1868 | # Ultimately this will be refactored in the new interpreter code, but |
|
1874 | # Ultimately this will be refactored in the new interpreter code, but | |
1869 | # for now, we should expose the main prefilter method (there's legacy |
|
1875 | # for now, we should expose the main prefilter method (there's legacy | |
1870 | # code out there that may rely on this). |
|
1876 | # code out there that may rely on this). | |
1871 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1877 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1872 |
|
1878 | |||
1873 | def auto_rewrite_input(self, cmd): |
|
1879 | def auto_rewrite_input(self, cmd): | |
1874 | """Print to the screen the rewritten form of the user's command. |
|
1880 | """Print to the screen the rewritten form of the user's command. | |
1875 |
|
1881 | |||
1876 | This shows visual feedback by rewriting input lines that cause |
|
1882 | This shows visual feedback by rewriting input lines that cause | |
1877 | automatic calling to kick in, like:: |
|
1883 | automatic calling to kick in, like:: | |
1878 |
|
1884 | |||
1879 | /f x |
|
1885 | /f x | |
1880 |
|
1886 | |||
1881 | into:: |
|
1887 | into:: | |
1882 |
|
1888 | |||
1883 | ------> f(x) |
|
1889 | ------> f(x) | |
1884 |
|
1890 | |||
1885 | after the user's input prompt. This helps the user understand that the |
|
1891 | after the user's input prompt. This helps the user understand that the | |
1886 | input line was transformed automatically by IPython. |
|
1892 | input line was transformed automatically by IPython. | |
1887 | """ |
|
1893 | """ | |
1888 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1894 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
1889 |
|
1895 | |||
1890 | try: |
|
1896 | try: | |
1891 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1897 | # plain ascii works better w/ pyreadline, on some machines, so | |
1892 | # we use it and only print uncolored rewrite if we have unicode |
|
1898 | # we use it and only print uncolored rewrite if we have unicode | |
1893 | rw = str(rw) |
|
1899 | rw = str(rw) | |
1894 | print >> IPython.utils.io.Term.cout, rw |
|
1900 | print >> IPython.utils.io.Term.cout, rw | |
1895 | except UnicodeEncodeError: |
|
1901 | except UnicodeEncodeError: | |
1896 | print "------> " + cmd |
|
1902 | print "------> " + cmd | |
1897 |
|
1903 | |||
1898 | #------------------------------------------------------------------------- |
|
1904 | #------------------------------------------------------------------------- | |
1899 | # Things related to extracting values/expressions from kernel and user_ns |
|
1905 | # Things related to extracting values/expressions from kernel and user_ns | |
1900 | #------------------------------------------------------------------------- |
|
1906 | #------------------------------------------------------------------------- | |
1901 |
|
1907 | |||
1902 | def _simple_error(self): |
|
1908 | def _simple_error(self): | |
1903 | etype, value = sys.exc_info()[:2] |
|
1909 | etype, value = sys.exc_info()[:2] | |
1904 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1910 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1905 |
|
1911 | |||
1906 | def user_variables(self, names): |
|
1912 | def user_variables(self, names): | |
1907 | """Get a list of variable names from the user's namespace. |
|
1913 | """Get a list of variable names from the user's namespace. | |
1908 |
|
1914 | |||
1909 | Parameters |
|
1915 | Parameters | |
1910 | ---------- |
|
1916 | ---------- | |
1911 | names : list of strings |
|
1917 | names : list of strings | |
1912 | A list of names of variables to be read from the user namespace. |
|
1918 | A list of names of variables to be read from the user namespace. | |
1913 |
|
1919 | |||
1914 | Returns |
|
1920 | Returns | |
1915 | ------- |
|
1921 | ------- | |
1916 | A dict, keyed by the input names and with the repr() of each value. |
|
1922 | A dict, keyed by the input names and with the repr() of each value. | |
1917 | """ |
|
1923 | """ | |
1918 | out = {} |
|
1924 | out = {} | |
1919 | user_ns = self.user_ns |
|
1925 | user_ns = self.user_ns | |
1920 | for varname in names: |
|
1926 | for varname in names: | |
1921 | try: |
|
1927 | try: | |
1922 | value = repr(user_ns[varname]) |
|
1928 | value = repr(user_ns[varname]) | |
1923 | except: |
|
1929 | except: | |
1924 | value = self._simple_error() |
|
1930 | value = self._simple_error() | |
1925 | out[varname] = value |
|
1931 | out[varname] = value | |
1926 | return out |
|
1932 | return out | |
1927 |
|
1933 | |||
1928 | def user_expressions(self, expressions): |
|
1934 | def user_expressions(self, expressions): | |
1929 | """Evaluate a dict of expressions in the user's namespace. |
|
1935 | """Evaluate a dict of expressions in the user's namespace. | |
1930 |
|
1936 | |||
1931 | Parameters |
|
1937 | Parameters | |
1932 | ---------- |
|
1938 | ---------- | |
1933 | expressions : dict |
|
1939 | expressions : dict | |
1934 | A dict with string keys and string values. The expression values |
|
1940 | A dict with string keys and string values. The expression values | |
1935 | should be valid Python expressions, each of which will be evaluated |
|
1941 | should be valid Python expressions, each of which will be evaluated | |
1936 | in the user namespace. |
|
1942 | in the user namespace. | |
1937 |
|
1943 | |||
1938 | Returns |
|
1944 | Returns | |
1939 | ------- |
|
1945 | ------- | |
1940 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1946 | A dict, keyed like the input expressions dict, with the repr() of each | |
1941 | value. |
|
1947 | value. | |
1942 | """ |
|
1948 | """ | |
1943 | out = {} |
|
1949 | out = {} | |
1944 | user_ns = self.user_ns |
|
1950 | user_ns = self.user_ns | |
1945 | global_ns = self.user_global_ns |
|
1951 | global_ns = self.user_global_ns | |
1946 | for key, expr in expressions.iteritems(): |
|
1952 | for key, expr in expressions.iteritems(): | |
1947 | try: |
|
1953 | try: | |
1948 | value = repr(eval(expr, global_ns, user_ns)) |
|
1954 | value = repr(eval(expr, global_ns, user_ns)) | |
1949 | except: |
|
1955 | except: | |
1950 | value = self._simple_error() |
|
1956 | value = self._simple_error() | |
1951 | out[key] = value |
|
1957 | out[key] = value | |
1952 | return out |
|
1958 | return out | |
1953 |
|
1959 | |||
1954 | #------------------------------------------------------------------------- |
|
1960 | #------------------------------------------------------------------------- | |
1955 | # Things related to the running of code |
|
1961 | # Things related to the running of code | |
1956 | #------------------------------------------------------------------------- |
|
1962 | #------------------------------------------------------------------------- | |
1957 |
|
1963 | |||
1958 | def ex(self, cmd): |
|
1964 | def ex(self, cmd): | |
1959 | """Execute a normal python statement in user namespace.""" |
|
1965 | """Execute a normal python statement in user namespace.""" | |
1960 | with nested(self.builtin_trap,): |
|
1966 | with nested(self.builtin_trap,): | |
1961 | exec cmd in self.user_global_ns, self.user_ns |
|
1967 | exec cmd in self.user_global_ns, self.user_ns | |
1962 |
|
1968 | |||
1963 | def ev(self, expr): |
|
1969 | def ev(self, expr): | |
1964 | """Evaluate python expression expr in user namespace. |
|
1970 | """Evaluate python expression expr in user namespace. | |
1965 |
|
1971 | |||
1966 | Returns the result of evaluation |
|
1972 | Returns the result of evaluation | |
1967 | """ |
|
1973 | """ | |
1968 | with nested(self.builtin_trap,): |
|
1974 | with nested(self.builtin_trap,): | |
1969 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1975 | return eval(expr, self.user_global_ns, self.user_ns) | |
1970 |
|
1976 | |||
1971 | def safe_execfile(self, fname, *where, **kw): |
|
1977 | def safe_execfile(self, fname, *where, **kw): | |
1972 | """A safe version of the builtin execfile(). |
|
1978 | """A safe version of the builtin execfile(). | |
1973 |
|
1979 | |||
1974 | This version will never throw an exception, but instead print |
|
1980 | This version will never throw an exception, but instead print | |
1975 | helpful error messages to the screen. This only works on pure |
|
1981 | helpful error messages to the screen. This only works on pure | |
1976 | Python files with the .py extension. |
|
1982 | Python files with the .py extension. | |
1977 |
|
1983 | |||
1978 | Parameters |
|
1984 | Parameters | |
1979 | ---------- |
|
1985 | ---------- | |
1980 | fname : string |
|
1986 | fname : string | |
1981 | The name of the file to be executed. |
|
1987 | The name of the file to be executed. | |
1982 | where : tuple |
|
1988 | where : tuple | |
1983 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1989 | One or two namespaces, passed to execfile() as (globals,locals). | |
1984 | If only one is given, it is passed as both. |
|
1990 | If only one is given, it is passed as both. | |
1985 | exit_ignore : bool (False) |
|
1991 | exit_ignore : bool (False) | |
1986 | If True, then silence SystemExit for non-zero status (it is always |
|
1992 | If True, then silence SystemExit for non-zero status (it is always | |
1987 | silenced for zero status, as it is so common). |
|
1993 | silenced for zero status, as it is so common). | |
1988 | """ |
|
1994 | """ | |
1989 | kw.setdefault('exit_ignore', False) |
|
1995 | kw.setdefault('exit_ignore', False) | |
1990 |
|
1996 | |||
1991 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1997 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1992 |
|
1998 | |||
1993 | # Make sure we have a .py file |
|
1999 | # Make sure we have a .py file | |
1994 | if not fname.endswith('.py'): |
|
2000 | if not fname.endswith('.py'): | |
1995 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2001 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1996 |
|
2002 | |||
1997 | # Make sure we can open the file |
|
2003 | # Make sure we can open the file | |
1998 | try: |
|
2004 | try: | |
1999 | with open(fname) as thefile: |
|
2005 | with open(fname) as thefile: | |
2000 | pass |
|
2006 | pass | |
2001 | except: |
|
2007 | except: | |
2002 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2008 | warn('Could not open file <%s> for safe execution.' % fname) | |
2003 | return |
|
2009 | return | |
2004 |
|
2010 | |||
2005 | # Find things also in current directory. This is needed to mimic the |
|
2011 | # Find things also in current directory. This is needed to mimic the | |
2006 | # behavior of running a script from the system command line, where |
|
2012 | # behavior of running a script from the system command line, where | |
2007 | # Python inserts the script's directory into sys.path |
|
2013 | # Python inserts the script's directory into sys.path | |
2008 | dname = os.path.dirname(fname) |
|
2014 | dname = os.path.dirname(fname) | |
2009 |
|
2015 | |||
2010 | with prepended_to_syspath(dname): |
|
2016 | with prepended_to_syspath(dname): | |
2011 | try: |
|
2017 | try: | |
2012 | execfile(fname,*where) |
|
2018 | execfile(fname,*where) | |
2013 | except SystemExit, status: |
|
2019 | except SystemExit, status: | |
2014 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2020 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2015 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2021 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2016 | # these are considered normal by the OS: |
|
2022 | # these are considered normal by the OS: | |
2017 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2023 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2018 | # 0 |
|
2024 | # 0 | |
2019 | # > python -c'import sys;sys.exit()'; echo $? |
|
2025 | # > python -c'import sys;sys.exit()'; echo $? | |
2020 | # 0 |
|
2026 | # 0 | |
2021 | # For other exit status, we show the exception unless |
|
2027 | # For other exit status, we show the exception unless | |
2022 | # explicitly silenced, but only in short form. |
|
2028 | # explicitly silenced, but only in short form. | |
2023 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2029 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2024 | self.showtraceback(exception_only=True) |
|
2030 | self.showtraceback(exception_only=True) | |
2025 | except: |
|
2031 | except: | |
2026 | self.showtraceback() |
|
2032 | self.showtraceback() | |
2027 |
|
2033 | |||
2028 | def safe_execfile_ipy(self, fname): |
|
2034 | def safe_execfile_ipy(self, fname): | |
2029 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2035 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2030 |
|
2036 | |||
2031 | Parameters |
|
2037 | Parameters | |
2032 | ---------- |
|
2038 | ---------- | |
2033 | fname : str |
|
2039 | fname : str | |
2034 | The name of the file to execute. The filename must have a |
|
2040 | The name of the file to execute. The filename must have a | |
2035 | .ipy extension. |
|
2041 | .ipy extension. | |
2036 | """ |
|
2042 | """ | |
2037 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2043 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2038 |
|
2044 | |||
2039 | # Make sure we have a .py file |
|
2045 | # Make sure we have a .py file | |
2040 | if not fname.endswith('.ipy'): |
|
2046 | if not fname.endswith('.ipy'): | |
2041 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2047 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2042 |
|
2048 | |||
2043 | # Make sure we can open the file |
|
2049 | # Make sure we can open the file | |
2044 | try: |
|
2050 | try: | |
2045 | with open(fname) as thefile: |
|
2051 | with open(fname) as thefile: | |
2046 | pass |
|
2052 | pass | |
2047 | except: |
|
2053 | except: | |
2048 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2054 | warn('Could not open file <%s> for safe execution.' % fname) | |
2049 | return |
|
2055 | return | |
2050 |
|
2056 | |||
2051 | # Find things also in current directory. This is needed to mimic the |
|
2057 | # Find things also in current directory. This is needed to mimic the | |
2052 | # behavior of running a script from the system command line, where |
|
2058 | # behavior of running a script from the system command line, where | |
2053 | # Python inserts the script's directory into sys.path |
|
2059 | # Python inserts the script's directory into sys.path | |
2054 | dname = os.path.dirname(fname) |
|
2060 | dname = os.path.dirname(fname) | |
2055 |
|
2061 | |||
2056 | with prepended_to_syspath(dname): |
|
2062 | with prepended_to_syspath(dname): | |
2057 | try: |
|
2063 | try: | |
2058 | with open(fname) as thefile: |
|
2064 | with open(fname) as thefile: | |
2059 | # self.run_cell currently captures all exceptions |
|
2065 | # self.run_cell currently captures all exceptions | |
2060 | # raised in user code. It would be nice if there were |
|
2066 | # raised in user code. It would be nice if there were | |
2061 | # versions of runlines, execfile that did raise, so |
|
2067 | # versions of runlines, execfile that did raise, so | |
2062 | # we could catch the errors. |
|
2068 | # we could catch the errors. | |
2063 | self.run_cell(thefile.read()) |
|
2069 | self.run_cell(thefile.read()) | |
2064 | except: |
|
2070 | except: | |
2065 | self.showtraceback() |
|
2071 | self.showtraceback() | |
2066 | warn('Unknown failure executing file: <%s>' % fname) |
|
2072 | warn('Unknown failure executing file: <%s>' % fname) | |
2067 |
|
2073 | |||
2068 | def run_cell(self, cell): |
|
2074 | def run_cell(self, cell): | |
2069 | """Run the contents of an entire multiline 'cell' of code. |
|
2075 | """Run the contents of an entire multiline 'cell' of code. | |
2070 |
|
2076 | |||
2071 | The cell is split into separate blocks which can be executed |
|
2077 | The cell is split into separate blocks which can be executed | |
2072 | individually. Then, based on how many blocks there are, they are |
|
2078 | individually. Then, based on how many blocks there are, they are | |
2073 | executed as follows: |
|
2079 | executed as follows: | |
2074 |
|
2080 | |||
2075 | - A single block: 'single' mode. |
|
2081 | - A single block: 'single' mode. | |
2076 |
|
2082 | |||
2077 | If there's more than one block, it depends: |
|
2083 | If there's more than one block, it depends: | |
2078 |
|
2084 | |||
2079 | - if the last one is no more than two lines long, run all but the last |
|
2085 | - if the last one is no more than two lines long, run all but the last | |
2080 | in 'exec' mode and the very last one in 'single' mode. This makes it |
|
2086 | in 'exec' mode and the very last one in 'single' mode. This makes it | |
2081 | easy to type simple expressions at the end to see computed values. - |
|
2087 | easy to type simple expressions at the end to see computed values. - | |
2082 | otherwise (last one is also multiline), run all in 'exec' mode |
|
2088 | otherwise (last one is also multiline), run all in 'exec' mode | |
2083 |
|
2089 | |||
2084 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, |
|
2090 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, | |
2085 | results are displayed and output prompts are computed. In 'exec' mode, |
|
2091 | results are displayed and output prompts are computed. In 'exec' mode, | |
2086 | no results are displayed unless :func:`print` is called explicitly; |
|
2092 | no results are displayed unless :func:`print` is called explicitly; | |
2087 | this mode is more akin to running a script. |
|
2093 | this mode is more akin to running a script. | |
2088 |
|
2094 | |||
2089 | Parameters |
|
2095 | Parameters | |
2090 | ---------- |
|
2096 | ---------- | |
2091 | cell : str |
|
2097 | cell : str | |
2092 | A single or multiline string. |
|
2098 | A single or multiline string. | |
2093 | """ |
|
2099 | """ | |
2094 |
|
2100 | |||
2095 | # We need to break up the input into executable blocks that can be run |
|
2101 | # We need to break up the input into executable blocks that can be run | |
2096 | # in 'single' mode, to provide comfortable user behavior. |
|
2102 | # in 'single' mode, to provide comfortable user behavior. | |
2097 | blocks = self.input_splitter.split_blocks(cell) |
|
2103 | blocks = self.input_splitter.split_blocks(cell) | |
2098 |
|
2104 | |||
2099 | if not blocks: |
|
2105 | if not blocks: | |
2100 | return |
|
2106 | return | |
2101 |
|
2107 | |||
2102 | # Store the 'ipython' version of the cell as well, since that's what |
|
2108 | # Store the 'ipython' version of the cell as well, since that's what | |
2103 | # needs to go into the translated history and get executed (the |
|
2109 | # needs to go into the translated history and get executed (the | |
2104 | # original cell may contain non-python syntax). |
|
2110 | # original cell may contain non-python syntax). | |
2105 | ipy_cell = ''.join(blocks) |
|
2111 | ipy_cell = ''.join(blocks) | |
2106 |
|
2112 | |||
2107 | # Store raw and processed history |
|
2113 | # Store raw and processed history | |
2108 | self.history_manager.store_inputs(ipy_cell, cell) |
|
2114 | self.history_manager.store_inputs(ipy_cell, cell) | |
2109 |
|
2115 | |||
2110 | self.logger.log(ipy_cell, cell) |
|
2116 | self.logger.log(ipy_cell, cell) | |
2111 | # dbg code!!! |
|
2117 | # dbg code!!! | |
2112 | if 0: |
|
2118 | if 0: | |
2113 | def myapp(self, val): # dbg |
|
2119 | def myapp(self, val): # dbg | |
2114 | import traceback as tb |
|
2120 | import traceback as tb | |
2115 | stack = ''.join(tb.format_stack()) |
|
2121 | stack = ''.join(tb.format_stack()) | |
2116 | print 'Value:', val |
|
2122 | print 'Value:', val | |
2117 | print 'Stack:\n', stack |
|
2123 | print 'Stack:\n', stack | |
2118 | list.append(self, val) |
|
2124 | list.append(self, val) | |
2119 |
|
2125 | |||
2120 | import new |
|
2126 | import new | |
2121 | self.history_manager.input_hist_parsed.append = types.MethodType(myapp, |
|
2127 | self.history_manager.input_hist_parsed.append = types.MethodType(myapp, | |
2122 | self.history_manager.input_hist_parsed) |
|
2128 | self.history_manager.input_hist_parsed) | |
2123 | # End dbg |
|
2129 | # End dbg | |
2124 |
|
2130 | |||
2125 | # All user code execution must happen with our context managers active |
|
2131 | # All user code execution must happen with our context managers active | |
2126 | with nested(self.builtin_trap, self.display_trap): |
|
2132 | with nested(self.builtin_trap, self.display_trap): | |
2127 |
|
2133 | |||
2128 | # Single-block input should behave like an interactive prompt |
|
2134 | # Single-block input should behave like an interactive prompt | |
2129 | if len(blocks) == 1: |
|
2135 | if len(blocks) == 1: | |
2130 | # since we return here, we need to update the execution count |
|
2136 | # since we return here, we need to update the execution count | |
2131 | out = self.run_one_block(blocks[0]) |
|
2137 | out = self.run_one_block(blocks[0]) | |
2132 | self.execution_count += 1 |
|
2138 | self.execution_count += 1 | |
2133 | return out |
|
2139 | return out | |
2134 |
|
2140 | |||
2135 | # In multi-block input, if the last block is a simple (one-two |
|
2141 | # In multi-block input, if the last block is a simple (one-two | |
2136 | # lines) expression, run it in single mode so it produces output. |
|
2142 | # lines) expression, run it in single mode so it produces output. | |
2137 | # Otherwise just feed the whole thing to run_code. This seems like |
|
2143 | # Otherwise just feed the whole thing to run_code. This seems like | |
2138 | # a reasonable usability design. |
|
2144 | # a reasonable usability design. | |
2139 | last = blocks[-1] |
|
2145 | last = blocks[-1] | |
2140 | last_nlines = len(last.splitlines()) |
|
2146 | last_nlines = len(last.splitlines()) | |
2141 |
|
2147 | |||
2142 | # Note: below, whenever we call run_code, we must sync history |
|
2148 | # Note: below, whenever we call run_code, we must sync history | |
2143 | # ourselves, because run_code is NOT meant to manage history at all. |
|
2149 | # ourselves, because run_code is NOT meant to manage history at all. | |
2144 | if last_nlines < 2: |
|
2150 | if last_nlines < 2: | |
2145 | # Here we consider the cell split between 'body' and 'last', |
|
2151 | # Here we consider the cell split between 'body' and 'last', | |
2146 | # store all history and execute 'body', and if successful, then |
|
2152 | # store all history and execute 'body', and if successful, then | |
2147 | # proceed to execute 'last'. |
|
2153 | # proceed to execute 'last'. | |
2148 |
|
2154 | |||
2149 | # Get the main body to run as a cell |
|
2155 | # Get the main body to run as a cell | |
2150 | ipy_body = ''.join(blocks[:-1]) |
|
2156 | ipy_body = ''.join(blocks[:-1]) | |
2151 | retcode = self.run_source(ipy_body, symbol='exec', |
|
2157 | retcode = self.run_source(ipy_body, symbol='exec', | |
2152 | post_execute=False) |
|
2158 | post_execute=False) | |
2153 | if retcode==0: |
|
2159 | if retcode==0: | |
2154 | # And the last expression via runlines so it produces output |
|
2160 | # And the last expression via runlines so it produces output | |
2155 | self.run_one_block(last) |
|
2161 | self.run_one_block(last) | |
2156 | else: |
|
2162 | else: | |
2157 | # Run the whole cell as one entity, storing both raw and |
|
2163 | # Run the whole cell as one entity, storing both raw and | |
2158 | # processed input in history |
|
2164 | # processed input in history | |
2159 | self.run_source(ipy_cell, symbol='exec') |
|
2165 | self.run_source(ipy_cell, symbol='exec') | |
2160 |
|
2166 | |||
2161 | # Each cell is a *single* input, regardless of how many lines it has |
|
2167 | # Each cell is a *single* input, regardless of how many lines it has | |
2162 | self.execution_count += 1 |
|
2168 | self.execution_count += 1 | |
2163 |
|
2169 | |||
2164 | def run_one_block(self, block): |
|
2170 | def run_one_block(self, block): | |
2165 | """Run a single interactive block. |
|
2171 | """Run a single interactive block. | |
2166 |
|
2172 | |||
2167 | If the block is single-line, dynamic transformations are applied to it |
|
2173 | If the block is single-line, dynamic transformations are applied to it | |
2168 | (like automagics, autocall and alias recognition). |
|
2174 | (like automagics, autocall and alias recognition). | |
2169 | """ |
|
2175 | """ | |
2170 | if len(block.splitlines()) <= 1: |
|
2176 | if len(block.splitlines()) <= 1: | |
2171 | out = self.run_single_line(block) |
|
2177 | out = self.run_single_line(block) | |
2172 | else: |
|
2178 | else: | |
2173 | out = self.run_code(block) |
|
2179 | out = self.run_code(block) | |
2174 | return out |
|
2180 | return out | |
2175 |
|
2181 | |||
2176 | def run_single_line(self, line): |
|
2182 | def run_single_line(self, line): | |
2177 | """Run a single-line interactive statement. |
|
2183 | """Run a single-line interactive statement. | |
2178 |
|
2184 | |||
2179 | This assumes the input has been transformed to IPython syntax by |
|
2185 | This assumes the input has been transformed to IPython syntax by | |
2180 | applying all static transformations (those with an explicit prefix like |
|
2186 | applying all static transformations (those with an explicit prefix like | |
2181 | % or !), but it will further try to apply the dynamic ones. |
|
2187 | % or !), but it will further try to apply the dynamic ones. | |
2182 |
|
2188 | |||
2183 | It does not update history. |
|
2189 | It does not update history. | |
2184 | """ |
|
2190 | """ | |
2185 | tline = self.prefilter_manager.prefilter_line(line) |
|
2191 | tline = self.prefilter_manager.prefilter_line(line) | |
2186 | return self.run_source(tline) |
|
2192 | return self.run_source(tline) | |
2187 |
|
2193 | |||
2188 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2194 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2189 | # input logic has been 100% moved to frontends and is stable. |
|
2195 | # input logic has been 100% moved to frontends and is stable. | |
2190 | def runlines(self, lines, clean=False): |
|
2196 | def runlines(self, lines, clean=False): | |
2191 | """Run a string of one or more lines of source. |
|
2197 | """Run a string of one or more lines of source. | |
2192 |
|
2198 | |||
2193 | This method is capable of running a string containing multiple source |
|
2199 | This method is capable of running a string containing multiple source | |
2194 | lines, as if they had been entered at the IPython prompt. Since it |
|
2200 | lines, as if they had been entered at the IPython prompt. Since it | |
2195 | exposes IPython's processing machinery, the given strings can contain |
|
2201 | exposes IPython's processing machinery, the given strings can contain | |
2196 | magic calls (%magic), special shell access (!cmd), etc. |
|
2202 | magic calls (%magic), special shell access (!cmd), etc. | |
2197 | """ |
|
2203 | """ | |
2198 |
|
2204 | |||
2199 | if isinstance(lines, (list, tuple)): |
|
2205 | if isinstance(lines, (list, tuple)): | |
2200 | lines = '\n'.join(lines) |
|
2206 | lines = '\n'.join(lines) | |
2201 |
|
2207 | |||
2202 | if clean: |
|
2208 | if clean: | |
2203 | lines = self._cleanup_ipy_script(lines) |
|
2209 | lines = self._cleanup_ipy_script(lines) | |
2204 |
|
2210 | |||
2205 | # We must start with a clean buffer, in case this is run from an |
|
2211 | # We must start with a clean buffer, in case this is run from an | |
2206 | # interactive IPython session (via a magic, for example). |
|
2212 | # interactive IPython session (via a magic, for example). | |
2207 | self.reset_buffer() |
|
2213 | self.reset_buffer() | |
2208 | lines = lines.splitlines() |
|
2214 | lines = lines.splitlines() | |
2209 |
|
2215 | |||
2210 | # Since we will prefilter all lines, store the user's raw input too |
|
2216 | # Since we will prefilter all lines, store the user's raw input too | |
2211 | # before we apply any transformations |
|
2217 | # before we apply any transformations | |
2212 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2218 | self.buffer_raw[:] = [ l+'\n' for l in lines] | |
2213 |
|
2219 | |||
2214 | more = False |
|
2220 | more = False | |
2215 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2221 | prefilter_lines = self.prefilter_manager.prefilter_lines | |
2216 | with nested(self.builtin_trap, self.display_trap): |
|
2222 | with nested(self.builtin_trap, self.display_trap): | |
2217 | for line in lines: |
|
2223 | for line in lines: | |
2218 | # skip blank lines so we don't mess up the prompt counter, but |
|
2224 | # skip blank lines so we don't mess up the prompt counter, but | |
2219 | # do NOT skip even a blank line if we are in a code block (more |
|
2225 | # do NOT skip even a blank line if we are in a code block (more | |
2220 | # is true) |
|
2226 | # is true) | |
2221 |
|
2227 | |||
2222 | if line or more: |
|
2228 | if line or more: | |
2223 | more = self.push_line(prefilter_lines(line, more)) |
|
2229 | more = self.push_line(prefilter_lines(line, more)) | |
2224 | # IPython's run_source returns None if there was an error |
|
2230 | # IPython's run_source returns None if there was an error | |
2225 | # compiling the code. This allows us to stop processing |
|
2231 | # compiling the code. This allows us to stop processing | |
2226 | # right away, so the user gets the error message at the |
|
2232 | # right away, so the user gets the error message at the | |
2227 | # right place. |
|
2233 | # right place. | |
2228 | if more is None: |
|
2234 | if more is None: | |
2229 | break |
|
2235 | break | |
2230 | # final newline in case the input didn't have it, so that the code |
|
2236 | # final newline in case the input didn't have it, so that the code | |
2231 | # actually does get executed |
|
2237 | # actually does get executed | |
2232 | if more: |
|
2238 | if more: | |
2233 | self.push_line('\n') |
|
2239 | self.push_line('\n') | |
2234 |
|
2240 | |||
2235 | def run_source(self, source, filename=None, |
|
2241 | def run_source(self, source, filename=None, | |
2236 | symbol='single', post_execute=True): |
|
2242 | symbol='single', post_execute=True): | |
2237 | """Compile and run some source in the interpreter. |
|
2243 | """Compile and run some source in the interpreter. | |
2238 |
|
2244 | |||
2239 | Arguments are as for compile_command(). |
|
2245 | Arguments are as for compile_command(). | |
2240 |
|
2246 | |||
2241 | One several things can happen: |
|
2247 | One several things can happen: | |
2242 |
|
2248 | |||
2243 | 1) The input is incorrect; compile_command() raised an |
|
2249 | 1) The input is incorrect; compile_command() raised an | |
2244 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2250 | exception (SyntaxError or OverflowError). A syntax traceback | |
2245 | will be printed by calling the showsyntaxerror() method. |
|
2251 | will be printed by calling the showsyntaxerror() method. | |
2246 |
|
2252 | |||
2247 | 2) The input is incomplete, and more input is required; |
|
2253 | 2) The input is incomplete, and more input is required; | |
2248 | compile_command() returned None. Nothing happens. |
|
2254 | compile_command() returned None. Nothing happens. | |
2249 |
|
2255 | |||
2250 | 3) The input is complete; compile_command() returned a code |
|
2256 | 3) The input is complete; compile_command() returned a code | |
2251 | object. The code is executed by calling self.run_code() (which |
|
2257 | object. The code is executed by calling self.run_code() (which | |
2252 | also handles run-time exceptions, except for SystemExit). |
|
2258 | also handles run-time exceptions, except for SystemExit). | |
2253 |
|
2259 | |||
2254 | The return value is: |
|
2260 | The return value is: | |
2255 |
|
2261 | |||
2256 | - True in case 2 |
|
2262 | - True in case 2 | |
2257 |
|
2263 | |||
2258 | - False in the other cases, unless an exception is raised, where |
|
2264 | - False in the other cases, unless an exception is raised, where | |
2259 | None is returned instead. This can be used by external callers to |
|
2265 | None is returned instead. This can be used by external callers to | |
2260 | know whether to continue feeding input or not. |
|
2266 | know whether to continue feeding input or not. | |
2261 |
|
2267 | |||
2262 | The return value can be used to decide whether to use sys.ps1 or |
|
2268 | The return value can be used to decide whether to use sys.ps1 or | |
2263 | sys.ps2 to prompt the next line.""" |
|
2269 | sys.ps2 to prompt the next line.""" | |
2264 |
|
2270 | |||
2265 | # We need to ensure that the source is unicode from here on. |
|
2271 | # We need to ensure that the source is unicode from here on. | |
2266 | if type(source)==str: |
|
2272 | if type(source)==str: | |
2267 | usource = source.decode(self.stdin_encoding) |
|
2273 | usource = source.decode(self.stdin_encoding) | |
2268 | else: |
|
2274 | else: | |
2269 | usource = source |
|
2275 | usource = source | |
2270 |
|
2276 | |||
2271 | if 0: # dbg |
|
2277 | if 0: # dbg | |
2272 | print 'Source:', repr(source) # dbg |
|
2278 | print 'Source:', repr(source) # dbg | |
2273 | print 'USource:', repr(usource) # dbg |
|
2279 | print 'USource:', repr(usource) # dbg | |
2274 | print 'type:', type(source) # dbg |
|
2280 | print 'type:', type(source) # dbg | |
2275 | print 'encoding', self.stdin_encoding # dbg |
|
2281 | print 'encoding', self.stdin_encoding # dbg | |
2276 |
|
2282 | |||
2277 | try: |
|
2283 | try: | |
2278 | code = self.compile(usource, symbol, self.execution_count) |
|
2284 | code = self.compile(usource, symbol, self.execution_count) | |
2279 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2285 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2280 | # Case 1 |
|
2286 | # Case 1 | |
2281 | self.showsyntaxerror(filename) |
|
2287 | self.showsyntaxerror(filename) | |
2282 | return None |
|
2288 | return None | |
2283 |
|
2289 | |||
2284 | if code is None: |
|
2290 | if code is None: | |
2285 | # Case 2 |
|
2291 | # Case 2 | |
2286 | return True |
|
2292 | return True | |
2287 |
|
2293 | |||
2288 | # Case 3 |
|
2294 | # Case 3 | |
2289 | # We store the code object so that threaded shells and |
|
2295 | # We store the code object so that threaded shells and | |
2290 | # custom exception handlers can access all this info if needed. |
|
2296 | # custom exception handlers can access all this info if needed. | |
2291 | # The source corresponding to this can be obtained from the |
|
2297 | # The source corresponding to this can be obtained from the | |
2292 | # buffer attribute as '\n'.join(self.buffer). |
|
2298 | # buffer attribute as '\n'.join(self.buffer). | |
2293 | self.code_to_run = code |
|
2299 | self.code_to_run = code | |
2294 | # now actually execute the code object |
|
2300 | # now actually execute the code object | |
2295 | if self.run_code(code, post_execute) == 0: |
|
2301 | if self.run_code(code, post_execute) == 0: | |
2296 | return False |
|
2302 | return False | |
2297 | else: |
|
2303 | else: | |
2298 | return None |
|
2304 | return None | |
2299 |
|
2305 | |||
2300 | # For backwards compatibility |
|
2306 | # For backwards compatibility | |
2301 | runsource = run_source |
|
2307 | runsource = run_source | |
2302 |
|
2308 | |||
2303 | def run_code(self, code_obj, post_execute=True): |
|
2309 | def run_code(self, code_obj, post_execute=True): | |
2304 | """Execute a code object. |
|
2310 | """Execute a code object. | |
2305 |
|
2311 | |||
2306 | When an exception occurs, self.showtraceback() is called to display a |
|
2312 | When an exception occurs, self.showtraceback() is called to display a | |
2307 | traceback. |
|
2313 | traceback. | |
2308 |
|
2314 | |||
2309 | Return value: a flag indicating whether the code to be run completed |
|
2315 | Return value: a flag indicating whether the code to be run completed | |
2310 | successfully: |
|
2316 | successfully: | |
2311 |
|
2317 | |||
2312 | - 0: successful execution. |
|
2318 | - 0: successful execution. | |
2313 | - 1: an error occurred. |
|
2319 | - 1: an error occurred. | |
2314 | """ |
|
2320 | """ | |
2315 |
|
2321 | |||
2316 | # Set our own excepthook in case the user code tries to call it |
|
2322 | # Set our own excepthook in case the user code tries to call it | |
2317 | # directly, so that the IPython crash handler doesn't get triggered |
|
2323 | # directly, so that the IPython crash handler doesn't get triggered | |
2318 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2324 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2319 |
|
2325 | |||
2320 | # we save the original sys.excepthook in the instance, in case config |
|
2326 | # we save the original sys.excepthook in the instance, in case config | |
2321 | # code (such as magics) needs access to it. |
|
2327 | # code (such as magics) needs access to it. | |
2322 | self.sys_excepthook = old_excepthook |
|
2328 | self.sys_excepthook = old_excepthook | |
2323 | outflag = 1 # happens in more places, so it's easier as default |
|
2329 | outflag = 1 # happens in more places, so it's easier as default | |
2324 | try: |
|
2330 | try: | |
2325 | try: |
|
2331 | try: | |
2326 | self.hooks.pre_run_code_hook() |
|
2332 | self.hooks.pre_run_code_hook() | |
2327 | #rprint('Running code') # dbg |
|
2333 | #rprint('Running code') # dbg | |
2328 | exec code_obj in self.user_global_ns, self.user_ns |
|
2334 | exec code_obj in self.user_global_ns, self.user_ns | |
2329 | finally: |
|
2335 | finally: | |
2330 | # Reset our crash handler in place |
|
2336 | # Reset our crash handler in place | |
2331 | sys.excepthook = old_excepthook |
|
2337 | sys.excepthook = old_excepthook | |
2332 | except SystemExit: |
|
2338 | except SystemExit: | |
2333 | self.reset_buffer() |
|
2339 | self.reset_buffer() | |
2334 | self.showtraceback(exception_only=True) |
|
2340 | self.showtraceback(exception_only=True) | |
2335 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2341 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2336 | except self.custom_exceptions: |
|
2342 | except self.custom_exceptions: | |
2337 | etype,value,tb = sys.exc_info() |
|
2343 | etype,value,tb = sys.exc_info() | |
2338 | self.CustomTB(etype,value,tb) |
|
2344 | self.CustomTB(etype,value,tb) | |
2339 | except: |
|
2345 | except: | |
2340 | self.showtraceback() |
|
2346 | self.showtraceback() | |
2341 | else: |
|
2347 | else: | |
2342 | outflag = 0 |
|
2348 | outflag = 0 | |
2343 | if softspace(sys.stdout, 0): |
|
2349 | if softspace(sys.stdout, 0): | |
2344 |
|
2350 | |||
2345 |
|
2351 | |||
2346 | # Execute any registered post-execution functions. Here, any errors |
|
2352 | # Execute any registered post-execution functions. Here, any errors | |
2347 | # are reported only minimally and just on the terminal, because the |
|
2353 | # are reported only minimally and just on the terminal, because the | |
2348 | # main exception channel may be occupied with a user traceback. |
|
2354 | # main exception channel may be occupied with a user traceback. | |
2349 | # FIXME: we need to think this mechanism a little more carefully. |
|
2355 | # FIXME: we need to think this mechanism a little more carefully. | |
2350 | if post_execute: |
|
2356 | if post_execute: | |
2351 | for func in self._post_execute: |
|
2357 | for func in self._post_execute: | |
2352 | try: |
|
2358 | try: | |
2353 | func() |
|
2359 | func() | |
2354 | except: |
|
2360 | except: | |
2355 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2361 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ | |
2356 | func |
|
2362 | func | |
2357 | print >> io.Term.cout, head |
|
2363 | print >> io.Term.cout, head | |
2358 | print >> io.Term.cout, self._simple_error() |
|
2364 | print >> io.Term.cout, self._simple_error() | |
2359 | print >> io.Term.cout, 'Removing from post_execute' |
|
2365 | print >> io.Term.cout, 'Removing from post_execute' | |
2360 | self._post_execute.remove(func) |
|
2366 | self._post_execute.remove(func) | |
2361 |
|
2367 | |||
2362 | # Flush out code object which has been run (and source) |
|
2368 | # Flush out code object which has been run (and source) | |
2363 | self.code_to_run = None |
|
2369 | self.code_to_run = None | |
2364 | return outflag |
|
2370 | return outflag | |
2365 |
|
2371 | |||
2366 | # For backwards compatibility |
|
2372 | # For backwards compatibility | |
2367 | runcode = run_code |
|
2373 | runcode = run_code | |
2368 |
|
2374 | |||
2369 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2375 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2370 | # input logic has been 100% moved to frontends and is stable. |
|
2376 | # input logic has been 100% moved to frontends and is stable. | |
2371 | def push_line(self, line): |
|
2377 | def push_line(self, line): | |
2372 | """Push a line to the interpreter. |
|
2378 | """Push a line to the interpreter. | |
2373 |
|
2379 | |||
2374 | The line should not have a trailing newline; it may have |
|
2380 | The line should not have a trailing newline; it may have | |
2375 | internal newlines. The line is appended to a buffer and the |
|
2381 | internal newlines. The line is appended to a buffer and the | |
2376 | interpreter's run_source() method is called with the |
|
2382 | interpreter's run_source() method is called with the | |
2377 | concatenated contents of the buffer as source. If this |
|
2383 | concatenated contents of the buffer as source. If this | |
2378 | indicates that the command was executed or invalid, the buffer |
|
2384 | indicates that the command was executed or invalid, the buffer | |
2379 | is reset; otherwise, the command is incomplete, and the buffer |
|
2385 | is reset; otherwise, the command is incomplete, and the buffer | |
2380 | is left as it was after the line was appended. The return |
|
2386 | is left as it was after the line was appended. The return | |
2381 | value is 1 if more input is required, 0 if the line was dealt |
|
2387 | value is 1 if more input is required, 0 if the line was dealt | |
2382 | with in some way (this is the same as run_source()). |
|
2388 | with in some way (this is the same as run_source()). | |
2383 | """ |
|
2389 | """ | |
2384 |
|
2390 | |||
2385 | # autoindent management should be done here, and not in the |
|
2391 | # autoindent management should be done here, and not in the | |
2386 | # interactive loop, since that one is only seen by keyboard input. We |
|
2392 | # interactive loop, since that one is only seen by keyboard input. We | |
2387 | # need this done correctly even for code run via runlines (which uses |
|
2393 | # need this done correctly even for code run via runlines (which uses | |
2388 | # push). |
|
2394 | # push). | |
2389 |
|
2395 | |||
2390 | #print 'push line: <%s>' % line # dbg |
|
2396 | #print 'push line: <%s>' % line # dbg | |
2391 | self.buffer.append(line) |
|
2397 | self.buffer.append(line) | |
2392 | full_source = '\n'.join(self.buffer) |
|
2398 | full_source = '\n'.join(self.buffer) | |
2393 | more = self.run_source(full_source, self.filename) |
|
2399 | more = self.run_source(full_source, self.filename) | |
2394 | if not more: |
|
2400 | if not more: | |
2395 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), |
|
2401 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), | |
2396 | full_source) |
|
2402 | full_source) | |
2397 | self.reset_buffer() |
|
2403 | self.reset_buffer() | |
2398 | self.execution_count += 1 |
|
2404 | self.execution_count += 1 | |
2399 | return more |
|
2405 | return more | |
2400 |
|
2406 | |||
2401 | def reset_buffer(self): |
|
2407 | def reset_buffer(self): | |
2402 | """Reset the input buffer.""" |
|
2408 | """Reset the input buffer.""" | |
2403 | self.buffer[:] = [] |
|
2409 | self.buffer[:] = [] | |
2404 | self.buffer_raw[:] = [] |
|
2410 | self.buffer_raw[:] = [] | |
2405 | self.input_splitter.reset() |
|
2411 | self.input_splitter.reset() | |
2406 |
|
2412 | |||
2407 | # For backwards compatibility |
|
2413 | # For backwards compatibility | |
2408 | resetbuffer = reset_buffer |
|
2414 | resetbuffer = reset_buffer | |
2409 |
|
2415 | |||
2410 | def _is_secondary_block_start(self, s): |
|
2416 | def _is_secondary_block_start(self, s): | |
2411 | if not s.endswith(':'): |
|
2417 | if not s.endswith(':'): | |
2412 | return False |
|
2418 | return False | |
2413 | if (s.startswith('elif') or |
|
2419 | if (s.startswith('elif') or | |
2414 | s.startswith('else') or |
|
2420 | s.startswith('else') or | |
2415 | s.startswith('except') or |
|
2421 | s.startswith('except') or | |
2416 | s.startswith('finally')): |
|
2422 | s.startswith('finally')): | |
2417 | return True |
|
2423 | return True | |
2418 |
|
2424 | |||
2419 | def _cleanup_ipy_script(self, script): |
|
2425 | def _cleanup_ipy_script(self, script): | |
2420 | """Make a script safe for self.runlines() |
|
2426 | """Make a script safe for self.runlines() | |
2421 |
|
2427 | |||
2422 | Currently, IPython is lines based, with blocks being detected by |
|
2428 | Currently, IPython is lines based, with blocks being detected by | |
2423 | empty lines. This is a problem for block based scripts that may |
|
2429 | empty lines. This is a problem for block based scripts that may | |
2424 | not have empty lines after blocks. This script adds those empty |
|
2430 | not have empty lines after blocks. This script adds those empty | |
2425 | lines to make scripts safe for running in the current line based |
|
2431 | lines to make scripts safe for running in the current line based | |
2426 | IPython. |
|
2432 | IPython. | |
2427 | """ |
|
2433 | """ | |
2428 | res = [] |
|
2434 | res = [] | |
2429 | lines = script.splitlines() |
|
2435 | lines = script.splitlines() | |
2430 | level = 0 |
|
2436 | level = 0 | |
2431 |
|
2437 | |||
2432 | for l in lines: |
|
2438 | for l in lines: | |
2433 | lstripped = l.lstrip() |
|
2439 | lstripped = l.lstrip() | |
2434 | stripped = l.strip() |
|
2440 | stripped = l.strip() | |
2435 | if not stripped: |
|
2441 | if not stripped: | |
2436 | continue |
|
2442 | continue | |
2437 | newlevel = len(l) - len(lstripped) |
|
2443 | newlevel = len(l) - len(lstripped) | |
2438 | if level > 0 and newlevel == 0 and \ |
|
2444 | if level > 0 and newlevel == 0 and \ | |
2439 | not self._is_secondary_block_start(stripped): |
|
2445 | not self._is_secondary_block_start(stripped): | |
2440 | # add empty line |
|
2446 | # add empty line | |
2441 | res.append('') |
|
2447 | res.append('') | |
2442 | res.append(l) |
|
2448 | res.append(l) | |
2443 | level = newlevel |
|
2449 | level = newlevel | |
2444 |
|
2450 | |||
2445 | return '\n'.join(res) + '\n' |
|
2451 | return '\n'.join(res) + '\n' | |
2446 |
|
2452 | |||
2447 | #------------------------------------------------------------------------- |
|
2453 | #------------------------------------------------------------------------- | |
2448 | # Things related to GUI support and pylab |
|
2454 | # Things related to GUI support and pylab | |
2449 | #------------------------------------------------------------------------- |
|
2455 | #------------------------------------------------------------------------- | |
2450 |
|
2456 | |||
2451 | def enable_pylab(self, gui=None): |
|
2457 | def enable_pylab(self, gui=None): | |
2452 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2458 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2453 |
|
2459 | |||
2454 | #------------------------------------------------------------------------- |
|
2460 | #------------------------------------------------------------------------- | |
2455 | # Utilities |
|
2461 | # Utilities | |
2456 | #------------------------------------------------------------------------- |
|
2462 | #------------------------------------------------------------------------- | |
2457 |
|
2463 | |||
2458 | def var_expand(self,cmd,depth=0): |
|
2464 | def var_expand(self,cmd,depth=0): | |
2459 | """Expand python variables in a string. |
|
2465 | """Expand python variables in a string. | |
2460 |
|
2466 | |||
2461 | The depth argument indicates how many frames above the caller should |
|
2467 | The depth argument indicates how many frames above the caller should | |
2462 | be walked to look for the local namespace where to expand variables. |
|
2468 | be walked to look for the local namespace where to expand variables. | |
2463 |
|
2469 | |||
2464 | The global namespace for expansion is always the user's interactive |
|
2470 | The global namespace for expansion is always the user's interactive | |
2465 | namespace. |
|
2471 | namespace. | |
2466 | """ |
|
2472 | """ | |
2467 |
|
2473 | |||
2468 | return str(ItplNS(cmd, |
|
2474 | return str(ItplNS(cmd, | |
2469 | self.user_ns, # globals |
|
2475 | self.user_ns, # globals | |
2470 | # Skip our own frame in searching for locals: |
|
2476 | # Skip our own frame in searching for locals: | |
2471 | sys._getframe(depth+1).f_locals # locals |
|
2477 | sys._getframe(depth+1).f_locals # locals | |
2472 | )) |
|
2478 | )) | |
2473 |
|
2479 | |||
2474 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2480 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2475 | """Make a new tempfile and return its filename. |
|
2481 | """Make a new tempfile and return its filename. | |
2476 |
|
2482 | |||
2477 | This makes a call to tempfile.mktemp, but it registers the created |
|
2483 | This makes a call to tempfile.mktemp, but it registers the created | |
2478 | filename internally so ipython cleans it up at exit time. |
|
2484 | filename internally so ipython cleans it up at exit time. | |
2479 |
|
2485 | |||
2480 | Optional inputs: |
|
2486 | Optional inputs: | |
2481 |
|
2487 | |||
2482 | - data(None): if data is given, it gets written out to the temp file |
|
2488 | - data(None): if data is given, it gets written out to the temp file | |
2483 | immediately, and the file is closed again.""" |
|
2489 | immediately, and the file is closed again.""" | |
2484 |
|
2490 | |||
2485 | filename = tempfile.mktemp('.py', prefix) |
|
2491 | filename = tempfile.mktemp('.py', prefix) | |
2486 | self.tempfiles.append(filename) |
|
2492 | self.tempfiles.append(filename) | |
2487 |
|
2493 | |||
2488 | if data: |
|
2494 | if data: | |
2489 | tmp_file = open(filename,'w') |
|
2495 | tmp_file = open(filename,'w') | |
2490 | tmp_file.write(data) |
|
2496 | tmp_file.write(data) | |
2491 | tmp_file.close() |
|
2497 | tmp_file.close() | |
2492 | return filename |
|
2498 | return filename | |
2493 |
|
2499 | |||
2494 | # TODO: This should be removed when Term is refactored. |
|
2500 | # TODO: This should be removed when Term is refactored. | |
2495 | def write(self,data): |
|
2501 | def write(self,data): | |
2496 | """Write a string to the default output""" |
|
2502 | """Write a string to the default output""" | |
2497 | io.Term.cout.write(data) |
|
2503 | io.Term.cout.write(data) | |
2498 |
|
2504 | |||
2499 | # TODO: This should be removed when Term is refactored. |
|
2505 | # TODO: This should be removed when Term is refactored. | |
2500 | def write_err(self,data): |
|
2506 | def write_err(self,data): | |
2501 | """Write a string to the default error output""" |
|
2507 | """Write a string to the default error output""" | |
2502 | io.Term.cerr.write(data) |
|
2508 | io.Term.cerr.write(data) | |
2503 |
|
2509 | |||
2504 | def ask_yes_no(self,prompt,default=True): |
|
2510 | def ask_yes_no(self,prompt,default=True): | |
2505 | if self.quiet: |
|
2511 | if self.quiet: | |
2506 | return True |
|
2512 | return True | |
2507 | return ask_yes_no(prompt,default) |
|
2513 | return ask_yes_no(prompt,default) | |
2508 |
|
2514 | |||
2509 | def show_usage(self): |
|
2515 | def show_usage(self): | |
2510 | """Show a usage message""" |
|
2516 | """Show a usage message""" | |
2511 | page.page(IPython.core.usage.interactive_usage) |
|
2517 | page.page(IPython.core.usage.interactive_usage) | |
2512 |
|
2518 | |||
2513 | #------------------------------------------------------------------------- |
|
2519 | #------------------------------------------------------------------------- | |
2514 | # Things related to IPython exiting |
|
2520 | # Things related to IPython exiting | |
2515 | #------------------------------------------------------------------------- |
|
2521 | #------------------------------------------------------------------------- | |
2516 | def atexit_operations(self): |
|
2522 | def atexit_operations(self): | |
2517 | """This will be executed at the time of exit. |
|
2523 | """This will be executed at the time of exit. | |
2518 |
|
2524 | |||
2519 | Cleanup operations and saving of persistent data that is done |
|
2525 | Cleanup operations and saving of persistent data that is done | |
2520 | unconditionally by IPython should be performed here. |
|
2526 | unconditionally by IPython should be performed here. | |
2521 |
|
2527 | |||
2522 | For things that may depend on startup flags or platform specifics (such |
|
2528 | For things that may depend on startup flags or platform specifics (such | |
2523 | as having readline or not), register a separate atexit function in the |
|
2529 | as having readline or not), register a separate atexit function in the | |
2524 | code that has the appropriate information, rather than trying to |
|
2530 | code that has the appropriate information, rather than trying to | |
2525 | clutter |
|
2531 | clutter | |
2526 | """ |
|
2532 | """ | |
2527 | # Cleanup all tempfiles left around |
|
2533 | # Cleanup all tempfiles left around | |
2528 | for tfile in self.tempfiles: |
|
2534 | for tfile in self.tempfiles: | |
2529 | try: |
|
2535 | try: | |
2530 | os.unlink(tfile) |
|
2536 | os.unlink(tfile) | |
2531 | except OSError: |
|
2537 | except OSError: | |
2532 | pass |
|
2538 | pass | |
2533 |
|
2539 | |||
2534 | self.save_history() |
|
2540 | self.save_history() | |
2535 |
|
2541 | |||
2536 | # Clear all user namespaces to release all references cleanly. |
|
2542 | # Clear all user namespaces to release all references cleanly. | |
2537 | self.reset() |
|
2543 | self.reset() | |
2538 |
|
2544 | |||
2539 | # Run user hooks |
|
2545 | # Run user hooks | |
2540 | self.hooks.shutdown_hook() |
|
2546 | self.hooks.shutdown_hook() | |
2541 |
|
2547 | |||
2542 | def cleanup(self): |
|
2548 | def cleanup(self): | |
2543 | self.restore_sys_module_state() |
|
2549 | self.restore_sys_module_state() | |
2544 |
|
2550 | |||
2545 |
|
2551 | |||
2546 | class InteractiveShellABC(object): |
|
2552 | class InteractiveShellABC(object): | |
2547 | """An abstract base class for InteractiveShell.""" |
|
2553 | """An abstract base class for InteractiveShell.""" | |
2548 | __metaclass__ = abc.ABCMeta |
|
2554 | __metaclass__ = abc.ABCMeta | |
2549 |
|
2555 | |||
2550 | InteractiveShellABC.register(InteractiveShell) |
|
2556 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,598 +1,598 b'' | |||||
1 | from __future__ import print_function |
|
1 | from __future__ import print_function | |
2 |
|
2 | |||
3 | # Standard library imports |
|
3 | # Standard library imports | |
4 | from collections import namedtuple |
|
4 | from collections import namedtuple | |
5 | import sys |
|
5 | import sys | |
6 | import time |
|
6 | import time | |
7 |
|
7 | |||
8 | # System library imports |
|
8 | # System library imports | |
9 | from pygments.lexers import PythonLexer |
|
9 | from pygments.lexers import PythonLexer | |
10 | from PyQt4 import QtCore, QtGui |
|
10 | from PyQt4 import QtCore, QtGui | |
11 |
|
11 | |||
12 | # Local imports |
|
12 | # Local imports | |
13 | from IPython.core.inputsplitter import InputSplitter, transform_classic_prompt |
|
13 | from IPython.core.inputsplitter import InputSplitter, transform_classic_prompt | |
14 | from IPython.core.oinspect import call_tip |
|
14 | from IPython.core.oinspect import call_tip | |
15 | from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin |
|
15 | from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin | |
16 | from IPython.utils.traitlets import Bool |
|
16 | from IPython.utils.traitlets import Bool | |
17 | from bracket_matcher import BracketMatcher |
|
17 | from bracket_matcher import BracketMatcher | |
18 | from call_tip_widget import CallTipWidget |
|
18 | from call_tip_widget import CallTipWidget | |
19 | from completion_lexer import CompletionLexer |
|
19 | from completion_lexer import CompletionLexer | |
20 | from history_console_widget import HistoryConsoleWidget |
|
20 | from history_console_widget import HistoryConsoleWidget | |
21 | from pygments_highlighter import PygmentsHighlighter |
|
21 | from pygments_highlighter import PygmentsHighlighter | |
22 |
|
22 | |||
23 |
|
23 | |||
24 | class FrontendHighlighter(PygmentsHighlighter): |
|
24 | class FrontendHighlighter(PygmentsHighlighter): | |
25 | """ A PygmentsHighlighter that can be turned on and off and that ignores |
|
25 | """ A PygmentsHighlighter that can be turned on and off and that ignores | |
26 | prompts. |
|
26 | prompts. | |
27 | """ |
|
27 | """ | |
28 |
|
28 | |||
29 | def __init__(self, frontend): |
|
29 | def __init__(self, frontend): | |
30 | super(FrontendHighlighter, self).__init__(frontend._control.document()) |
|
30 | super(FrontendHighlighter, self).__init__(frontend._control.document()) | |
31 | self._current_offset = 0 |
|
31 | self._current_offset = 0 | |
32 | self._frontend = frontend |
|
32 | self._frontend = frontend | |
33 | self.highlighting_on = False |
|
33 | self.highlighting_on = False | |
34 |
|
34 | |||
35 | def highlightBlock(self, qstring): |
|
35 | def highlightBlock(self, qstring): | |
36 | """ Highlight a block of text. Reimplemented to highlight selectively. |
|
36 | """ Highlight a block of text. Reimplemented to highlight selectively. | |
37 | """ |
|
37 | """ | |
38 | if not self.highlighting_on: |
|
38 | if not self.highlighting_on: | |
39 | return |
|
39 | return | |
40 |
|
40 | |||
41 | # The input to this function is unicode string that may contain |
|
41 | # The input to this function is unicode string that may contain | |
42 | # paragraph break characters, non-breaking spaces, etc. Here we acquire |
|
42 | # paragraph break characters, non-breaking spaces, etc. Here we acquire | |
43 | # the string as plain text so we can compare it. |
|
43 | # the string as plain text so we can compare it. | |
44 | current_block = self.currentBlock() |
|
44 | current_block = self.currentBlock() | |
45 | string = self._frontend._get_block_plain_text(current_block) |
|
45 | string = self._frontend._get_block_plain_text(current_block) | |
46 |
|
46 | |||
47 | # Decide whether to check for the regular or continuation prompt. |
|
47 | # Decide whether to check for the regular or continuation prompt. | |
48 | if current_block.contains(self._frontend._prompt_pos): |
|
48 | if current_block.contains(self._frontend._prompt_pos): | |
49 | prompt = self._frontend._prompt |
|
49 | prompt = self._frontend._prompt | |
50 | else: |
|
50 | else: | |
51 | prompt = self._frontend._continuation_prompt |
|
51 | prompt = self._frontend._continuation_prompt | |
52 |
|
52 | |||
53 | # Don't highlight the part of the string that contains the prompt. |
|
53 | # Don't highlight the part of the string that contains the prompt. | |
54 | if string.startswith(prompt): |
|
54 | if string.startswith(prompt): | |
55 | self._current_offset = len(prompt) |
|
55 | self._current_offset = len(prompt) | |
56 | qstring.remove(0, len(prompt)) |
|
56 | qstring.remove(0, len(prompt)) | |
57 | else: |
|
57 | else: | |
58 | self._current_offset = 0 |
|
58 | self._current_offset = 0 | |
59 |
|
59 | |||
60 | PygmentsHighlighter.highlightBlock(self, qstring) |
|
60 | PygmentsHighlighter.highlightBlock(self, qstring) | |
61 |
|
61 | |||
62 | def rehighlightBlock(self, block): |
|
62 | def rehighlightBlock(self, block): | |
63 | """ Reimplemented to temporarily enable highlighting if disabled. |
|
63 | """ Reimplemented to temporarily enable highlighting if disabled. | |
64 | """ |
|
64 | """ | |
65 | old = self.highlighting_on |
|
65 | old = self.highlighting_on | |
66 | self.highlighting_on = True |
|
66 | self.highlighting_on = True | |
67 | super(FrontendHighlighter, self).rehighlightBlock(block) |
|
67 | super(FrontendHighlighter, self).rehighlightBlock(block) | |
68 | self.highlighting_on = old |
|
68 | self.highlighting_on = old | |
69 |
|
69 | |||
70 | def setFormat(self, start, count, format): |
|
70 | def setFormat(self, start, count, format): | |
71 | """ Reimplemented to highlight selectively. |
|
71 | """ Reimplemented to highlight selectively. | |
72 | """ |
|
72 | """ | |
73 | start += self._current_offset |
|
73 | start += self._current_offset | |
74 | PygmentsHighlighter.setFormat(self, start, count, format) |
|
74 | PygmentsHighlighter.setFormat(self, start, count, format) | |
75 |
|
75 | |||
76 |
|
76 | |||
77 | class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin): |
|
77 | class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin): | |
78 | """ A Qt frontend for a generic Python kernel. |
|
78 | """ A Qt frontend for a generic Python kernel. | |
79 | """ |
|
79 | """ | |
80 |
|
80 | |||
81 | # An option and corresponding signal for overriding the default kernel |
|
81 | # An option and corresponding signal for overriding the default kernel | |
82 | # interrupt behavior. |
|
82 | # interrupt behavior. | |
83 | custom_interrupt = Bool(False) |
|
83 | custom_interrupt = Bool(False) | |
84 | custom_interrupt_requested = QtCore.pyqtSignal() |
|
84 | custom_interrupt_requested = QtCore.pyqtSignal() | |
85 |
|
85 | |||
86 | # An option and corresponding signals for overriding the default kernel |
|
86 | # An option and corresponding signals for overriding the default kernel | |
87 | # restart behavior. |
|
87 | # restart behavior. | |
88 | custom_restart = Bool(False) |
|
88 | custom_restart = Bool(False) | |
89 | custom_restart_kernel_died = QtCore.pyqtSignal(float) |
|
89 | custom_restart_kernel_died = QtCore.pyqtSignal(float) | |
90 | custom_restart_requested = QtCore.pyqtSignal() |
|
90 | custom_restart_requested = QtCore.pyqtSignal() | |
91 |
|
91 | |||
92 | # Emitted when an 'execute_reply' has been received from the kernel and |
|
92 | # Emitted when an 'execute_reply' has been received from the kernel and | |
93 | # processed by the FrontendWidget. |
|
93 | # processed by the FrontendWidget. | |
94 | executed = QtCore.pyqtSignal(object) |
|
94 | executed = QtCore.pyqtSignal(object) | |
95 |
|
95 | |||
96 | # Emitted when an exit request has been received from the kernel. |
|
96 | # Emitted when an exit request has been received from the kernel. | |
97 | exit_requested = QtCore.pyqtSignal() |
|
97 | exit_requested = QtCore.pyqtSignal() | |
98 |
|
98 | |||
99 | # Protected class variables. |
|
99 | # Protected class variables. | |
100 | _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos']) |
|
100 | _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos']) | |
101 | _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos']) |
|
101 | _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos']) | |
102 | _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind']) |
|
102 | _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind']) | |
103 | _input_splitter_class = InputSplitter |
|
103 | _input_splitter_class = InputSplitter | |
104 | _local_kernel = False |
|
104 | _local_kernel = False | |
105 |
|
105 | |||
106 | #--------------------------------------------------------------------------- |
|
106 | #--------------------------------------------------------------------------- | |
107 | # 'object' interface |
|
107 | # 'object' interface | |
108 | #--------------------------------------------------------------------------- |
|
108 | #--------------------------------------------------------------------------- | |
109 |
|
109 | |||
110 | def __init__(self, *args, **kw): |
|
110 | def __init__(self, *args, **kw): | |
111 | super(FrontendWidget, self).__init__(*args, **kw) |
|
111 | super(FrontendWidget, self).__init__(*args, **kw) | |
112 |
|
112 | |||
113 | # FrontendWidget protected variables. |
|
113 | # FrontendWidget protected variables. | |
114 | self._bracket_matcher = BracketMatcher(self._control) |
|
114 | self._bracket_matcher = BracketMatcher(self._control) | |
115 | self._call_tip_widget = CallTipWidget(self._control) |
|
115 | self._call_tip_widget = CallTipWidget(self._control) | |
116 | self._completion_lexer = CompletionLexer(PythonLexer()) |
|
116 | self._completion_lexer = CompletionLexer(PythonLexer()) | |
117 | self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None) |
|
117 | self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None) | |
118 | self._hidden = False |
|
118 | self._hidden = False | |
119 | self._highlighter = FrontendHighlighter(self) |
|
119 | self._highlighter = FrontendHighlighter(self) | |
120 | self._input_splitter = self._input_splitter_class(input_mode='cell') |
|
120 | self._input_splitter = self._input_splitter_class(input_mode='cell') | |
121 | self._kernel_manager = None |
|
121 | self._kernel_manager = None | |
122 | self._request_info = {} |
|
122 | self._request_info = {} | |
123 |
|
123 | |||
124 | # Configure the ConsoleWidget. |
|
124 | # Configure the ConsoleWidget. | |
125 | self.tab_width = 4 |
|
125 | self.tab_width = 4 | |
126 | self._set_continuation_prompt('... ') |
|
126 | self._set_continuation_prompt('... ') | |
127 |
|
127 | |||
128 | # Configure the CallTipWidget. |
|
128 | # Configure the CallTipWidget. | |
129 | self._call_tip_widget.setFont(self.font) |
|
129 | self._call_tip_widget.setFont(self.font) | |
130 | self.font_changed.connect(self._call_tip_widget.setFont) |
|
130 | self.font_changed.connect(self._call_tip_widget.setFont) | |
131 |
|
131 | |||
132 | # Configure actions. |
|
132 | # Configure actions. | |
133 | action = self._copy_raw_action |
|
133 | action = self._copy_raw_action | |
134 | key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C |
|
134 | key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C | |
135 | action.setEnabled(False) |
|
135 | action.setEnabled(False) | |
136 | action.setShortcut(QtGui.QKeySequence(key)) |
|
136 | action.setShortcut(QtGui.QKeySequence(key)) | |
137 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) |
|
137 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) | |
138 | action.triggered.connect(self.copy_raw) |
|
138 | action.triggered.connect(self.copy_raw) | |
139 | self.copy_available.connect(action.setEnabled) |
|
139 | self.copy_available.connect(action.setEnabled) | |
140 | self.addAction(action) |
|
140 | self.addAction(action) | |
141 |
|
141 | |||
142 | # Connect signal handlers. |
|
142 | # Connect signal handlers. | |
143 | document = self._control.document() |
|
143 | document = self._control.document() | |
144 | document.contentsChange.connect(self._document_contents_change) |
|
144 | document.contentsChange.connect(self._document_contents_change) | |
145 |
|
145 | |||
146 | # set flag for whether we are connected via localhost |
|
146 | # set flag for whether we are connected via localhost | |
147 | self._local_kernel = kw.get('local_kernel', FrontendWidget._local_kernel) |
|
147 | self._local_kernel = kw.get('local_kernel', FrontendWidget._local_kernel) | |
148 |
|
148 | |||
149 | #--------------------------------------------------------------------------- |
|
149 | #--------------------------------------------------------------------------- | |
150 | # 'ConsoleWidget' public interface |
|
150 | # 'ConsoleWidget' public interface | |
151 | #--------------------------------------------------------------------------- |
|
151 | #--------------------------------------------------------------------------- | |
152 |
|
152 | |||
153 | def copy(self): |
|
153 | def copy(self): | |
154 | """ Copy the currently selected text to the clipboard, removing prompts. |
|
154 | """ Copy the currently selected text to the clipboard, removing prompts. | |
155 | """ |
|
155 | """ | |
156 | text = unicode(self._control.textCursor().selection().toPlainText()) |
|
156 | text = unicode(self._control.textCursor().selection().toPlainText()) | |
157 | if text: |
|
157 | if text: | |
158 | lines = map(transform_classic_prompt, text.splitlines()) |
|
158 | lines = map(transform_classic_prompt, text.splitlines()) | |
159 | text = '\n'.join(lines) |
|
159 | text = '\n'.join(lines) | |
160 | QtGui.QApplication.clipboard().setText(text) |
|
160 | QtGui.QApplication.clipboard().setText(text) | |
161 |
|
161 | |||
162 | #--------------------------------------------------------------------------- |
|
162 | #--------------------------------------------------------------------------- | |
163 | # 'ConsoleWidget' abstract interface |
|
163 | # 'ConsoleWidget' abstract interface | |
164 | #--------------------------------------------------------------------------- |
|
164 | #--------------------------------------------------------------------------- | |
165 |
|
165 | |||
166 | def _is_complete(self, source, interactive): |
|
166 | def _is_complete(self, source, interactive): | |
167 | """ Returns whether 'source' can be completely processed and a new |
|
167 | """ Returns whether 'source' can be completely processed and a new | |
168 | prompt created. When triggered by an Enter/Return key press, |
|
168 | prompt created. When triggered by an Enter/Return key press, | |
169 | 'interactive' is True; otherwise, it is False. |
|
169 | 'interactive' is True; otherwise, it is False. | |
170 | """ |
|
170 | """ | |
171 | complete = self._input_splitter.push(source) |
|
171 | complete = self._input_splitter.push(source) | |
172 | if interactive: |
|
172 | if interactive: | |
173 | complete = not self._input_splitter.push_accepts_more() |
|
173 | complete = not self._input_splitter.push_accepts_more() | |
174 | return complete |
|
174 | return complete | |
175 |
|
175 | |||
176 | def _execute(self, source, hidden): |
|
176 | def _execute(self, source, hidden): | |
177 | """ Execute 'source'. If 'hidden', do not show any output. |
|
177 | """ Execute 'source'. If 'hidden', do not show any output. | |
178 |
|
178 | |||
179 | See parent class :meth:`execute` docstring for full details. |
|
179 | See parent class :meth:`execute` docstring for full details. | |
180 | """ |
|
180 | """ | |
181 | msg_id = self.kernel_manager.xreq_channel.execute(source, hidden) |
|
181 | msg_id = self.kernel_manager.xreq_channel.execute(source, hidden) | |
182 | self._request_info['execute'] = self._ExecutionRequest(msg_id, 'user') |
|
182 | self._request_info['execute'] = self._ExecutionRequest(msg_id, 'user') | |
183 | self._hidden = hidden |
|
183 | self._hidden = hidden | |
184 |
|
184 | |||
185 | def _prompt_started_hook(self): |
|
185 | def _prompt_started_hook(self): | |
186 | """ Called immediately after a new prompt is displayed. |
|
186 | """ Called immediately after a new prompt is displayed. | |
187 | """ |
|
187 | """ | |
188 | if not self._reading: |
|
188 | if not self._reading: | |
189 | self._highlighter.highlighting_on = True |
|
189 | self._highlighter.highlighting_on = True | |
190 |
|
190 | |||
191 | def _prompt_finished_hook(self): |
|
191 | def _prompt_finished_hook(self): | |
192 | """ Called immediately after a prompt is finished, i.e. when some input |
|
192 | """ Called immediately after a prompt is finished, i.e. when some input | |
193 | will be processed and a new prompt displayed. |
|
193 | will be processed and a new prompt displayed. | |
194 | """ |
|
194 | """ | |
195 | if not self._reading: |
|
195 | if not self._reading: | |
196 | self._highlighter.highlighting_on = False |
|
196 | self._highlighter.highlighting_on = False | |
197 |
|
197 | |||
198 | def _tab_pressed(self): |
|
198 | def _tab_pressed(self): | |
199 | """ Called when the tab key is pressed. Returns whether to continue |
|
199 | """ Called when the tab key is pressed. Returns whether to continue | |
200 | processing the event. |
|
200 | processing the event. | |
201 | """ |
|
201 | """ | |
202 | # Perform tab completion if: |
|
202 | # Perform tab completion if: | |
203 | # 1) The cursor is in the input buffer. |
|
203 | # 1) The cursor is in the input buffer. | |
204 | # 2) There is a non-whitespace character before the cursor. |
|
204 | # 2) There is a non-whitespace character before the cursor. | |
205 | text = self._get_input_buffer_cursor_line() |
|
205 | text = self._get_input_buffer_cursor_line() | |
206 | if text is None: |
|
206 | if text is None: | |
207 | return False |
|
207 | return False | |
208 | complete = bool(text[:self._get_input_buffer_cursor_column()].strip()) |
|
208 | complete = bool(text[:self._get_input_buffer_cursor_column()].strip()) | |
209 | if complete: |
|
209 | if complete: | |
210 | self._complete() |
|
210 | self._complete() | |
211 | return not complete |
|
211 | return not complete | |
212 |
|
212 | |||
213 | #--------------------------------------------------------------------------- |
|
213 | #--------------------------------------------------------------------------- | |
214 | # 'ConsoleWidget' protected interface |
|
214 | # 'ConsoleWidget' protected interface | |
215 | #--------------------------------------------------------------------------- |
|
215 | #--------------------------------------------------------------------------- | |
216 |
|
216 | |||
217 | def _context_menu_make(self, pos): |
|
217 | def _context_menu_make(self, pos): | |
218 | """ Reimplemented to add an action for raw copy. |
|
218 | """ Reimplemented to add an action for raw copy. | |
219 | """ |
|
219 | """ | |
220 | menu = super(FrontendWidget, self)._context_menu_make(pos) |
|
220 | menu = super(FrontendWidget, self)._context_menu_make(pos) | |
221 | for before_action in menu.actions(): |
|
221 | for before_action in menu.actions(): | |
222 | if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ |
|
222 | if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ | |
223 | QtGui.QKeySequence.ExactMatch: |
|
223 | QtGui.QKeySequence.ExactMatch: | |
224 | menu.insertAction(before_action, self._copy_raw_action) |
|
224 | menu.insertAction(before_action, self._copy_raw_action) | |
225 | break |
|
225 | break | |
226 | return menu |
|
226 | return menu | |
227 |
|
227 | |||
228 | def _event_filter_console_keypress(self, event): |
|
228 | def _event_filter_console_keypress(self, event): | |
229 | """ Reimplemented for execution interruption and smart backspace. |
|
229 | """ Reimplemented for execution interruption and smart backspace. | |
230 | """ |
|
230 | """ | |
231 | key = event.key() |
|
231 | key = event.key() | |
232 | if self._control_key_down(event.modifiers(), include_command=False): |
|
232 | if self._control_key_down(event.modifiers(), include_command=False): | |
233 |
|
233 | |||
234 | if key == QtCore.Qt.Key_C and self._executing: |
|
234 | if key == QtCore.Qt.Key_C and self._executing: | |
235 | self.interrupt_kernel() |
|
235 | self.interrupt_kernel() | |
236 | return True |
|
236 | return True | |
237 |
|
237 | |||
238 | elif key == QtCore.Qt.Key_Period: |
|
238 | elif key == QtCore.Qt.Key_Period: | |
239 | message = 'Are you sure you want to restart the kernel?' |
|
239 | message = 'Are you sure you want to restart the kernel?' | |
240 | self.restart_kernel(message, now=False) |
|
240 | self.restart_kernel(message, now=False) | |
241 | return True |
|
241 | return True | |
242 |
|
242 | |||
243 | elif not event.modifiers() & QtCore.Qt.AltModifier: |
|
243 | elif not event.modifiers() & QtCore.Qt.AltModifier: | |
244 |
|
244 | |||
245 | # Smart backspace: remove four characters in one backspace if: |
|
245 | # Smart backspace: remove four characters in one backspace if: | |
246 | # 1) everything left of the cursor is whitespace |
|
246 | # 1) everything left of the cursor is whitespace | |
247 | # 2) the four characters immediately left of the cursor are spaces |
|
247 | # 2) the four characters immediately left of the cursor are spaces | |
248 | if key == QtCore.Qt.Key_Backspace: |
|
248 | if key == QtCore.Qt.Key_Backspace: | |
249 | col = self._get_input_buffer_cursor_column() |
|
249 | col = self._get_input_buffer_cursor_column() | |
250 | cursor = self._control.textCursor() |
|
250 | cursor = self._control.textCursor() | |
251 | if col > 3 and not cursor.hasSelection(): |
|
251 | if col > 3 and not cursor.hasSelection(): | |
252 | text = self._get_input_buffer_cursor_line()[:col] |
|
252 | text = self._get_input_buffer_cursor_line()[:col] | |
253 | if text.endswith(' ') and not text.strip(): |
|
253 | if text.endswith(' ') and not text.strip(): | |
254 | cursor.movePosition(QtGui.QTextCursor.Left, |
|
254 | cursor.movePosition(QtGui.QTextCursor.Left, | |
255 | QtGui.QTextCursor.KeepAnchor, 4) |
|
255 | QtGui.QTextCursor.KeepAnchor, 4) | |
256 | cursor.removeSelectedText() |
|
256 | cursor.removeSelectedText() | |
257 | return True |
|
257 | return True | |
258 |
|
258 | |||
259 | return super(FrontendWidget, self)._event_filter_console_keypress(event) |
|
259 | return super(FrontendWidget, self)._event_filter_console_keypress(event) | |
260 |
|
260 | |||
261 | def _insert_continuation_prompt(self, cursor): |
|
261 | def _insert_continuation_prompt(self, cursor): | |
262 | """ Reimplemented for auto-indentation. |
|
262 | """ Reimplemented for auto-indentation. | |
263 | """ |
|
263 | """ | |
264 | super(FrontendWidget, self)._insert_continuation_prompt(cursor) |
|
264 | super(FrontendWidget, self)._insert_continuation_prompt(cursor) | |
265 | cursor.insertText(' ' * self._input_splitter.indent_spaces) |
|
265 | cursor.insertText(' ' * self._input_splitter.indent_spaces) | |
266 |
|
266 | |||
267 | #--------------------------------------------------------------------------- |
|
267 | #--------------------------------------------------------------------------- | |
268 | # 'BaseFrontendMixin' abstract interface |
|
268 | # 'BaseFrontendMixin' abstract interface | |
269 | #--------------------------------------------------------------------------- |
|
269 | #--------------------------------------------------------------------------- | |
270 |
|
270 | |||
271 | def _handle_complete_reply(self, rep): |
|
271 | def _handle_complete_reply(self, rep): | |
272 | """ Handle replies for tab completion. |
|
272 | """ Handle replies for tab completion. | |
273 | """ |
|
273 | """ | |
274 | cursor = self._get_cursor() |
|
274 | cursor = self._get_cursor() | |
275 | info = self._request_info.get('complete') |
|
275 | info = self._request_info.get('complete') | |
276 | if info and info.id == rep['parent_header']['msg_id'] and \ |
|
276 | if info and info.id == rep['parent_header']['msg_id'] and \ | |
277 | info.pos == cursor.position(): |
|
277 | info.pos == cursor.position(): | |
278 | text = '.'.join(self._get_context()) |
|
278 | text = '.'.join(self._get_context()) | |
279 | cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) |
|
279 | cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) | |
280 | self._complete_with_items(cursor, rep['content']['matches']) |
|
280 | self._complete_with_items(cursor, rep['content']['matches']) | |
281 |
|
281 | |||
282 | def _handle_execute_reply(self, msg): |
|
282 | def _handle_execute_reply(self, msg): | |
283 | """ Handles replies for code execution. |
|
283 | """ Handles replies for code execution. | |
284 | """ |
|
284 | """ | |
285 | info = self._request_info.get('execute') |
|
285 | info = self._request_info.get('execute') | |
286 | if info and info.id == msg['parent_header']['msg_id'] and \ |
|
286 | if info and info.id == msg['parent_header']['msg_id'] and \ | |
287 | info.kind == 'user' and not self._hidden: |
|
287 | info.kind == 'user' and not self._hidden: | |
288 | # Make sure that all output from the SUB channel has been processed |
|
288 | # Make sure that all output from the SUB channel has been processed | |
289 | # before writing a new prompt. |
|
289 | # before writing a new prompt. | |
290 | self.kernel_manager.sub_channel.flush() |
|
290 | self.kernel_manager.sub_channel.flush() | |
291 |
|
291 | |||
292 | # Reset the ANSI style information to prevent bad text in stdout |
|
292 | # Reset the ANSI style information to prevent bad text in stdout | |
293 | # from messing up our colors. We're not a true terminal so we're |
|
293 | # from messing up our colors. We're not a true terminal so we're | |
294 | # allowed to do this. |
|
294 | # allowed to do this. | |
295 | if self.ansi_codes: |
|
295 | if self.ansi_codes: | |
296 | self._ansi_processor.reset_sgr() |
|
296 | self._ansi_processor.reset_sgr() | |
297 |
|
297 | |||
298 | content = msg['content'] |
|
298 | content = msg['content'] | |
299 | status = content['status'] |
|
299 | status = content['status'] | |
300 | if status == 'ok': |
|
300 | if status == 'ok': | |
301 | self._process_execute_ok(msg) |
|
301 | self._process_execute_ok(msg) | |
302 | elif status == 'error': |
|
302 | elif status == 'error': | |
303 | self._process_execute_error(msg) |
|
303 | self._process_execute_error(msg) | |
304 | elif status == 'abort': |
|
304 | elif status == 'abort': | |
305 | self._process_execute_abort(msg) |
|
305 | self._process_execute_abort(msg) | |
306 |
|
306 | |||
307 | self._show_interpreter_prompt_for_reply(msg) |
|
307 | self._show_interpreter_prompt_for_reply(msg) | |
308 | self.executed.emit(msg) |
|
308 | self.executed.emit(msg) | |
309 |
|
309 | |||
310 | def _handle_input_request(self, msg): |
|
310 | def _handle_input_request(self, msg): | |
311 | """ Handle requests for raw_input. |
|
311 | """ Handle requests for raw_input. | |
312 | """ |
|
312 | """ | |
313 | if self._hidden: |
|
313 | if self._hidden: | |
314 | raise RuntimeError('Request for raw input during hidden execution.') |
|
314 | raise RuntimeError('Request for raw input during hidden execution.') | |
315 |
|
315 | |||
316 | # Make sure that all output from the SUB channel has been processed |
|
316 | # Make sure that all output from the SUB channel has been processed | |
317 | # before entering readline mode. |
|
317 | # before entering readline mode. | |
318 | self.kernel_manager.sub_channel.flush() |
|
318 | self.kernel_manager.sub_channel.flush() | |
319 |
|
319 | |||
320 | def callback(line): |
|
320 | def callback(line): | |
321 | self.kernel_manager.rep_channel.input(line) |
|
321 | self.kernel_manager.rep_channel.input(line) | |
322 | self._readline(msg['content']['prompt'], callback=callback) |
|
322 | self._readline(msg['content']['prompt'], callback=callback) | |
323 |
|
323 | |||
324 | def _handle_kernel_died(self, since_last_heartbeat): |
|
324 | def _handle_kernel_died(self, since_last_heartbeat): | |
325 | """ Handle the kernel's death by asking if the user wants to restart. |
|
325 | """ Handle the kernel's death by asking if the user wants to restart. | |
326 | """ |
|
326 | """ | |
327 | if self.custom_restart: |
|
327 | if self.custom_restart: | |
328 | self.custom_restart_kernel_died.emit(since_last_heartbeat) |
|
328 | self.custom_restart_kernel_died.emit(since_last_heartbeat) | |
329 | else: |
|
329 | else: | |
330 | message = 'The kernel heartbeat has been inactive for %.2f ' \ |
|
330 | message = 'The kernel heartbeat has been inactive for %.2f ' \ | |
331 | 'seconds. Do you want to restart the kernel? You may ' \ |
|
331 | 'seconds. Do you want to restart the kernel? You may ' \ | |
332 | 'first want to check the network connection.' % \ |
|
332 | 'first want to check the network connection.' % \ | |
333 | since_last_heartbeat |
|
333 | since_last_heartbeat | |
334 | self.restart_kernel(message, now=True) |
|
334 | self.restart_kernel(message, now=True) | |
335 |
|
335 | |||
336 | def _handle_object_info_reply(self, rep): |
|
336 | def _handle_object_info_reply(self, rep): | |
337 | """ Handle replies for call tips. |
|
337 | """ Handle replies for call tips. | |
338 | """ |
|
338 | """ | |
339 | cursor = self._get_cursor() |
|
339 | cursor = self._get_cursor() | |
340 | info = self._request_info.get('call_tip') |
|
340 | info = self._request_info.get('call_tip') | |
341 | if info and info.id == rep['parent_header']['msg_id'] and \ |
|
341 | if info and info.id == rep['parent_header']['msg_id'] and \ | |
342 | info.pos == cursor.position(): |
|
342 | info.pos == cursor.position(): | |
343 | # Get the information for a call tip. For now we format the call |
|
343 | # Get the information for a call tip. For now we format the call | |
344 | # line as string, later we can pass False to format_call and |
|
344 | # line as string, later we can pass False to format_call and | |
345 | # syntax-highlight it ourselves for nicer formatting in the |
|
345 | # syntax-highlight it ourselves for nicer formatting in the | |
346 | # calltip. |
|
346 | # calltip. | |
347 | call_info, doc = call_tip(rep['content'], format_call=True) |
|
347 | call_info, doc = call_tip(rep['content'], format_call=True) | |
348 | if call_info or doc: |
|
348 | if call_info or doc: | |
349 | self._call_tip_widget.show_call_info(call_info, doc) |
|
349 | self._call_tip_widget.show_call_info(call_info, doc) | |
350 |
|
350 | |||
351 | def _handle_pyout(self, msg): |
|
351 | def _handle_pyout(self, msg): | |
352 | """ Handle display hook output. |
|
352 | """ Handle display hook output. | |
353 | """ |
|
353 | """ | |
354 | if not self._hidden and self._is_from_this_session(msg): |
|
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 | def _handle_stream(self, msg): |
|
357 | def _handle_stream(self, msg): | |
358 | """ Handle stdout, stderr, and stdin. |
|
358 | """ Handle stdout, stderr, and stdin. | |
359 | """ |
|
359 | """ | |
360 | if not self._hidden and self._is_from_this_session(msg): |
|
360 | if not self._hidden and self._is_from_this_session(msg): | |
361 | # Most consoles treat tabs as being 8 space characters. Convert tabs |
|
361 | # Most consoles treat tabs as being 8 space characters. Convert tabs | |
362 | # to spaces so that output looks as expected regardless of this |
|
362 | # to spaces so that output looks as expected regardless of this | |
363 | # widget's tab width. |
|
363 | # widget's tab width. | |
364 | text = msg['content']['data'].expandtabs(8) |
|
364 | text = msg['content']['data'].expandtabs(8) | |
365 |
|
365 | |||
366 | self._append_plain_text(text) |
|
366 | self._append_plain_text(text) | |
367 | self._control.moveCursor(QtGui.QTextCursor.End) |
|
367 | self._control.moveCursor(QtGui.QTextCursor.End) | |
368 |
|
368 | |||
369 | def _handle_shutdown_reply(self, msg): |
|
369 | def _handle_shutdown_reply(self, msg): | |
370 | """ Handle shutdown signal, only if from other console. |
|
370 | """ Handle shutdown signal, only if from other console. | |
371 | """ |
|
371 | """ | |
372 | if not self._hidden and not self._is_from_this_session(msg): |
|
372 | if not self._hidden and not self._is_from_this_session(msg): | |
373 | if self._local_kernel: |
|
373 | if self._local_kernel: | |
374 | if not msg['content']['restart']: |
|
374 | if not msg['content']['restart']: | |
375 | sys.exit(0) |
|
375 | sys.exit(0) | |
376 | else: |
|
376 | else: | |
377 | # we just got notified of a restart! |
|
377 | # we just got notified of a restart! | |
378 | time.sleep(0.25) # wait 1/4 sec to reset |
|
378 | time.sleep(0.25) # wait 1/4 sec to reset | |
379 | # lest the request for a new prompt |
|
379 | # lest the request for a new prompt | |
380 | # goes to the old kernel |
|
380 | # goes to the old kernel | |
381 | self.reset() |
|
381 | self.reset() | |
382 | else: # remote kernel, prompt on Kernel shutdown/reset |
|
382 | else: # remote kernel, prompt on Kernel shutdown/reset | |
383 | title = self.window().windowTitle() |
|
383 | title = self.window().windowTitle() | |
384 | if not msg['content']['restart']: |
|
384 | if not msg['content']['restart']: | |
385 | reply = QtGui.QMessageBox.question(self, title, |
|
385 | reply = QtGui.QMessageBox.question(self, title, | |
386 | "Kernel has been shutdown permanently. Close the Console?", |
|
386 | "Kernel has been shutdown permanently. Close the Console?", | |
387 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) |
|
387 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) | |
388 | if reply == QtGui.QMessageBox.Yes: |
|
388 | if reply == QtGui.QMessageBox.Yes: | |
389 | sys.exit(0) |
|
389 | sys.exit(0) | |
390 | else: |
|
390 | else: | |
391 | reply = QtGui.QMessageBox.question(self, title, |
|
391 | reply = QtGui.QMessageBox.question(self, title, | |
392 | "Kernel has been reset. Clear the Console?", |
|
392 | "Kernel has been reset. Clear the Console?", | |
393 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) |
|
393 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) | |
394 | if reply == QtGui.QMessageBox.Yes: |
|
394 | if reply == QtGui.QMessageBox.Yes: | |
395 | time.sleep(0.25) # wait 1/4 sec to reset |
|
395 | time.sleep(0.25) # wait 1/4 sec to reset | |
396 | # lest the request for a new prompt |
|
396 | # lest the request for a new prompt | |
397 | # goes to the old kernel |
|
397 | # goes to the old kernel | |
398 | self.reset() |
|
398 | self.reset() | |
399 |
|
399 | |||
400 | def _started_channels(self): |
|
400 | def _started_channels(self): | |
401 | """ Called when the KernelManager channels have started listening or |
|
401 | """ Called when the KernelManager channels have started listening or | |
402 | when the frontend is assigned an already listening KernelManager. |
|
402 | when the frontend is assigned an already listening KernelManager. | |
403 | """ |
|
403 | """ | |
404 | self.reset() |
|
404 | self.reset() | |
405 |
|
405 | |||
406 | #--------------------------------------------------------------------------- |
|
406 | #--------------------------------------------------------------------------- | |
407 | # 'FrontendWidget' public interface |
|
407 | # 'FrontendWidget' public interface | |
408 | #--------------------------------------------------------------------------- |
|
408 | #--------------------------------------------------------------------------- | |
409 |
|
409 | |||
410 | def copy_raw(self): |
|
410 | def copy_raw(self): | |
411 | """ Copy the currently selected text to the clipboard without attempting |
|
411 | """ Copy the currently selected text to the clipboard without attempting | |
412 | to remove prompts or otherwise alter the text. |
|
412 | to remove prompts or otherwise alter the text. | |
413 | """ |
|
413 | """ | |
414 | self._control.copy() |
|
414 | self._control.copy() | |
415 |
|
415 | |||
416 | def execute_file(self, path, hidden=False): |
|
416 | def execute_file(self, path, hidden=False): | |
417 | """ Attempts to execute file with 'path'. If 'hidden', no output is |
|
417 | """ Attempts to execute file with 'path'. If 'hidden', no output is | |
418 | shown. |
|
418 | shown. | |
419 | """ |
|
419 | """ | |
420 | self.execute('execfile("%s")' % path, hidden=hidden) |
|
420 | self.execute('execfile("%s")' % path, hidden=hidden) | |
421 |
|
421 | |||
422 | def interrupt_kernel(self): |
|
422 | def interrupt_kernel(self): | |
423 | """ Attempts to interrupt the running kernel. |
|
423 | """ Attempts to interrupt the running kernel. | |
424 | """ |
|
424 | """ | |
425 | if self.custom_interrupt: |
|
425 | if self.custom_interrupt: | |
426 | self.custom_interrupt_requested.emit() |
|
426 | self.custom_interrupt_requested.emit() | |
427 | elif self.kernel_manager.has_kernel: |
|
427 | elif self.kernel_manager.has_kernel: | |
428 | self.kernel_manager.interrupt_kernel() |
|
428 | self.kernel_manager.interrupt_kernel() | |
429 | else: |
|
429 | else: | |
430 | self._append_plain_text('Kernel process is either remote or ' |
|
430 | self._append_plain_text('Kernel process is either remote or ' | |
431 | 'unspecified. Cannot interrupt.\n') |
|
431 | 'unspecified. Cannot interrupt.\n') | |
432 |
|
432 | |||
433 | def reset(self): |
|
433 | def reset(self): | |
434 | """ Resets the widget to its initial state. Similar to ``clear``, but |
|
434 | """ Resets the widget to its initial state. Similar to ``clear``, but | |
435 | also re-writes the banner and aborts execution if necessary. |
|
435 | also re-writes the banner and aborts execution if necessary. | |
436 | """ |
|
436 | """ | |
437 | if self._executing: |
|
437 | if self._executing: | |
438 | self._executing = False |
|
438 | self._executing = False | |
439 | self._request_info['execute'] = None |
|
439 | self._request_info['execute'] = None | |
440 | self._reading = False |
|
440 | self._reading = False | |
441 | self._highlighter.highlighting_on = False |
|
441 | self._highlighter.highlighting_on = False | |
442 |
|
442 | |||
443 | self._control.clear() |
|
443 | self._control.clear() | |
444 | self._append_plain_text(self._get_banner()) |
|
444 | self._append_plain_text(self._get_banner()) | |
445 | self._show_interpreter_prompt() |
|
445 | self._show_interpreter_prompt() | |
446 |
|
446 | |||
447 | def restart_kernel(self, message, now=False): |
|
447 | def restart_kernel(self, message, now=False): | |
448 | """ Attempts to restart the running kernel. |
|
448 | """ Attempts to restart the running kernel. | |
449 | """ |
|
449 | """ | |
450 | # FIXME: now should be configurable via a checkbox in the dialog. Right |
|
450 | # FIXME: now should be configurable via a checkbox in the dialog. Right | |
451 | # now at least the heartbeat path sets it to True and the manual restart |
|
451 | # now at least the heartbeat path sets it to True and the manual restart | |
452 | # to False. But those should just be the pre-selected states of a |
|
452 | # to False. But those should just be the pre-selected states of a | |
453 | # checkbox that the user could override if so desired. But I don't know |
|
453 | # checkbox that the user could override if so desired. But I don't know | |
454 | # enough Qt to go implementing the checkbox now. |
|
454 | # enough Qt to go implementing the checkbox now. | |
455 |
|
455 | |||
456 | if self.custom_restart: |
|
456 | if self.custom_restart: | |
457 | self.custom_restart_requested.emit() |
|
457 | self.custom_restart_requested.emit() | |
458 |
|
458 | |||
459 | elif self.kernel_manager.has_kernel: |
|
459 | elif self.kernel_manager.has_kernel: | |
460 | # Pause the heart beat channel to prevent further warnings. |
|
460 | # Pause the heart beat channel to prevent further warnings. | |
461 | self.kernel_manager.hb_channel.pause() |
|
461 | self.kernel_manager.hb_channel.pause() | |
462 |
|
462 | |||
463 | # Prompt the user to restart the kernel. Un-pause the heartbeat if |
|
463 | # Prompt the user to restart the kernel. Un-pause the heartbeat if | |
464 | # they decline. (If they accept, the heartbeat will be un-paused |
|
464 | # they decline. (If they accept, the heartbeat will be un-paused | |
465 | # automatically when the kernel is restarted.) |
|
465 | # automatically when the kernel is restarted.) | |
466 | buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No |
|
466 | buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | |
467 | result = QtGui.QMessageBox.question(self, 'Restart kernel?', |
|
467 | result = QtGui.QMessageBox.question(self, 'Restart kernel?', | |
468 | message, buttons) |
|
468 | message, buttons) | |
469 | if result == QtGui.QMessageBox.Yes: |
|
469 | if result == QtGui.QMessageBox.Yes: | |
470 | try: |
|
470 | try: | |
471 | self.kernel_manager.restart_kernel(now=now) |
|
471 | self.kernel_manager.restart_kernel(now=now) | |
472 | except RuntimeError: |
|
472 | except RuntimeError: | |
473 | self._append_plain_text('Kernel started externally. ' |
|
473 | self._append_plain_text('Kernel started externally. ' | |
474 | 'Cannot restart.\n') |
|
474 | 'Cannot restart.\n') | |
475 | else: |
|
475 | else: | |
476 | self.reset() |
|
476 | self.reset() | |
477 | else: |
|
477 | else: | |
478 | self.kernel_manager.hb_channel.unpause() |
|
478 | self.kernel_manager.hb_channel.unpause() | |
479 |
|
479 | |||
480 | else: |
|
480 | else: | |
481 | self._append_plain_text('Kernel process is either remote or ' |
|
481 | self._append_plain_text('Kernel process is either remote or ' | |
482 | 'unspecified. Cannot restart.\n') |
|
482 | 'unspecified. Cannot restart.\n') | |
483 |
|
483 | |||
484 | #--------------------------------------------------------------------------- |
|
484 | #--------------------------------------------------------------------------- | |
485 | # 'FrontendWidget' protected interface |
|
485 | # 'FrontendWidget' protected interface | |
486 | #--------------------------------------------------------------------------- |
|
486 | #--------------------------------------------------------------------------- | |
487 |
|
487 | |||
488 | def _call_tip(self): |
|
488 | def _call_tip(self): | |
489 | """ Shows a call tip, if appropriate, at the current cursor location. |
|
489 | """ Shows a call tip, if appropriate, at the current cursor location. | |
490 | """ |
|
490 | """ | |
491 | # Decide if it makes sense to show a call tip |
|
491 | # Decide if it makes sense to show a call tip | |
492 | cursor = self._get_cursor() |
|
492 | cursor = self._get_cursor() | |
493 | cursor.movePosition(QtGui.QTextCursor.Left) |
|
493 | cursor.movePosition(QtGui.QTextCursor.Left) | |
494 | if cursor.document().characterAt(cursor.position()).toAscii() != '(': |
|
494 | if cursor.document().characterAt(cursor.position()).toAscii() != '(': | |
495 | return False |
|
495 | return False | |
496 | context = self._get_context(cursor) |
|
496 | context = self._get_context(cursor) | |
497 | if not context: |
|
497 | if not context: | |
498 | return False |
|
498 | return False | |
499 |
|
499 | |||
500 | # Send the metadata request to the kernel |
|
500 | # Send the metadata request to the kernel | |
501 | name = '.'.join(context) |
|
501 | name = '.'.join(context) | |
502 | msg_id = self.kernel_manager.xreq_channel.object_info(name) |
|
502 | msg_id = self.kernel_manager.xreq_channel.object_info(name) | |
503 | pos = self._get_cursor().position() |
|
503 | pos = self._get_cursor().position() | |
504 | self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) |
|
504 | self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) | |
505 | return True |
|
505 | return True | |
506 |
|
506 | |||
507 | def _complete(self): |
|
507 | def _complete(self): | |
508 | """ Performs completion at the current cursor location. |
|
508 | """ Performs completion at the current cursor location. | |
509 | """ |
|
509 | """ | |
510 | context = self._get_context() |
|
510 | context = self._get_context() | |
511 | if context: |
|
511 | if context: | |
512 | # Send the completion request to the kernel |
|
512 | # Send the completion request to the kernel | |
513 | msg_id = self.kernel_manager.xreq_channel.complete( |
|
513 | msg_id = self.kernel_manager.xreq_channel.complete( | |
514 | '.'.join(context), # text |
|
514 | '.'.join(context), # text | |
515 | self._get_input_buffer_cursor_line(), # line |
|
515 | self._get_input_buffer_cursor_line(), # line | |
516 | self._get_input_buffer_cursor_column(), # cursor_pos |
|
516 | self._get_input_buffer_cursor_column(), # cursor_pos | |
517 | self.input_buffer) # block |
|
517 | self.input_buffer) # block | |
518 | pos = self._get_cursor().position() |
|
518 | pos = self._get_cursor().position() | |
519 | info = self._CompletionRequest(msg_id, pos) |
|
519 | info = self._CompletionRequest(msg_id, pos) | |
520 | self._request_info['complete'] = info |
|
520 | self._request_info['complete'] = info | |
521 |
|
521 | |||
522 | def _get_banner(self): |
|
522 | def _get_banner(self): | |
523 | """ Gets a banner to display at the beginning of a session. |
|
523 | """ Gets a banner to display at the beginning of a session. | |
524 | """ |
|
524 | """ | |
525 | banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \ |
|
525 | banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \ | |
526 | '"license" for more information.' |
|
526 | '"license" for more information.' | |
527 | return banner % (sys.version, sys.platform) |
|
527 | return banner % (sys.version, sys.platform) | |
528 |
|
528 | |||
529 | def _get_context(self, cursor=None): |
|
529 | def _get_context(self, cursor=None): | |
530 | """ Gets the context for the specified cursor (or the current cursor |
|
530 | """ Gets the context for the specified cursor (or the current cursor | |
531 | if none is specified). |
|
531 | if none is specified). | |
532 | """ |
|
532 | """ | |
533 | if cursor is None: |
|
533 | if cursor is None: | |
534 | cursor = self._get_cursor() |
|
534 | cursor = self._get_cursor() | |
535 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, |
|
535 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, | |
536 | QtGui.QTextCursor.KeepAnchor) |
|
536 | QtGui.QTextCursor.KeepAnchor) | |
537 | text = unicode(cursor.selection().toPlainText()) |
|
537 | text = unicode(cursor.selection().toPlainText()) | |
538 | return self._completion_lexer.get_context(text) |
|
538 | return self._completion_lexer.get_context(text) | |
539 |
|
539 | |||
540 | def _process_execute_abort(self, msg): |
|
540 | def _process_execute_abort(self, msg): | |
541 | """ Process a reply for an aborted execution request. |
|
541 | """ Process a reply for an aborted execution request. | |
542 | """ |
|
542 | """ | |
543 | self._append_plain_text("ERROR: execution aborted\n") |
|
543 | self._append_plain_text("ERROR: execution aborted\n") | |
544 |
|
544 | |||
545 | def _process_execute_error(self, msg): |
|
545 | def _process_execute_error(self, msg): | |
546 | """ Process a reply for an execution request that resulted in an error. |
|
546 | """ Process a reply for an execution request that resulted in an error. | |
547 | """ |
|
547 | """ | |
548 | content = msg['content'] |
|
548 | content = msg['content'] | |
549 | # If a SystemExit is passed along, this means exit() was called - also |
|
549 | # If a SystemExit is passed along, this means exit() was called - also | |
550 | # all the ipython %exit magic syntax of '-k' to be used to keep |
|
550 | # all the ipython %exit magic syntax of '-k' to be used to keep | |
551 | # the kernel running |
|
551 | # the kernel running | |
552 | if content['ename']=='SystemExit': |
|
552 | if content['ename']=='SystemExit': | |
553 | keepkernel = content['evalue']=='-k' or content['evalue']=='True' |
|
553 | keepkernel = content['evalue']=='-k' or content['evalue']=='True' | |
554 | self._keep_kernel_on_exit = keepkernel |
|
554 | self._keep_kernel_on_exit = keepkernel | |
555 | self.exit_requested.emit() |
|
555 | self.exit_requested.emit() | |
556 | else: |
|
556 | else: | |
557 | traceback = ''.join(content['traceback']) |
|
557 | traceback = ''.join(content['traceback']) | |
558 | self._append_plain_text(traceback) |
|
558 | self._append_plain_text(traceback) | |
559 |
|
559 | |||
560 | def _process_execute_ok(self, msg): |
|
560 | def _process_execute_ok(self, msg): | |
561 | """ Process a reply for a successful execution equest. |
|
561 | """ Process a reply for a successful execution equest. | |
562 | """ |
|
562 | """ | |
563 | payload = msg['content']['payload'] |
|
563 | payload = msg['content']['payload'] | |
564 | for item in payload: |
|
564 | for item in payload: | |
565 | if not self._process_execute_payload(item): |
|
565 | if not self._process_execute_payload(item): | |
566 | warning = 'Warning: received unknown payload of type %s' |
|
566 | warning = 'Warning: received unknown payload of type %s' | |
567 | print(warning % repr(item['source'])) |
|
567 | print(warning % repr(item['source'])) | |
568 |
|
568 | |||
569 | def _process_execute_payload(self, item): |
|
569 | def _process_execute_payload(self, item): | |
570 | """ Process a single payload item from the list of payload items in an |
|
570 | """ Process a single payload item from the list of payload items in an | |
571 | execution reply. Returns whether the payload was handled. |
|
571 | execution reply. Returns whether the payload was handled. | |
572 | """ |
|
572 | """ | |
573 | # The basic FrontendWidget doesn't handle payloads, as they are a |
|
573 | # The basic FrontendWidget doesn't handle payloads, as they are a | |
574 | # mechanism for going beyond the standard Python interpreter model. |
|
574 | # mechanism for going beyond the standard Python interpreter model. | |
575 | return False |
|
575 | return False | |
576 |
|
576 | |||
577 | def _show_interpreter_prompt(self): |
|
577 | def _show_interpreter_prompt(self): | |
578 | """ Shows a prompt for the interpreter. |
|
578 | """ Shows a prompt for the interpreter. | |
579 | """ |
|
579 | """ | |
580 | self._show_prompt('>>> ') |
|
580 | self._show_prompt('>>> ') | |
581 |
|
581 | |||
582 | def _show_interpreter_prompt_for_reply(self, msg): |
|
582 | def _show_interpreter_prompt_for_reply(self, msg): | |
583 | """ Shows a prompt for the interpreter given an 'execute_reply' message. |
|
583 | """ Shows a prompt for the interpreter given an 'execute_reply' message. | |
584 | """ |
|
584 | """ | |
585 | self._show_interpreter_prompt() |
|
585 | self._show_interpreter_prompt() | |
586 |
|
586 | |||
587 | #------ Signal handlers ---------------------------------------------------- |
|
587 | #------ Signal handlers ---------------------------------------------------- | |
588 |
|
588 | |||
589 | def _document_contents_change(self, position, removed, added): |
|
589 | def _document_contents_change(self, position, removed, added): | |
590 | """ Called whenever the document's content changes. Display a call tip |
|
590 | """ Called whenever the document's content changes. Display a call tip | |
591 | if appropriate. |
|
591 | if appropriate. | |
592 | """ |
|
592 | """ | |
593 | # Calculate where the cursor should be *after* the change: |
|
593 | # Calculate where the cursor should be *after* the change: | |
594 | position += added |
|
594 | position += added | |
595 |
|
595 | |||
596 | document = self._control.document() |
|
596 | document = self._control.document() | |
597 | if position == self._get_cursor().position(): |
|
597 | if position == self._get_cursor().position(): | |
598 | self._call_tip() |
|
598 | self._call_tip() |
@@ -1,482 +1,495 b'' | |||||
1 | """ A FrontendWidget that emulates the interface of the console IPython and |
|
1 | """ A FrontendWidget that emulates the interface of the console IPython and | |
2 | supports the additional functionality provided by the IPython kernel. |
|
2 | supports the additional functionality provided by the IPython kernel. | |
3 |
|
3 | |||
4 | TODO: Add support for retrieving the system default editor. Requires code |
|
4 | TODO: Add support for retrieving the system default editor. Requires code | |
5 | paths for Windows (use the registry), Mac OS (use LaunchServices), and |
|
5 | paths for Windows (use the registry), Mac OS (use LaunchServices), and | |
6 | Linux (use the xdg system). |
|
6 | Linux (use the xdg system). | |
7 | """ |
|
7 | """ | |
8 |
|
8 | |||
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 | # Imports |
|
10 | # Imports | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | # Standard library imports |
|
13 | # Standard library imports | |
14 | from collections import namedtuple |
|
14 | from collections import namedtuple | |
15 | import re |
|
15 | import re | |
16 | from subprocess import Popen |
|
16 | from subprocess import Popen | |
17 | from textwrap import dedent |
|
17 | from textwrap import dedent | |
18 |
|
18 | |||
19 | # System library imports |
|
19 | # System library imports | |
20 | from PyQt4 import QtCore, QtGui |
|
20 | from PyQt4 import QtCore, QtGui | |
21 |
|
21 | |||
22 | # Local imports |
|
22 | # Local imports | |
23 | from IPython.core.inputsplitter import IPythonInputSplitter, \ |
|
23 | from IPython.core.inputsplitter import IPythonInputSplitter, \ | |
24 | transform_ipy_prompt |
|
24 | transform_ipy_prompt | |
25 | from IPython.core.usage import default_gui_banner |
|
25 | from IPython.core.usage import default_gui_banner | |
26 | from IPython.utils.traitlets import Bool, Str |
|
26 | from IPython.utils.traitlets import Bool, Str | |
27 | from frontend_widget import FrontendWidget |
|
27 | from frontend_widget import FrontendWidget | |
28 | from styles import (default_light_style_sheet, default_light_syntax_style, |
|
28 | from styles import (default_light_style_sheet, default_light_syntax_style, | |
29 | default_dark_style_sheet, default_dark_syntax_style, |
|
29 | default_dark_style_sheet, default_dark_syntax_style, | |
30 | default_bw_style_sheet, default_bw_syntax_style) |
|
30 | default_bw_style_sheet, default_bw_syntax_style) | |
31 |
|
31 | |||
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 | # Constants |
|
33 | # Constants | |
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | # Default strings to build and display input and output prompts (and separators |
|
36 | # Default strings to build and display input and output prompts (and separators | |
37 | # in between) |
|
37 | # in between) | |
38 | default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' |
|
38 | default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' | |
39 | default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' |
|
39 | default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' | |
40 | default_input_sep = '\n' |
|
40 | default_input_sep = '\n' | |
41 | default_output_sep = '' |
|
41 | default_output_sep = '' | |
42 | default_output_sep2 = '' |
|
42 | default_output_sep2 = '' | |
43 |
|
43 | |||
44 | # Base path for most payload sources. |
|
44 | # Base path for most payload sources. | |
45 | zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell' |
|
45 | zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell' | |
46 |
|
46 | |||
47 | #----------------------------------------------------------------------------- |
|
47 | #----------------------------------------------------------------------------- | |
48 | # IPythonWidget class |
|
48 | # IPythonWidget class | |
49 | #----------------------------------------------------------------------------- |
|
49 | #----------------------------------------------------------------------------- | |
50 |
|
50 | |||
51 | class IPythonWidget(FrontendWidget): |
|
51 | class IPythonWidget(FrontendWidget): | |
52 | """ A FrontendWidget for an IPython kernel. |
|
52 | """ A FrontendWidget for an IPython kernel. | |
53 | """ |
|
53 | """ | |
54 |
|
54 | |||
55 | # If set, the 'custom_edit_requested(str, int)' signal will be emitted when |
|
55 | # If set, the 'custom_edit_requested(str, int)' signal will be emitted when | |
56 | # an editor is needed for a file. This overrides 'editor' and 'editor_line' |
|
56 | # an editor is needed for a file. This overrides 'editor' and 'editor_line' | |
57 | # settings. |
|
57 | # settings. | |
58 | custom_edit = Bool(False) |
|
58 | custom_edit = Bool(False) | |
59 | custom_edit_requested = QtCore.pyqtSignal(object, object) |
|
59 | custom_edit_requested = QtCore.pyqtSignal(object, object) | |
60 |
|
60 | |||
61 | # A command for invoking a system text editor. If the string contains a |
|
61 | # A command for invoking a system text editor. If the string contains a | |
62 | # {filename} format specifier, it will be used. Otherwise, the filename will |
|
62 | # {filename} format specifier, it will be used. Otherwise, the filename will | |
63 | # be appended to the end the command. |
|
63 | # be appended to the end the command. | |
64 | editor = Str('default', config=True) |
|
64 | editor = Str('default', config=True) | |
65 |
|
65 | |||
66 | # The editor command to use when a specific line number is requested. The |
|
66 | # The editor command to use when a specific line number is requested. The | |
67 | # string should contain two format specifiers: {line} and {filename}. If |
|
67 | # string should contain two format specifiers: {line} and {filename}. If | |
68 | # this parameter is not specified, the line number option to the %edit magic |
|
68 | # this parameter is not specified, the line number option to the %edit magic | |
69 | # will be ignored. |
|
69 | # will be ignored. | |
70 | editor_line = Str(config=True) |
|
70 | editor_line = Str(config=True) | |
71 |
|
71 | |||
72 | # A CSS stylesheet. The stylesheet can contain classes for: |
|
72 | # A CSS stylesheet. The stylesheet can contain classes for: | |
73 | # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc |
|
73 | # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc | |
74 | # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter) |
|
74 | # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter) | |
75 | # 3. IPython: .error, .in-prompt, .out-prompt, etc |
|
75 | # 3. IPython: .error, .in-prompt, .out-prompt, etc | |
76 | style_sheet = Str(config=True) |
|
76 | style_sheet = Str(config=True) | |
77 |
|
77 | |||
78 | # If not empty, use this Pygments style for syntax highlighting. Otherwise, |
|
78 | # If not empty, use this Pygments style for syntax highlighting. Otherwise, | |
79 | # the style sheet is queried for Pygments style information. |
|
79 | # the style sheet is queried for Pygments style information. | |
80 | syntax_style = Str(config=True) |
|
80 | syntax_style = Str(config=True) | |
81 |
|
81 | |||
82 | # Prompts. |
|
82 | # Prompts. | |
83 | in_prompt = Str(default_in_prompt, config=True) |
|
83 | in_prompt = Str(default_in_prompt, config=True) | |
84 | out_prompt = Str(default_out_prompt, config=True) |
|
84 | out_prompt = Str(default_out_prompt, config=True) | |
85 | input_sep = Str(default_input_sep, config=True) |
|
85 | input_sep = Str(default_input_sep, config=True) | |
86 | output_sep = Str(default_output_sep, config=True) |
|
86 | output_sep = Str(default_output_sep, config=True) | |
87 | output_sep2 = Str(default_output_sep2, config=True) |
|
87 | output_sep2 = Str(default_output_sep2, config=True) | |
88 |
|
88 | |||
89 | # FrontendWidget protected class variables. |
|
89 | # FrontendWidget protected class variables. | |
90 | _input_splitter_class = IPythonInputSplitter |
|
90 | _input_splitter_class = IPythonInputSplitter | |
91 |
|
91 | |||
92 | # IPythonWidget protected class variables. |
|
92 | # IPythonWidget protected class variables. | |
93 | _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) |
|
93 | _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) | |
94 | _payload_source_edit = zmq_shell_source + '.edit_magic' |
|
94 | _payload_source_edit = zmq_shell_source + '.edit_magic' | |
95 | _payload_source_exit = zmq_shell_source + '.ask_exit' |
|
95 | _payload_source_exit = zmq_shell_source + '.ask_exit' | |
96 | _payload_source_loadpy = zmq_shell_source + '.magic_loadpy' |
|
96 | _payload_source_loadpy = zmq_shell_source + '.magic_loadpy' | |
97 | _payload_source_page = 'IPython.zmq.page.page' |
|
97 | _payload_source_page = 'IPython.zmq.page.page' | |
98 |
|
98 | |||
99 | #--------------------------------------------------------------------------- |
|
99 | #--------------------------------------------------------------------------- | |
100 | # 'object' interface |
|
100 | # 'object' interface | |
101 | #--------------------------------------------------------------------------- |
|
101 | #--------------------------------------------------------------------------- | |
102 |
|
102 | |||
103 | def __init__(self, *args, **kw): |
|
103 | def __init__(self, *args, **kw): | |
104 | super(IPythonWidget, self).__init__(*args, **kw) |
|
104 | super(IPythonWidget, self).__init__(*args, **kw) | |
105 |
|
105 | |||
106 | # IPythonWidget protected variables. |
|
106 | # IPythonWidget protected variables. | |
107 | self._code_to_load = None |
|
107 | self._code_to_load = None | |
108 | self._payload_handlers = { |
|
108 | self._payload_handlers = { | |
109 | self._payload_source_edit : self._handle_payload_edit, |
|
109 | self._payload_source_edit : self._handle_payload_edit, | |
110 | self._payload_source_exit : self._handle_payload_exit, |
|
110 | self._payload_source_exit : self._handle_payload_exit, | |
111 | self._payload_source_page : self._handle_payload_page, |
|
111 | self._payload_source_page : self._handle_payload_page, | |
112 | self._payload_source_loadpy : self._handle_payload_loadpy } |
|
112 | self._payload_source_loadpy : self._handle_payload_loadpy } | |
113 | self._previous_prompt_obj = None |
|
113 | self._previous_prompt_obj = None | |
114 | self._keep_kernel_on_exit = None |
|
114 | self._keep_kernel_on_exit = None | |
115 |
|
115 | |||
116 | # Initialize widget styling. |
|
116 | # Initialize widget styling. | |
117 | if self.style_sheet: |
|
117 | if self.style_sheet: | |
118 | self._style_sheet_changed() |
|
118 | self._style_sheet_changed() | |
119 | self._syntax_style_changed() |
|
119 | self._syntax_style_changed() | |
120 | else: |
|
120 | else: | |
121 | self.set_default_style() |
|
121 | self.set_default_style() | |
122 |
|
122 | |||
123 | #--------------------------------------------------------------------------- |
|
123 | #--------------------------------------------------------------------------- | |
124 | # 'BaseFrontendMixin' abstract interface |
|
124 | # 'BaseFrontendMixin' abstract interface | |
125 | #--------------------------------------------------------------------------- |
|
125 | #--------------------------------------------------------------------------- | |
126 |
|
126 | |||
127 | def _handle_complete_reply(self, rep): |
|
127 | def _handle_complete_reply(self, rep): | |
128 | """ Reimplemented to support IPython's improved completion machinery. |
|
128 | """ Reimplemented to support IPython's improved completion machinery. | |
129 | """ |
|
129 | """ | |
130 | cursor = self._get_cursor() |
|
130 | cursor = self._get_cursor() | |
131 | info = self._request_info.get('complete') |
|
131 | info = self._request_info.get('complete') | |
132 | if info and info.id == rep['parent_header']['msg_id'] and \ |
|
132 | if info and info.id == rep['parent_header']['msg_id'] and \ | |
133 | info.pos == cursor.position(): |
|
133 | info.pos == cursor.position(): | |
134 | matches = rep['content']['matches'] |
|
134 | matches = rep['content']['matches'] | |
135 | text = rep['content']['matched_text'] |
|
135 | text = rep['content']['matched_text'] | |
136 | offset = len(text) |
|
136 | offset = len(text) | |
137 |
|
137 | |||
138 | # Clean up matches with period and path separators if the matched |
|
138 | # Clean up matches with period and path separators if the matched | |
139 | # text has not been transformed. This is done by truncating all |
|
139 | # text has not been transformed. This is done by truncating all | |
140 | # but the last component and then suitably decreasing the offset |
|
140 | # but the last component and then suitably decreasing the offset | |
141 | # between the current cursor position and the start of completion. |
|
141 | # between the current cursor position and the start of completion. | |
142 | if len(matches) > 1 and matches[0][:offset] == text: |
|
142 | if len(matches) > 1 and matches[0][:offset] == text: | |
143 | parts = re.split(r'[./\\]', text) |
|
143 | parts = re.split(r'[./\\]', text) | |
144 | sep_count = len(parts) - 1 |
|
144 | sep_count = len(parts) - 1 | |
145 | if sep_count: |
|
145 | if sep_count: | |
146 | chop_length = sum(map(len, parts[:sep_count])) + sep_count |
|
146 | chop_length = sum(map(len, parts[:sep_count])) + sep_count | |
147 | matches = [ match[chop_length:] for match in matches ] |
|
147 | matches = [ match[chop_length:] for match in matches ] | |
148 | offset -= chop_length |
|
148 | offset -= chop_length | |
149 |
|
149 | |||
150 | # Move the cursor to the start of the match and complete. |
|
150 | # Move the cursor to the start of the match and complete. | |
151 | cursor.movePosition(QtGui.QTextCursor.Left, n=offset) |
|
151 | cursor.movePosition(QtGui.QTextCursor.Left, n=offset) | |
152 | self._complete_with_items(cursor, matches) |
|
152 | self._complete_with_items(cursor, matches) | |
153 |
|
153 | |||
154 | def _handle_execute_reply(self, msg): |
|
154 | def _handle_execute_reply(self, msg): | |
155 | """ Reimplemented to support prompt requests. |
|
155 | """ Reimplemented to support prompt requests. | |
156 | """ |
|
156 | """ | |
157 | info = self._request_info.get('execute') |
|
157 | info = self._request_info.get('execute') | |
158 | if info and info.id == msg['parent_header']['msg_id']: |
|
158 | if info and info.id == msg['parent_header']['msg_id']: | |
159 | if info.kind == 'prompt': |
|
159 | if info.kind == 'prompt': | |
160 | number = msg['content']['execution_count'] + 1 |
|
160 | number = msg['content']['execution_count'] + 1 | |
161 | self._show_interpreter_prompt(number) |
|
161 | self._show_interpreter_prompt(number) | |
162 | else: |
|
162 | else: | |
163 | super(IPythonWidget, self)._handle_execute_reply(msg) |
|
163 | super(IPythonWidget, self)._handle_execute_reply(msg) | |
164 |
|
164 | |||
165 | def _handle_history_reply(self, msg): |
|
165 | def _handle_history_reply(self, msg): | |
166 | """ Implemented to handle history replies, which are only supported by |
|
166 | """ Implemented to handle history replies, which are only supported by | |
167 | the IPython kernel. |
|
167 | the IPython kernel. | |
168 | """ |
|
168 | """ | |
169 | history_dict = msg['content']['history'] |
|
169 | history_dict = msg['content']['history'] | |
170 | input_history_dict = {} |
|
170 | input_history_dict = {} | |
171 | for key,val in history_dict.items(): |
|
171 | for key,val in history_dict.items(): | |
172 | input_history_dict[int(key)] = val |
|
172 | input_history_dict[int(key)] = val | |
173 | items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ] |
|
173 | items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ] | |
174 | self._set_history(items) |
|
174 | self._set_history(items) | |
175 |
|
175 | |||
176 | def _handle_pyout(self, msg): |
|
176 | def _handle_pyout(self, msg): | |
177 | """ Reimplemented for IPython-style "display hook". |
|
177 | """ Reimplemented for IPython-style "display hook". | |
178 | """ |
|
178 | """ | |
179 | if not self._hidden and self._is_from_this_session(msg): |
|
179 | if not self._hidden and self._is_from_this_session(msg): | |
180 | content = msg['content'] |
|
180 | content = msg['content'] | |
181 | prompt_number = content['execution_count'] |
|
181 | prompt_number = content['execution_count'] | |
182 | self._append_plain_text(self.output_sep) |
|
182 | data = content['data'] | |
183 | self._append_html(self._make_out_prompt(prompt_number)) |
|
183 | if data.has_key('text/html'): | |
184 |
self._append_plain_text( |
|
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 | def _handle_display_data(self, msg): |
|
195 | def _handle_display_data(self, msg): | |
187 | """ The base handler for the ``display_data`` message. |
|
196 | """ The base handler for the ``display_data`` message. | |
188 | """ |
|
197 | """ | |
189 | # For now, we don't display data from other frontends, but we |
|
198 | # For now, we don't display data from other frontends, but we | |
190 | # eventually will as this allows all frontends to monitor the display |
|
199 | # eventually will as this allows all frontends to monitor the display | |
191 | # data. But we need to figure out how to handle this in the GUI. |
|
200 | # data. But we need to figure out how to handle this in the GUI. | |
192 | if not self._hidden and self._is_from_this_session(msg): |
|
201 | if not self._hidden and self._is_from_this_session(msg): | |
193 | source = msg['content']['source'] |
|
202 | source = msg['content']['source'] | |
194 | data = msg['content']['data'] |
|
203 | data = msg['content']['data'] | |
195 | metadata = msg['content']['metadata'] |
|
204 | metadata = msg['content']['metadata'] | |
196 | # In the regular IPythonWidget, we simply print the plain text |
|
205 | # In the regular IPythonWidget, we simply print the plain text | |
197 | # representation. |
|
206 | # representation. | |
198 |
if data.has_key('text/ |
|
207 | if data.has_key('text/html'): | |
199 |
|
|
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 | def _started_channels(self): |
|
214 | def _started_channels(self): | |
202 | """ Reimplemented to make a history request. |
|
215 | """ Reimplemented to make a history request. | |
203 | """ |
|
216 | """ | |
204 | super(IPythonWidget, self)._started_channels() |
|
217 | super(IPythonWidget, self)._started_channels() | |
205 | self.kernel_manager.xreq_channel.history(raw=True, output=False) |
|
218 | self.kernel_manager.xreq_channel.history(raw=True, output=False) | |
206 |
|
219 | |||
207 | #--------------------------------------------------------------------------- |
|
220 | #--------------------------------------------------------------------------- | |
208 | # 'ConsoleWidget' public interface |
|
221 | # 'ConsoleWidget' public interface | |
209 | #--------------------------------------------------------------------------- |
|
222 | #--------------------------------------------------------------------------- | |
210 |
|
223 | |||
211 | def copy(self): |
|
224 | def copy(self): | |
212 | """ Copy the currently selected text to the clipboard, removing prompts |
|
225 | """ Copy the currently selected text to the clipboard, removing prompts | |
213 | if possible. |
|
226 | if possible. | |
214 | """ |
|
227 | """ | |
215 | text = unicode(self._control.textCursor().selection().toPlainText()) |
|
228 | text = unicode(self._control.textCursor().selection().toPlainText()) | |
216 | if text: |
|
229 | if text: | |
217 | lines = map(transform_ipy_prompt, text.splitlines()) |
|
230 | lines = map(transform_ipy_prompt, text.splitlines()) | |
218 | text = '\n'.join(lines) |
|
231 | text = '\n'.join(lines) | |
219 | QtGui.QApplication.clipboard().setText(text) |
|
232 | QtGui.QApplication.clipboard().setText(text) | |
220 |
|
233 | |||
221 | #--------------------------------------------------------------------------- |
|
234 | #--------------------------------------------------------------------------- | |
222 | # 'FrontendWidget' public interface |
|
235 | # 'FrontendWidget' public interface | |
223 | #--------------------------------------------------------------------------- |
|
236 | #--------------------------------------------------------------------------- | |
224 |
|
237 | |||
225 | def execute_file(self, path, hidden=False): |
|
238 | def execute_file(self, path, hidden=False): | |
226 | """ Reimplemented to use the 'run' magic. |
|
239 | """ Reimplemented to use the 'run' magic. | |
227 | """ |
|
240 | """ | |
228 | self.execute('%%run %s' % path, hidden=hidden) |
|
241 | self.execute('%%run %s' % path, hidden=hidden) | |
229 |
|
242 | |||
230 | #--------------------------------------------------------------------------- |
|
243 | #--------------------------------------------------------------------------- | |
231 | # 'FrontendWidget' protected interface |
|
244 | # 'FrontendWidget' protected interface | |
232 | #--------------------------------------------------------------------------- |
|
245 | #--------------------------------------------------------------------------- | |
233 |
|
246 | |||
234 | def _complete(self): |
|
247 | def _complete(self): | |
235 | """ Reimplemented to support IPython's improved completion machinery. |
|
248 | """ Reimplemented to support IPython's improved completion machinery. | |
236 | """ |
|
249 | """ | |
237 | # We let the kernel split the input line, so we *always* send an empty |
|
250 | # We let the kernel split the input line, so we *always* send an empty | |
238 | # text field. Readline-based frontends do get a real text field which |
|
251 | # text field. Readline-based frontends do get a real text field which | |
239 | # they can use. |
|
252 | # they can use. | |
240 | text = '' |
|
253 | text = '' | |
241 |
|
254 | |||
242 | # Send the completion request to the kernel |
|
255 | # Send the completion request to the kernel | |
243 | msg_id = self.kernel_manager.xreq_channel.complete( |
|
256 | msg_id = self.kernel_manager.xreq_channel.complete( | |
244 | text, # text |
|
257 | text, # text | |
245 | self._get_input_buffer_cursor_line(), # line |
|
258 | self._get_input_buffer_cursor_line(), # line | |
246 | self._get_input_buffer_cursor_column(), # cursor_pos |
|
259 | self._get_input_buffer_cursor_column(), # cursor_pos | |
247 | self.input_buffer) # block |
|
260 | self.input_buffer) # block | |
248 | pos = self._get_cursor().position() |
|
261 | pos = self._get_cursor().position() | |
249 | info = self._CompletionRequest(msg_id, pos) |
|
262 | info = self._CompletionRequest(msg_id, pos) | |
250 | self._request_info['complete'] = info |
|
263 | self._request_info['complete'] = info | |
251 |
|
264 | |||
252 | def _get_banner(self): |
|
265 | def _get_banner(self): | |
253 | """ Reimplemented to return IPython's default banner. |
|
266 | """ Reimplemented to return IPython's default banner. | |
254 | """ |
|
267 | """ | |
255 | return default_gui_banner |
|
268 | return default_gui_banner | |
256 |
|
269 | |||
257 | def _process_execute_error(self, msg): |
|
270 | def _process_execute_error(self, msg): | |
258 | """ Reimplemented for IPython-style traceback formatting. |
|
271 | """ Reimplemented for IPython-style traceback formatting. | |
259 | """ |
|
272 | """ | |
260 | content = msg['content'] |
|
273 | content = msg['content'] | |
261 | traceback = '\n'.join(content['traceback']) + '\n' |
|
274 | traceback = '\n'.join(content['traceback']) + '\n' | |
262 | if False: |
|
275 | if False: | |
263 | # FIXME: For now, tracebacks come as plain text, so we can't use |
|
276 | # FIXME: For now, tracebacks come as plain text, so we can't use | |
264 | # the html renderer yet. Once we refactor ultratb to produce |
|
277 | # the html renderer yet. Once we refactor ultratb to produce | |
265 | # properly styled tracebacks, this branch should be the default |
|
278 | # properly styled tracebacks, this branch should be the default | |
266 | traceback = traceback.replace(' ', ' ') |
|
279 | traceback = traceback.replace(' ', ' ') | |
267 | traceback = traceback.replace('\n', '<br/>') |
|
280 | traceback = traceback.replace('\n', '<br/>') | |
268 |
|
281 | |||
269 | ename = content['ename'] |
|
282 | ename = content['ename'] | |
270 | ename_styled = '<span class="error">%s</span>' % ename |
|
283 | ename_styled = '<span class="error">%s</span>' % ename | |
271 | traceback = traceback.replace(ename, ename_styled) |
|
284 | traceback = traceback.replace(ename, ename_styled) | |
272 |
|
285 | |||
273 | self._append_html(traceback) |
|
286 | self._append_html(traceback) | |
274 | else: |
|
287 | else: | |
275 | # This is the fallback for now, using plain text with ansi escapes |
|
288 | # This is the fallback for now, using plain text with ansi escapes | |
276 | self._append_plain_text(traceback) |
|
289 | self._append_plain_text(traceback) | |
277 |
|
290 | |||
278 | def _process_execute_payload(self, item): |
|
291 | def _process_execute_payload(self, item): | |
279 | """ Reimplemented to dispatch payloads to handler methods. |
|
292 | """ Reimplemented to dispatch payloads to handler methods. | |
280 | """ |
|
293 | """ | |
281 | handler = self._payload_handlers.get(item['source']) |
|
294 | handler = self._payload_handlers.get(item['source']) | |
282 | if handler is None: |
|
295 | if handler is None: | |
283 | # We have no handler for this type of payload, simply ignore it |
|
296 | # We have no handler for this type of payload, simply ignore it | |
284 | return False |
|
297 | return False | |
285 | else: |
|
298 | else: | |
286 | handler(item) |
|
299 | handler(item) | |
287 | return True |
|
300 | return True | |
288 |
|
301 | |||
289 | def _show_interpreter_prompt(self, number=None): |
|
302 | def _show_interpreter_prompt(self, number=None): | |
290 | """ Reimplemented for IPython-style prompts. |
|
303 | """ Reimplemented for IPython-style prompts. | |
291 | """ |
|
304 | """ | |
292 | # If a number was not specified, make a prompt number request. |
|
305 | # If a number was not specified, make a prompt number request. | |
293 | if number is None: |
|
306 | if number is None: | |
294 | msg_id = self.kernel_manager.xreq_channel.execute('', silent=True) |
|
307 | msg_id = self.kernel_manager.xreq_channel.execute('', silent=True) | |
295 | info = self._ExecutionRequest(msg_id, 'prompt') |
|
308 | info = self._ExecutionRequest(msg_id, 'prompt') | |
296 | self._request_info['execute'] = info |
|
309 | self._request_info['execute'] = info | |
297 | return |
|
310 | return | |
298 |
|
311 | |||
299 | # Show a new prompt and save information about it so that it can be |
|
312 | # Show a new prompt and save information about it so that it can be | |
300 | # updated later if the prompt number turns out to be wrong. |
|
313 | # updated later if the prompt number turns out to be wrong. | |
301 | self._prompt_sep = self.input_sep |
|
314 | self._prompt_sep = self.input_sep | |
302 | self._show_prompt(self._make_in_prompt(number), html=True) |
|
315 | self._show_prompt(self._make_in_prompt(number), html=True) | |
303 | block = self._control.document().lastBlock() |
|
316 | block = self._control.document().lastBlock() | |
304 | length = len(self._prompt) |
|
317 | length = len(self._prompt) | |
305 | self._previous_prompt_obj = self._PromptBlock(block, length, number) |
|
318 | self._previous_prompt_obj = self._PromptBlock(block, length, number) | |
306 |
|
319 | |||
307 | # Update continuation prompt to reflect (possibly) new prompt length. |
|
320 | # Update continuation prompt to reflect (possibly) new prompt length. | |
308 | self._set_continuation_prompt( |
|
321 | self._set_continuation_prompt( | |
309 | self._make_continuation_prompt(self._prompt), html=True) |
|
322 | self._make_continuation_prompt(self._prompt), html=True) | |
310 |
|
323 | |||
311 | # Load code from the %loadpy magic, if necessary. |
|
324 | # Load code from the %loadpy magic, if necessary. | |
312 | if self._code_to_load is not None: |
|
325 | if self._code_to_load is not None: | |
313 | self.input_buffer = dedent(unicode(self._code_to_load).rstrip()) |
|
326 | self.input_buffer = dedent(unicode(self._code_to_load).rstrip()) | |
314 | self._code_to_load = None |
|
327 | self._code_to_load = None | |
315 |
|
328 | |||
316 | def _show_interpreter_prompt_for_reply(self, msg): |
|
329 | def _show_interpreter_prompt_for_reply(self, msg): | |
317 | """ Reimplemented for IPython-style prompts. |
|
330 | """ Reimplemented for IPython-style prompts. | |
318 | """ |
|
331 | """ | |
319 | # Update the old prompt number if necessary. |
|
332 | # Update the old prompt number if necessary. | |
320 | content = msg['content'] |
|
333 | content = msg['content'] | |
321 | previous_prompt_number = content['execution_count'] |
|
334 | previous_prompt_number = content['execution_count'] | |
322 | if self._previous_prompt_obj and \ |
|
335 | if self._previous_prompt_obj and \ | |
323 | self._previous_prompt_obj.number != previous_prompt_number: |
|
336 | self._previous_prompt_obj.number != previous_prompt_number: | |
324 | block = self._previous_prompt_obj.block |
|
337 | block = self._previous_prompt_obj.block | |
325 |
|
338 | |||
326 | # Make sure the prompt block has not been erased. |
|
339 | # Make sure the prompt block has not been erased. | |
327 | if block.isValid() and not block.text().isEmpty(): |
|
340 | if block.isValid() and not block.text().isEmpty(): | |
328 |
|
341 | |||
329 | # Remove the old prompt and insert a new prompt. |
|
342 | # Remove the old prompt and insert a new prompt. | |
330 | cursor = QtGui.QTextCursor(block) |
|
343 | cursor = QtGui.QTextCursor(block) | |
331 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
344 | cursor.movePosition(QtGui.QTextCursor.Right, | |
332 | QtGui.QTextCursor.KeepAnchor, |
|
345 | QtGui.QTextCursor.KeepAnchor, | |
333 | self._previous_prompt_obj.length) |
|
346 | self._previous_prompt_obj.length) | |
334 | prompt = self._make_in_prompt(previous_prompt_number) |
|
347 | prompt = self._make_in_prompt(previous_prompt_number) | |
335 | self._prompt = self._insert_html_fetching_plain_text( |
|
348 | self._prompt = self._insert_html_fetching_plain_text( | |
336 | cursor, prompt) |
|
349 | cursor, prompt) | |
337 |
|
350 | |||
338 | # When the HTML is inserted, Qt blows away the syntax |
|
351 | # When the HTML is inserted, Qt blows away the syntax | |
339 | # highlighting for the line, so we need to rehighlight it. |
|
352 | # highlighting for the line, so we need to rehighlight it. | |
340 | self._highlighter.rehighlightBlock(cursor.block()) |
|
353 | self._highlighter.rehighlightBlock(cursor.block()) | |
341 |
|
354 | |||
342 | self._previous_prompt_obj = None |
|
355 | self._previous_prompt_obj = None | |
343 |
|
356 | |||
344 | # Show a new prompt with the kernel's estimated prompt number. |
|
357 | # Show a new prompt with the kernel's estimated prompt number. | |
345 | self._show_interpreter_prompt(previous_prompt_number + 1) |
|
358 | self._show_interpreter_prompt(previous_prompt_number + 1) | |
346 |
|
359 | |||
347 | #--------------------------------------------------------------------------- |
|
360 | #--------------------------------------------------------------------------- | |
348 | # 'IPythonWidget' interface |
|
361 | # 'IPythonWidget' interface | |
349 | #--------------------------------------------------------------------------- |
|
362 | #--------------------------------------------------------------------------- | |
350 |
|
363 | |||
351 | def set_default_style(self, colors='lightbg'): |
|
364 | def set_default_style(self, colors='lightbg'): | |
352 | """ Sets the widget style to the class defaults. |
|
365 | """ Sets the widget style to the class defaults. | |
353 |
|
366 | |||
354 | Parameters: |
|
367 | Parameters: | |
355 | ----------- |
|
368 | ----------- | |
356 | colors : str, optional (default lightbg) |
|
369 | colors : str, optional (default lightbg) | |
357 | Whether to use the default IPython light background or dark |
|
370 | Whether to use the default IPython light background or dark | |
358 | background or B&W style. |
|
371 | background or B&W style. | |
359 | """ |
|
372 | """ | |
360 | colors = colors.lower() |
|
373 | colors = colors.lower() | |
361 | if colors=='lightbg': |
|
374 | if colors=='lightbg': | |
362 | self.style_sheet = default_light_style_sheet |
|
375 | self.style_sheet = default_light_style_sheet | |
363 | self.syntax_style = default_light_syntax_style |
|
376 | self.syntax_style = default_light_syntax_style | |
364 | elif colors=='linux': |
|
377 | elif colors=='linux': | |
365 | self.style_sheet = default_dark_style_sheet |
|
378 | self.style_sheet = default_dark_style_sheet | |
366 | self.syntax_style = default_dark_syntax_style |
|
379 | self.syntax_style = default_dark_syntax_style | |
367 | elif colors=='nocolor': |
|
380 | elif colors=='nocolor': | |
368 | self.style_sheet = default_bw_style_sheet |
|
381 | self.style_sheet = default_bw_style_sheet | |
369 | self.syntax_style = default_bw_syntax_style |
|
382 | self.syntax_style = default_bw_syntax_style | |
370 | else: |
|
383 | else: | |
371 | raise KeyError("No such color scheme: %s"%colors) |
|
384 | raise KeyError("No such color scheme: %s"%colors) | |
372 |
|
385 | |||
373 | #--------------------------------------------------------------------------- |
|
386 | #--------------------------------------------------------------------------- | |
374 | # 'IPythonWidget' protected interface |
|
387 | # 'IPythonWidget' protected interface | |
375 | #--------------------------------------------------------------------------- |
|
388 | #--------------------------------------------------------------------------- | |
376 |
|
389 | |||
377 | def _edit(self, filename, line=None): |
|
390 | def _edit(self, filename, line=None): | |
378 | """ Opens a Python script for editing. |
|
391 | """ Opens a Python script for editing. | |
379 |
|
392 | |||
380 | Parameters: |
|
393 | Parameters: | |
381 | ----------- |
|
394 | ----------- | |
382 | filename : str |
|
395 | filename : str | |
383 | A path to a local system file. |
|
396 | A path to a local system file. | |
384 |
|
397 | |||
385 | line : int, optional |
|
398 | line : int, optional | |
386 | A line of interest in the file. |
|
399 | A line of interest in the file. | |
387 | """ |
|
400 | """ | |
388 | if self.custom_edit: |
|
401 | if self.custom_edit: | |
389 | self.custom_edit_requested.emit(filename, line) |
|
402 | self.custom_edit_requested.emit(filename, line) | |
390 | elif self.editor == 'default': |
|
403 | elif self.editor == 'default': | |
391 | self._append_plain_text('No default editor available.\n') |
|
404 | self._append_plain_text('No default editor available.\n') | |
392 | else: |
|
405 | else: | |
393 | try: |
|
406 | try: | |
394 | filename = '"%s"' % filename |
|
407 | filename = '"%s"' % filename | |
395 | if line and self.editor_line: |
|
408 | if line and self.editor_line: | |
396 | command = self.editor_line.format(filename=filename, |
|
409 | command = self.editor_line.format(filename=filename, | |
397 | line=line) |
|
410 | line=line) | |
398 | else: |
|
411 | else: | |
399 | try: |
|
412 | try: | |
400 | command = self.editor.format() |
|
413 | command = self.editor.format() | |
401 | except KeyError: |
|
414 | except KeyError: | |
402 | command = self.editor.format(filename=filename) |
|
415 | command = self.editor.format(filename=filename) | |
403 | else: |
|
416 | else: | |
404 | command += ' ' + filename |
|
417 | command += ' ' + filename | |
405 | except KeyError: |
|
418 | except KeyError: | |
406 | self._append_plain_text('Invalid editor command.\n') |
|
419 | self._append_plain_text('Invalid editor command.\n') | |
407 | else: |
|
420 | else: | |
408 | try: |
|
421 | try: | |
409 | Popen(command, shell=True) |
|
422 | Popen(command, shell=True) | |
410 | except OSError: |
|
423 | except OSError: | |
411 | msg = 'Opening editor with command "%s" failed.\n' |
|
424 | msg = 'Opening editor with command "%s" failed.\n' | |
412 | self._append_plain_text(msg % command) |
|
425 | self._append_plain_text(msg % command) | |
413 |
|
426 | |||
414 | def _make_in_prompt(self, number): |
|
427 | def _make_in_prompt(self, number): | |
415 | """ Given a prompt number, returns an HTML In prompt. |
|
428 | """ Given a prompt number, returns an HTML In prompt. | |
416 | """ |
|
429 | """ | |
417 | body = self.in_prompt % number |
|
430 | body = self.in_prompt % number | |
418 | return '<span class="in-prompt">%s</span>' % body |
|
431 | return '<span class="in-prompt">%s</span>' % body | |
419 |
|
432 | |||
420 | def _make_continuation_prompt(self, prompt): |
|
433 | def _make_continuation_prompt(self, prompt): | |
421 | """ Given a plain text version of an In prompt, returns an HTML |
|
434 | """ Given a plain text version of an In prompt, returns an HTML | |
422 | continuation prompt. |
|
435 | continuation prompt. | |
423 | """ |
|
436 | """ | |
424 | end_chars = '...: ' |
|
437 | end_chars = '...: ' | |
425 | space_count = len(prompt.lstrip('\n')) - len(end_chars) |
|
438 | space_count = len(prompt.lstrip('\n')) - len(end_chars) | |
426 | body = ' ' * space_count + end_chars |
|
439 | body = ' ' * space_count + end_chars | |
427 | return '<span class="in-prompt">%s</span>' % body |
|
440 | return '<span class="in-prompt">%s</span>' % body | |
428 |
|
441 | |||
429 | def _make_out_prompt(self, number): |
|
442 | def _make_out_prompt(self, number): | |
430 | """ Given a prompt number, returns an HTML Out prompt. |
|
443 | """ Given a prompt number, returns an HTML Out prompt. | |
431 | """ |
|
444 | """ | |
432 | body = self.out_prompt % number |
|
445 | body = self.out_prompt % number | |
433 | return '<span class="out-prompt">%s</span>' % body |
|
446 | return '<span class="out-prompt">%s</span>' % body | |
434 |
|
447 | |||
435 | #------ Payload handlers -------------------------------------------------- |
|
448 | #------ Payload handlers -------------------------------------------------- | |
436 |
|
449 | |||
437 | # Payload handlers with a generic interface: each takes the opaque payload |
|
450 | # Payload handlers with a generic interface: each takes the opaque payload | |
438 | # dict, unpacks it and calls the underlying functions with the necessary |
|
451 | # dict, unpacks it and calls the underlying functions with the necessary | |
439 | # arguments. |
|
452 | # arguments. | |
440 |
|
453 | |||
441 | def _handle_payload_edit(self, item): |
|
454 | def _handle_payload_edit(self, item): | |
442 | self._edit(item['filename'], item['line_number']) |
|
455 | self._edit(item['filename'], item['line_number']) | |
443 |
|
456 | |||
444 | def _handle_payload_exit(self, item): |
|
457 | def _handle_payload_exit(self, item): | |
445 | self._keep_kernel_on_exit = item['keepkernel'] |
|
458 | self._keep_kernel_on_exit = item['keepkernel'] | |
446 | self.exit_requested.emit() |
|
459 | self.exit_requested.emit() | |
447 |
|
460 | |||
448 | def _handle_payload_loadpy(self, item): |
|
461 | def _handle_payload_loadpy(self, item): | |
449 | # Simple save the text of the .py file for later. The text is written |
|
462 | # Simple save the text of the .py file for later. The text is written | |
450 | # to the buffer when _prompt_started_hook is called. |
|
463 | # to the buffer when _prompt_started_hook is called. | |
451 | self._code_to_load = item['text'] |
|
464 | self._code_to_load = item['text'] | |
452 |
|
465 | |||
453 | def _handle_payload_page(self, item): |
|
466 | def _handle_payload_page(self, item): | |
454 | # Since the plain text widget supports only a very small subset of HTML |
|
467 | # Since the plain text widget supports only a very small subset of HTML | |
455 | # and we have no control over the HTML source, we only page HTML |
|
468 | # and we have no control over the HTML source, we only page HTML | |
456 | # payloads in the rich text widget. |
|
469 | # payloads in the rich text widget. | |
457 | if item['html'] and self.kind == 'rich': |
|
470 | if item['html'] and self.kind == 'rich': | |
458 | self._page(item['html'], html=True) |
|
471 | self._page(item['html'], html=True) | |
459 | else: |
|
472 | else: | |
460 | self._page(item['text'], html=False) |
|
473 | self._page(item['text'], html=False) | |
461 |
|
474 | |||
462 | #------ Trait change handlers -------------------------------------------- |
|
475 | #------ Trait change handlers -------------------------------------------- | |
463 |
|
476 | |||
464 | def _style_sheet_changed(self): |
|
477 | def _style_sheet_changed(self): | |
465 | """ Set the style sheets of the underlying widgets. |
|
478 | """ Set the style sheets of the underlying widgets. | |
466 | """ |
|
479 | """ | |
467 | self.setStyleSheet(self.style_sheet) |
|
480 | self.setStyleSheet(self.style_sheet) | |
468 | self._control.document().setDefaultStyleSheet(self.style_sheet) |
|
481 | self._control.document().setDefaultStyleSheet(self.style_sheet) | |
469 | if self._page_control: |
|
482 | if self._page_control: | |
470 | self._page_control.document().setDefaultStyleSheet(self.style_sheet) |
|
483 | self._page_control.document().setDefaultStyleSheet(self.style_sheet) | |
471 |
|
484 | |||
472 | bg_color = self._control.palette().background().color() |
|
485 | bg_color = self._control.palette().background().color() | |
473 | self._ansi_processor.set_background_color(bg_color) |
|
486 | self._ansi_processor.set_background_color(bg_color) | |
474 |
|
487 | |||
475 | def _syntax_style_changed(self): |
|
488 | def _syntax_style_changed(self): | |
476 | """ Set the style for the syntax highlighter. |
|
489 | """ Set the style for the syntax highlighter. | |
477 | """ |
|
490 | """ | |
478 | if self.syntax_style: |
|
491 | if self.syntax_style: | |
479 | self._highlighter.set_style(self.syntax_style) |
|
492 | self._highlighter.set_style(self.syntax_style) | |
480 | else: |
|
493 | else: | |
481 | self._highlighter.set_style_sheet(self.style_sheet) |
|
494 | self._highlighter.set_style_sheet(self.style_sheet) | |
482 |
|
495 |
@@ -1,226 +1,240 b'' | |||||
1 | # System library imports |
|
1 | # System library imports | |
2 | import os |
|
2 | import os | |
3 | import re |
|
3 | import re | |
4 | from PyQt4 import QtCore, QtGui |
|
4 | from PyQt4 import QtCore, QtGui | |
5 |
|
5 | |||
6 | # Local imports |
|
6 | # Local imports | |
7 | from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image |
|
7 | from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image | |
8 | from ipython_widget import IPythonWidget |
|
8 | from ipython_widget import IPythonWidget | |
9 |
|
9 | |||
10 |
|
10 | |||
11 | class RichIPythonWidget(IPythonWidget): |
|
11 | class RichIPythonWidget(IPythonWidget): | |
12 | """ An IPythonWidget that supports rich text, including lists, images, and |
|
12 | """ An IPythonWidget that supports rich text, including lists, images, and | |
13 | tables. Note that raw performance will be reduced compared to the plain |
|
13 | tables. Note that raw performance will be reduced compared to the plain | |
14 | text version. |
|
14 | text version. | |
15 | """ |
|
15 | """ | |
16 |
|
16 | |||
17 | # RichIPythonWidget protected class variables. |
|
17 | # RichIPythonWidget protected class variables. | |
18 | _payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload' |
|
18 | _payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload' | |
19 | _svg_text_format_property = 1 |
|
19 | _svg_text_format_property = 1 | |
20 |
|
20 | |||
21 | #--------------------------------------------------------------------------- |
|
21 | #--------------------------------------------------------------------------- | |
22 | # 'object' interface |
|
22 | # 'object' interface | |
23 | #--------------------------------------------------------------------------- |
|
23 | #--------------------------------------------------------------------------- | |
24 |
|
24 | |||
25 | def __init__(self, *args, **kw): |
|
25 | def __init__(self, *args, **kw): | |
26 | """ Create a RichIPythonWidget. |
|
26 | """ Create a RichIPythonWidget. | |
27 | """ |
|
27 | """ | |
28 | kw['kind'] = 'rich' |
|
28 | kw['kind'] = 'rich' | |
29 | super(RichIPythonWidget, self).__init__(*args, **kw) |
|
29 | super(RichIPythonWidget, self).__init__(*args, **kw) | |
30 | # Dictionary for resolving Qt names to images when |
|
30 | # Dictionary for resolving Qt names to images when | |
31 | # generating XHTML output |
|
31 | # generating XHTML output | |
32 | self._name_to_svg = {} |
|
32 | self._name_to_svg = {} | |
33 |
|
33 | |||
34 | #--------------------------------------------------------------------------- |
|
34 | #--------------------------------------------------------------------------- | |
35 | # 'ConsoleWidget' protected interface |
|
35 | # 'ConsoleWidget' protected interface | |
36 | #--------------------------------------------------------------------------- |
|
36 | #--------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 | def _context_menu_make(self, pos): |
|
38 | def _context_menu_make(self, pos): | |
39 | """ Reimplemented to return a custom context menu for images. |
|
39 | """ Reimplemented to return a custom context menu for images. | |
40 | """ |
|
40 | """ | |
41 | format = self._control.cursorForPosition(pos).charFormat() |
|
41 | format = self._control.cursorForPosition(pos).charFormat() | |
42 | name = format.stringProperty(QtGui.QTextFormat.ImageName) |
|
42 | name = format.stringProperty(QtGui.QTextFormat.ImageName) | |
43 | if name.isEmpty(): |
|
43 | if name.isEmpty(): | |
44 | menu = super(RichIPythonWidget, self)._context_menu_make(pos) |
|
44 | menu = super(RichIPythonWidget, self)._context_menu_make(pos) | |
45 | else: |
|
45 | else: | |
46 | menu = QtGui.QMenu() |
|
46 | menu = QtGui.QMenu() | |
47 |
|
47 | |||
48 | menu.addAction('Copy Image', lambda: self._copy_image(name)) |
|
48 | menu.addAction('Copy Image', lambda: self._copy_image(name)) | |
49 | menu.addAction('Save Image As...', lambda: self._save_image(name)) |
|
49 | menu.addAction('Save Image As...', lambda: self._save_image(name)) | |
50 | menu.addSeparator() |
|
50 | menu.addSeparator() | |
51 |
|
51 | |||
52 | svg = format.stringProperty(self._svg_text_format_property) |
|
52 | svg = format.stringProperty(self._svg_text_format_property) | |
53 | if not svg.isEmpty(): |
|
53 | if not svg.isEmpty(): | |
54 | menu.addSeparator() |
|
54 | menu.addSeparator() | |
55 | menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg)) |
|
55 | menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg)) | |
56 | menu.addAction('Save SVG As...', |
|
56 | menu.addAction('Save SVG As...', | |
57 | lambda: save_svg(svg, self._control)) |
|
57 | lambda: save_svg(svg, self._control)) | |
58 | return menu |
|
58 | return menu | |
59 |
|
59 | |||
60 | #--------------------------------------------------------------------------- |
|
60 | #--------------------------------------------------------------------------- | |
61 | # 'BaseFrontendMixin' abstract interface |
|
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 | def _handle_display_data(self, msg): |
|
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 | if not self._hidden and self._is_from_this_session(msg): |
|
84 | if not self._hidden and self._is_from_this_session(msg): | |
68 | source = msg['content']['source'] |
|
85 | source = msg['content']['source'] | |
69 | data = msg['content']['data'] |
|
86 | data = msg['content']['data'] | |
70 | metadata = msg['content']['metadata'] |
|
87 | metadata = msg['content']['metadata'] | |
71 | # Try to use the svg or html representations. |
|
88 | # Try to use the svg or html representations. | |
72 | # FIXME: Is this the right ordering of things to try? |
|
89 | # FIXME: Is this the right ordering of things to try? | |
73 | if data.has_key('image/svg+xml'): |
|
90 | if data.has_key('image/svg+xml'): | |
74 | svg = data['image/svg+xml'] |
|
91 | svg = data['image/svg+xml'] | |
75 | # TODO: try/except this call. |
|
92 | # TODO: try/except this call. | |
76 | self._append_svg(svg) |
|
93 | self._append_svg(svg) | |
77 | elif data.has_key('text/html'): |
|
|||
78 | html = data['text/html'] |
|
|||
79 | self._append_html(html) |
|
|||
80 | else: |
|
94 | else: | |
81 | # Default back to the plain text representation. |
|
95 | # Default back to the plain text representation. | |
82 | return super(RichIPythonWidget, self)._handle_display_data(msg) |
|
96 | return super(RichIPythonWidget, self)._handle_display_data(msg) | |
83 |
|
97 | |||
84 | #--------------------------------------------------------------------------- |
|
98 | #--------------------------------------------------------------------------- | |
85 | # 'FrontendWidget' protected interface |
|
99 | # 'FrontendWidget' protected interface | |
86 | #--------------------------------------------------------------------------- |
|
100 | #--------------------------------------------------------------------------- | |
87 |
|
101 | |||
88 | def _process_execute_payload(self, item): |
|
102 | def _process_execute_payload(self, item): | |
89 | """ Reimplemented to handle matplotlib plot payloads. |
|
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 | if item['source'] == self._payload_source_plot: |
|
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 | if item['format'] == 'svg': |
|
108 | if item['format'] == 'svg': | |
95 | svg = item['data'] |
|
109 | svg = item['data'] | |
96 | self._append_svg(svg) |
|
110 | self._append_svg(svg) | |
97 | return True |
|
111 | return True | |
98 | else: |
|
112 | else: | |
99 | # Add other plot formats here! |
|
113 | # Add other plot formats here! | |
100 | return False |
|
114 | return False | |
101 | else: |
|
115 | else: | |
102 | return super(RichIPythonWidget, self)._process_execute_payload(item) |
|
116 | return super(RichIPythonWidget, self)._process_execute_payload(item) | |
103 |
|
117 | |||
104 | #--------------------------------------------------------------------------- |
|
118 | #--------------------------------------------------------------------------- | |
105 | # 'RichIPythonWidget' protected interface |
|
119 | # 'RichIPythonWidget' protected interface | |
106 | #--------------------------------------------------------------------------- |
|
120 | #--------------------------------------------------------------------------- | |
107 |
|
121 | |||
108 | def _append_svg(self, svg): |
|
122 | def _append_svg(self, svg): | |
109 | """ Append raw svg data to the widget. |
|
123 | """ Append raw svg data to the widget. | |
110 | """ |
|
124 | """ | |
111 | try: |
|
125 | try: | |
112 | image = svg_to_image(svg) |
|
126 | image = svg_to_image(svg) | |
113 | except ValueError: |
|
127 | except ValueError: | |
114 | self._append_plain_text('Received invalid plot data.') |
|
128 | self._append_plain_text('Received invalid plot data.') | |
115 | else: |
|
129 | else: | |
116 | format = self._add_image(image) |
|
130 | format = self._add_image(image) | |
117 | self._name_to_svg[str(format.name())] = svg |
|
131 | self._name_to_svg[str(format.name())] = svg | |
118 | format.setProperty(self._svg_text_format_property, svg) |
|
132 | format.setProperty(self._svg_text_format_property, svg) | |
119 | cursor = self._get_end_cursor() |
|
133 | cursor = self._get_end_cursor() | |
120 | cursor.insertBlock() |
|
134 | cursor.insertBlock() | |
121 | cursor.insertImage(format) |
|
135 | cursor.insertImage(format) | |
122 | cursor.insertBlock() |
|
136 | cursor.insertBlock() | |
123 |
|
137 | |||
124 | def _add_image(self, image): |
|
138 | def _add_image(self, image): | |
125 | """ Adds the specified QImage to the document and returns a |
|
139 | """ Adds the specified QImage to the document and returns a | |
126 | QTextImageFormat that references it. |
|
140 | QTextImageFormat that references it. | |
127 | """ |
|
141 | """ | |
128 | document = self._control.document() |
|
142 | document = self._control.document() | |
129 | name = QtCore.QString.number(image.cacheKey()) |
|
143 | name = QtCore.QString.number(image.cacheKey()) | |
130 | document.addResource(QtGui.QTextDocument.ImageResource, |
|
144 | document.addResource(QtGui.QTextDocument.ImageResource, | |
131 | QtCore.QUrl(name), image) |
|
145 | QtCore.QUrl(name), image) | |
132 | format = QtGui.QTextImageFormat() |
|
146 | format = QtGui.QTextImageFormat() | |
133 | format.setName(name) |
|
147 | format.setName(name) | |
134 | return format |
|
148 | return format | |
135 |
|
149 | |||
136 | def _copy_image(self, name): |
|
150 | def _copy_image(self, name): | |
137 | """ Copies the ImageResource with 'name' to the clipboard. |
|
151 | """ Copies the ImageResource with 'name' to the clipboard. | |
138 | """ |
|
152 | """ | |
139 | image = self._get_image(name) |
|
153 | image = self._get_image(name) | |
140 | QtGui.QApplication.clipboard().setImage(image) |
|
154 | QtGui.QApplication.clipboard().setImage(image) | |
141 |
|
155 | |||
142 | def _get_image(self, name): |
|
156 | def _get_image(self, name): | |
143 | """ Returns the QImage stored as the ImageResource with 'name'. |
|
157 | """ Returns the QImage stored as the ImageResource with 'name'. | |
144 | """ |
|
158 | """ | |
145 | document = self._control.document() |
|
159 | document = self._control.document() | |
146 | variant = document.resource(QtGui.QTextDocument.ImageResource, |
|
160 | variant = document.resource(QtGui.QTextDocument.ImageResource, | |
147 | QtCore.QUrl(name)) |
|
161 | QtCore.QUrl(name)) | |
148 | return variant.toPyObject() |
|
162 | return variant.toPyObject() | |
149 |
|
163 | |||
150 | def _save_image(self, name, format='PNG'): |
|
164 | def _save_image(self, name, format='PNG'): | |
151 | """ Shows a save dialog for the ImageResource with 'name'. |
|
165 | """ Shows a save dialog for the ImageResource with 'name'. | |
152 | """ |
|
166 | """ | |
153 | dialog = QtGui.QFileDialog(self._control, 'Save Image') |
|
167 | dialog = QtGui.QFileDialog(self._control, 'Save Image') | |
154 | dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) |
|
168 | dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) | |
155 | dialog.setDefaultSuffix(format.lower()) |
|
169 | dialog.setDefaultSuffix(format.lower()) | |
156 | dialog.setNameFilter('%s file (*.%s)' % (format, format.lower())) |
|
170 | dialog.setNameFilter('%s file (*.%s)' % (format, format.lower())) | |
157 | if dialog.exec_(): |
|
171 | if dialog.exec_(): | |
158 | filename = dialog.selectedFiles()[0] |
|
172 | filename = dialog.selectedFiles()[0] | |
159 | image = self._get_image(name) |
|
173 | image = self._get_image(name) | |
160 | image.save(filename, format) |
|
174 | image.save(filename, format) | |
161 |
|
175 | |||
162 | def image_tag(self, match, path = None, format = "png"): |
|
176 | def image_tag(self, match, path = None, format = "png"): | |
163 | """ Return (X)HTML mark-up for the image-tag given by match. |
|
177 | """ Return (X)HTML mark-up for the image-tag given by match. | |
164 |
|
178 | |||
165 | Parameters |
|
179 | Parameters | |
166 | ---------- |
|
180 | ---------- | |
167 | match : re.SRE_Match |
|
181 | match : re.SRE_Match | |
168 | A match to an HTML image tag as exported by Qt, with |
|
182 | A match to an HTML image tag as exported by Qt, with | |
169 | match.group("Name") containing the matched image ID. |
|
183 | match.group("Name") containing the matched image ID. | |
170 |
|
184 | |||
171 | path : string|None, optional [default None] |
|
185 | path : string|None, optional [default None] | |
172 | If not None, specifies a path to which supporting files |
|
186 | If not None, specifies a path to which supporting files | |
173 | may be written (e.g., for linked images). |
|
187 | may be written (e.g., for linked images). | |
174 | If None, all images are to be included inline. |
|
188 | If None, all images are to be included inline. | |
175 |
|
189 | |||
176 | format : "png"|"svg", optional [default "png"] |
|
190 | format : "png"|"svg", optional [default "png"] | |
177 | Format for returned or referenced images. |
|
191 | Format for returned or referenced images. | |
178 |
|
192 | |||
179 | Subclasses supporting image display should override this |
|
193 | Subclasses supporting image display should override this | |
180 | method. |
|
194 | method. | |
181 | """ |
|
195 | """ | |
182 |
|
196 | |||
183 | if(format == "png"): |
|
197 | if(format == "png"): | |
184 | try: |
|
198 | try: | |
185 | image = self._get_image(match.group("name")) |
|
199 | image = self._get_image(match.group("name")) | |
186 | except KeyError: |
|
200 | except KeyError: | |
187 | return "<b>Couldn't find image %s</b>" % match.group("name") |
|
201 | return "<b>Couldn't find image %s</b>" % match.group("name") | |
188 |
|
202 | |||
189 | if(path is not None): |
|
203 | if(path is not None): | |
190 | if not os.path.exists(path): |
|
204 | if not os.path.exists(path): | |
191 | os.mkdir(path) |
|
205 | os.mkdir(path) | |
192 | relpath = os.path.basename(path) |
|
206 | relpath = os.path.basename(path) | |
193 | if(image.save("%s/qt_img%s.png" % (path,match.group("name")), |
|
207 | if(image.save("%s/qt_img%s.png" % (path,match.group("name")), | |
194 | "PNG")): |
|
208 | "PNG")): | |
195 | return '<img src="%s/qt_img%s.png">' % (relpath, |
|
209 | return '<img src="%s/qt_img%s.png">' % (relpath, | |
196 | match.group("name")) |
|
210 | match.group("name")) | |
197 | else: |
|
211 | else: | |
198 | return "<b>Couldn't save image!</b>" |
|
212 | return "<b>Couldn't save image!</b>" | |
199 | else: |
|
213 | else: | |
200 | ba = QtCore.QByteArray() |
|
214 | ba = QtCore.QByteArray() | |
201 | buffer_ = QtCore.QBuffer(ba) |
|
215 | buffer_ = QtCore.QBuffer(ba) | |
202 | buffer_.open(QtCore.QIODevice.WriteOnly) |
|
216 | buffer_.open(QtCore.QIODevice.WriteOnly) | |
203 | image.save(buffer_, "PNG") |
|
217 | image.save(buffer_, "PNG") | |
204 | buffer_.close() |
|
218 | buffer_.close() | |
205 | return '<img src="data:image/png;base64,\n%s\n" />' % ( |
|
219 | return '<img src="data:image/png;base64,\n%s\n" />' % ( | |
206 | re.sub(r'(.{60})',r'\1\n',str(ba.toBase64()))) |
|
220 | re.sub(r'(.{60})',r'\1\n',str(ba.toBase64()))) | |
207 |
|
221 | |||
208 | elif(format == "svg"): |
|
222 | elif(format == "svg"): | |
209 | try: |
|
223 | try: | |
210 | svg = str(self._name_to_svg[match.group("name")]) |
|
224 | svg = str(self._name_to_svg[match.group("name")]) | |
211 | except KeyError: |
|
225 | except KeyError: | |
212 | return "<b>Couldn't find image %s</b>" % match.group("name") |
|
226 | return "<b>Couldn't find image %s</b>" % match.group("name") | |
213 |
|
227 | |||
214 | # Not currently checking path, because it's tricky to find a |
|
228 | # Not currently checking path, because it's tricky to find a | |
215 | # cross-browser way to embed external SVG images (e.g., via |
|
229 | # cross-browser way to embed external SVG images (e.g., via | |
216 | # object or embed tags). |
|
230 | # object or embed tags). | |
217 |
|
231 | |||
218 | # Chop stand-alone header from matplotlib SVG |
|
232 | # Chop stand-alone header from matplotlib SVG | |
219 | offset = svg.find("<svg") |
|
233 | offset = svg.find("<svg") | |
220 | assert(offset > -1) |
|
234 | assert(offset > -1) | |
221 |
|
235 | |||
222 | return svg[offset:] |
|
236 | return svg[offset:] | |
223 |
|
237 | |||
224 | else: |
|
238 | else: | |
225 | return '<b>Unrecognized image format</b>' |
|
239 | return '<b>Unrecognized image format</b>' | |
226 |
|
240 |
@@ -1,110 +1,110 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 |
|
3 | |||
4 | """This module contains blocking clients for the controller interfaces. |
|
4 | """This module contains blocking clients for the controller interfaces. | |
5 |
|
5 | |||
6 | Unlike the clients in `asyncclient.py`, the clients in this module are fully |
|
6 | Unlike the clients in `asyncclient.py`, the clients in this module are fully | |
7 | blocking. This means that methods on the clients return the actual results |
|
7 | blocking. This means that methods on the clients return the actual results | |
8 | rather than a deferred to the result. Also, we manage the Twisted reactor |
|
8 | rather than a deferred to the result. Also, we manage the Twisted reactor | |
9 | for you. This is done by running the reactor in a thread. |
|
9 | for you. This is done by running the reactor in a thread. | |
10 |
|
10 | |||
11 | The main classes in this module are: |
|
11 | The main classes in this module are: | |
12 |
|
12 | |||
13 | * MultiEngineClient |
|
13 | * MultiEngineClient | |
14 | * TaskClient |
|
14 | * TaskClient | |
15 | * Task |
|
15 | * Task | |
16 | * CompositeError |
|
16 | * CompositeError | |
17 | """ |
|
17 | """ | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Copyright (C) 2008-2009 The IPython Development Team |
|
20 | # Copyright (C) 2008-2009 The IPython Development Team | |
21 | # |
|
21 | # | |
22 | # Distributed under the terms of the BSD License. The full license is in |
|
22 | # Distributed under the terms of the BSD License. The full license is in | |
23 | # the file COPYING, distributed as part of this software. |
|
23 | # the file COPYING, distributed as part of this software. | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 | # Warnings control |
|
27 | # Warnings control | |
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 |
|
29 | |||
30 | import warnings |
|
30 | import warnings | |
31 |
|
31 | |||
32 | # Twisted generates annoying warnings with Python 2.6, as will do other code |
|
32 | # Twisted generates annoying warnings with Python 2.6, as will do other code | |
33 | # that imports 'sets' as of today |
|
33 | # that imports 'sets' as of today | |
34 | warnings.filterwarnings('ignore', 'the sets module is deprecated', |
|
34 | warnings.filterwarnings('ignore', 'the sets module is deprecated', | |
35 | DeprecationWarning ) |
|
35 | DeprecationWarning ) | |
36 |
|
36 | |||
37 | # This one also comes from Twisted |
|
37 | # This one also comes from Twisted | |
38 | warnings.filterwarnings('ignore', 'the sha module is deprecated', |
|
38 | warnings.filterwarnings('ignore', 'the sha module is deprecated', | |
39 | DeprecationWarning) |
|
39 | DeprecationWarning) | |
40 |
|
40 | |||
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 | # Imports |
|
42 | # Imports | |
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 |
|
44 | |||
45 | import sys |
|
45 | import sys | |
46 |
|
46 | |||
47 | import twisted |
|
47 | import twisted | |
48 | from twisted.internet import reactor |
|
48 | from twisted.internet import reactor | |
49 | from twisted.python import log |
|
49 | from twisted.python import log | |
50 |
|
50 | |||
51 | from IPython.kernel.clientconnector import ClientConnector, Cluster |
|
51 | from IPython.kernel.clientconnector import ClientConnector, Cluster | |
52 | from IPython.kernel.twistedutil import ReactorInThread |
|
52 | from IPython.kernel.twistedutil import ReactorInThread | |
53 | from IPython.kernel.twistedutil import blockingCallFromThread |
|
53 | from IPython.kernel.twistedutil import blockingCallFromThread | |
54 |
|
54 | |||
55 | # These enable various things |
|
55 | # These enable various things | |
56 | from IPython.kernel import codeutil |
|
56 | from IPython.kernel import codeutil | |
57 |
|
57 | |||
58 | # Other things that the user will need |
|
58 | # Other things that the user will need | |
59 | from IPython.kernel.task import MapTask, StringTask |
|
59 | from IPython.kernel.task import MapTask, StringTask | |
60 | from IPython.kernel.error import CompositeError |
|
60 | from IPython.kernel.error import CompositeError | |
61 |
|
61 | |||
62 | #------------------------------------------------------------------------------- |
|
62 | #------------------------------------------------------------------------------- | |
63 | # Code |
|
63 | # Code | |
64 | #------------------------------------------------------------------------------- |
|
64 | #------------------------------------------------------------------------------- | |
65 |
|
65 | |||
66 | # PotentialZombieWarning is deprecated from Twisted 10.0.0 and above and |
|
66 | # PotentialZombieWarning is deprecated from Twisted 10.0.0 and above and | |
67 | # using the filter on > 10.0.0 creates a warning itself. |
|
67 | # using the filter on > 10.0.0 creates a warning itself. | |
68 | if twisted.version.major < 10: |
|
68 | if twisted.version.major < 10: | |
69 | from twisted.internet.error import PotentialZombieWarning |
|
69 | from twisted.internet.error import PotentialZombieWarning | |
70 | warnings.simplefilter('ignore', PotentialZombieWarning) |
|
70 | warnings.simplefilter('ignore', PotentialZombieWarning) | |
71 |
|
71 | |||
72 | _client_tub = ClientConnector() |
|
72 | _client_tub = ClientConnector() | |
73 |
|
73 | |||
74 | get_multiengine_client = _client_tub.get_multiengine_client |
|
74 | get_multiengine_client = _client_tub.get_multiengine_client | |
75 | get_task_client = _client_tub.get_task_client |
|
75 | get_task_client = _client_tub.get_task_client | |
76 | MultiEngineClient = get_multiengine_client |
|
76 | MultiEngineClient = get_multiengine_client | |
77 | TaskClient = get_task_client |
|
77 | TaskClient = get_task_client | |
78 |
|
78 | |||
79 | # This isn't great. I should probably set this up in the ReactorInThread |
|
79 | # This isn't great. I should probably set this up in the ReactorInThread | |
80 | # class below. But, it does work for now. |
|
80 | # class below. But, it does work for now. | |
81 | log.startLogging(sys.stdout, setStdout=0) |
|
81 | log.startLogging(sys.stdout, setStdout=0) | |
82 |
|
82 | |||
83 | def _result_list_printer(obj, p, cycle): |
|
83 | def _result_list_printer(obj, p, cycle): | |
84 | if cycle: |
|
84 | if cycle: | |
85 | return p.text('ResultList(...)') |
|
85 | return p.text('ResultList(...)') | |
86 | return p.text(repr(obj)) |
|
86 | return p.text(repr(obj)) | |
87 |
|
87 | |||
88 | # ResultList is a list subclass and will use the default pretty printer. |
|
88 | # ResultList is a list subclass and will use the default pretty printer. | |
89 | # This overrides that to use the __repr__ of ResultList. |
|
89 | # This overrides that to use the __repr__ of ResultList. | |
90 | ip = get_ipython() |
|
90 | ip = get_ipython() | |
91 |
ip.display |
|
91 | ip.display_formatter.formatters['text/plain'].for_type_by_name( | |
92 | 'IPython.kernel.multiengineclient', 'ResultList', _result_list_printer |
|
92 | 'IPython.kernel.multiengineclient', 'ResultList', _result_list_printer | |
93 | ) |
|
93 | ) | |
94 |
|
94 | |||
95 | # Now we start the reactor in a thread |
|
95 | # Now we start the reactor in a thread | |
96 | rit = ReactorInThread() |
|
96 | rit = ReactorInThread() | |
97 | rit.setDaemon(True) |
|
97 | rit.setDaemon(True) | |
98 | rit.start() |
|
98 | rit.start() | |
99 |
|
99 | |||
100 |
|
100 | |||
101 | __all__ = [ |
|
101 | __all__ = [ | |
102 | 'MapTask', |
|
102 | 'MapTask', | |
103 | 'StringTask', |
|
103 | 'StringTask', | |
104 | 'MultiEngineClient', |
|
104 | 'MultiEngineClient', | |
105 | 'TaskClient', |
|
105 | 'TaskClient', | |
106 | 'CompositeError', |
|
106 | 'CompositeError', | |
107 | 'get_task_client', |
|
107 | 'get_task_client', | |
108 | 'get_multiengine_client', |
|
108 | 'get_multiengine_client', | |
109 | 'Cluster' |
|
109 | 'Cluster' | |
110 | ] |
|
110 | ] |
@@ -1,123 +1,123 b'' | |||||
1 | """Produce SVG versions of active plots for display by the rich Qt frontend. |
|
1 | """Produce SVG versions of active plots for display by the rich Qt frontend. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Imports |
|
4 | # Imports | |
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | from __future__ import print_function |
|
6 | from __future__ import print_function | |
7 |
|
7 | |||
8 | # Standard library imports |
|
8 | # Standard library imports | |
9 | from cStringIO import StringIO |
|
9 | from cStringIO import StringIO | |
10 |
|
10 | |||
11 | # System library imports. |
|
11 | # System library imports. | |
12 | import matplotlib |
|
12 | import matplotlib | |
13 | from matplotlib.backends.backend_svg import new_figure_manager |
|
13 | from matplotlib.backends.backend_svg import new_figure_manager | |
14 | from matplotlib._pylab_helpers import Gcf |
|
14 | from matplotlib._pylab_helpers import Gcf | |
15 |
|
15 | |||
16 | # Local imports. |
|
16 | # Local imports. | |
17 | from IPython.core.displaypub import publish_display_data |
|
17 | from IPython.core.displaypub import publish_display_data | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Functions |
|
20 | # Functions | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | def show(close=True): |
|
23 | def show(close=True): | |
24 | """Show all figures as SVG payloads sent to the IPython clients. |
|
24 | """Show all figures as SVG payloads sent to the IPython clients. | |
25 |
|
25 | |||
26 | Parameters |
|
26 | Parameters | |
27 | ---------- |
|
27 | ---------- | |
28 | close : bool, optional |
|
28 | close : bool, optional | |
29 | If true, a ``plt.close('all')`` call is automatically issued after |
|
29 | If true, a ``plt.close('all')`` call is automatically issued after | |
30 | sending all the SVG figures. |
|
30 | sending all the SVG figures. | |
31 | """ |
|
31 | """ | |
32 | for figure_manager in Gcf.get_all_fig_managers(): |
|
32 | for figure_manager in Gcf.get_all_fig_managers(): | |
33 | send_svg_canvas(figure_manager.canvas) |
|
33 | send_svg_canvas(figure_manager.canvas) | |
34 | if close: |
|
34 | if close: | |
35 | matplotlib.pyplot.close('all') |
|
35 | matplotlib.pyplot.close('all') | |
36 |
|
36 | |||
37 | # This flag will be reset by draw_if_interactive when called |
|
37 | # This flag will be reset by draw_if_interactive when called | |
38 | show._draw_called = False |
|
38 | show._draw_called = False | |
39 |
|
39 | |||
40 |
|
40 | |||
41 | def figsize(sizex, sizey): |
|
41 | def figsize(sizex, sizey): | |
42 | """Set the default figure size to be [sizex, sizey]. |
|
42 | """Set the default figure size to be [sizex, sizey]. | |
43 |
|
43 | |||
44 | This is just an easy to remember, convenience wrapper that sets:: |
|
44 | This is just an easy to remember, convenience wrapper that sets:: | |
45 |
|
45 | |||
46 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
|
46 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] | |
47 | """ |
|
47 | """ | |
48 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
|
48 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] | |
49 |
|
49 | |||
50 |
|
50 | |||
51 | def pastefig(*figs): |
|
51 | def pastefig(*figs): | |
52 | """Paste one or more figures into the console workspace. |
|
52 | """Paste one or more figures into the console workspace. | |
53 |
|
53 | |||
54 | If no arguments are given, all available figures are pasted. If the |
|
54 | If no arguments are given, all available figures are pasted. If the | |
55 | argument list contains references to invalid figures, a warning is printed |
|
55 | argument list contains references to invalid figures, a warning is printed | |
56 | but the function continues pasting further figures. |
|
56 | but the function continues pasting further figures. | |
57 |
|
57 | |||
58 | Parameters |
|
58 | Parameters | |
59 | ---------- |
|
59 | ---------- | |
60 | figs : tuple |
|
60 | figs : tuple | |
61 | A tuple that can contain any mixture of integers and figure objects. |
|
61 | A tuple that can contain any mixture of integers and figure objects. | |
62 | """ |
|
62 | """ | |
63 | if not figs: |
|
63 | if not figs: | |
64 | show(close=False) |
|
64 | show(close=False) | |
65 | else: |
|
65 | else: | |
66 | fig_managers = Gcf.get_all_fig_managers() |
|
66 | fig_managers = Gcf.get_all_fig_managers() | |
67 | fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers] |
|
67 | fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers] | |
68 | + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] ) |
|
68 | + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] ) | |
69 |
|
69 | |||
70 | for fig in figs: |
|
70 | for fig in figs: | |
71 | canvas = fig_index.get(fig) |
|
71 | canvas = fig_index.get(fig) | |
72 | if canvas is None: |
|
72 | if canvas is None: | |
73 | print('Warning: figure %s not available.' % fig) |
|
73 | print('Warning: figure %s not available.' % fig) | |
74 | else: |
|
74 | else: | |
75 | send_svg_canvas(canvas) |
|
75 | send_svg_canvas(canvas) | |
76 |
|
76 | |||
77 |
|
77 | |||
78 | def send_svg_canvas(canvas): |
|
78 | def send_svg_canvas(canvas): | |
79 | """Draw the current canvas and send it as an SVG payload. |
|
79 | """Draw the current canvas and send it as an SVG payload. | |
80 | """ |
|
80 | """ | |
81 | # Set the background to white instead so it looks good on black. We store |
|
81 | # Set the background to white instead so it looks good on black. We store | |
82 | # the current values to restore them at the end. |
|
82 | # the current values to restore them at the end. | |
83 | fc = canvas.figure.get_facecolor() |
|
83 | fc = canvas.figure.get_facecolor() | |
84 | ec = canvas.figure.get_edgecolor() |
|
84 | ec = canvas.figure.get_edgecolor() | |
85 | canvas.figure.set_facecolor('white') |
|
85 | canvas.figure.set_facecolor('white') | |
86 | canvas.figure.set_edgecolor('white') |
|
86 | canvas.figure.set_edgecolor('white') | |
87 | try: |
|
87 | try: | |
88 | publish_display_data( |
|
88 | publish_display_data( | |
89 | 'IPython.zmq.pylab.backend_inline.send_svg_canvas', |
|
89 | 'IPython.zmq.pylab.backend_inline.send_svg_canvas', | |
90 |
' |
|
90 | 'Matplotlib Plot', | |
91 |
|
|
91 | {'image/svg+xml' : svg_from_canvas(canvas)} | |
92 | ) |
|
92 | ) | |
93 | finally: |
|
93 | finally: | |
94 | canvas.figure.set_facecolor(fc) |
|
94 | canvas.figure.set_facecolor(fc) | |
95 | canvas.figure.set_edgecolor(ec) |
|
95 | canvas.figure.set_edgecolor(ec) | |
96 |
|
96 | |||
97 |
|
97 | |||
98 | def svg_from_canvas(canvas): |
|
98 | def svg_from_canvas(canvas): | |
99 | """ Return a string containing the SVG representation of a FigureCanvasSvg. |
|
99 | """ Return a string containing the SVG representation of a FigureCanvasSvg. | |
100 | """ |
|
100 | """ | |
101 | string_io = StringIO() |
|
101 | string_io = StringIO() | |
102 | canvas.print_figure(string_io, format='svg') |
|
102 | canvas.print_figure(string_io, format='svg') | |
103 | return string_io.getvalue() |
|
103 | return string_io.getvalue() | |
104 |
|
104 | |||
105 |
|
105 | |||
106 | def draw_if_interactive(): |
|
106 | def draw_if_interactive(): | |
107 | """ |
|
107 | """ | |
108 | Is called after every pylab drawing command |
|
108 | Is called after every pylab drawing command | |
109 | """ |
|
109 | """ | |
110 | # We simply flag we were called and otherwise do nothing. At the end of |
|
110 | # We simply flag we were called and otherwise do nothing. At the end of | |
111 | # the code execution, a separate call to show_close() will act upon this. |
|
111 | # the code execution, a separate call to show_close() will act upon this. | |
112 | show._draw_called = True |
|
112 | show._draw_called = True | |
113 |
|
113 | |||
114 |
|
114 | |||
115 | def flush_svg(): |
|
115 | def flush_svg(): | |
116 | """Call show, close all open figures, sending all SVG images. |
|
116 | """Call show, close all open figures, sending all SVG images. | |
117 |
|
117 | |||
118 | This is meant to be called automatically and will call show() if, during |
|
118 | This is meant to be called automatically and will call show() if, during | |
119 | prior code execution, there had been any calls to draw_if_interactive. |
|
119 | prior code execution, there had been any calls to draw_if_interactive. | |
120 | """ |
|
120 | """ | |
121 | if show._draw_called: |
|
121 | if show._draw_called: | |
122 | show(close=True) |
|
122 | show(close=True) | |
123 | show._draw_called = False |
|
123 | show._draw_called = False |
@@ -1,605 +1,605 b'' | |||||
1 | """A ZMQ-based subclass of InteractiveShell. |
|
1 | """A ZMQ-based subclass of InteractiveShell. | |
2 |
|
2 | |||
3 | This code is meant to ease the refactoring of the base InteractiveShell into |
|
3 | This code is meant to ease the refactoring of the base InteractiveShell into | |
4 | something with a cleaner architecture for 2-process use, without actually |
|
4 | something with a cleaner architecture for 2-process use, without actually | |
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where |
|
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where | |
6 | we subclass and override what we want to fix. Once this is working well, we |
|
6 | we subclass and override what we want to fix. Once this is working well, we | |
7 | can go back to the base class and refactor the code for a cleaner inheritance |
|
7 | can go back to the base class and refactor the code for a cleaner inheritance | |
8 | implementation that doesn't rely on so much monkeypatching. |
|
8 | implementation that doesn't rely on so much monkeypatching. | |
9 |
|
9 | |||
10 | But this lets us maintain a fully working IPython as we develop the new |
|
10 | But this lets us maintain a fully working IPython as we develop the new | |
11 | machinery. This should thus be thought of as scaffolding. |
|
11 | machinery. This should thus be thought of as scaffolding. | |
12 | """ |
|
12 | """ | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Stdlib |
|
18 | # Stdlib | |
19 | import inspect |
|
19 | import inspect | |
20 | import os |
|
20 | import os | |
21 | import re |
|
21 | import re | |
22 |
|
22 | |||
23 | # Our own |
|
23 | # Our own | |
24 | from IPython.core.interactiveshell import ( |
|
24 | from IPython.core.interactiveshell import ( | |
25 | InteractiveShell, InteractiveShellABC |
|
25 | InteractiveShell, InteractiveShellABC | |
26 | ) |
|
26 | ) | |
27 | from IPython.core import page |
|
27 | from IPython.core import page | |
28 | from IPython.core.displayhook import DisplayHook |
|
28 | from IPython.core.displayhook import DisplayHook | |
29 | from IPython.core.displaypub import DisplayPublisher |
|
29 | from IPython.core.displaypub import DisplayPublisher | |
30 | from IPython.core.macro import Macro |
|
30 | from IPython.core.macro import Macro | |
31 | from IPython.core.payloadpage import install_payload_page |
|
31 | from IPython.core.payloadpage import install_payload_page | |
32 | from IPython.utils import io |
|
32 | from IPython.utils import io | |
33 | from IPython.utils.path import get_py_filename |
|
33 | from IPython.utils.path import get_py_filename | |
34 | from IPython.utils.text import StringTypes |
|
34 | from IPython.utils.text import StringTypes | |
35 | from IPython.utils.traitlets import Instance, Type, Dict |
|
35 | from IPython.utils.traitlets import Instance, Type, Dict | |
36 | from IPython.utils.warn import warn |
|
36 | from IPython.utils.warn import warn | |
37 | from IPython.zmq.session import extract_header |
|
37 | from IPython.zmq.session import extract_header | |
38 | from session import Session |
|
38 | from session import Session | |
39 |
|
39 | |||
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 | # Globals and side-effects |
|
41 | # Globals and side-effects | |
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 |
|
43 | |||
44 | # Install the payload version of page. |
|
44 | # Install the payload version of page. | |
45 | install_payload_page() |
|
45 | install_payload_page() | |
46 |
|
46 | |||
47 | #----------------------------------------------------------------------------- |
|
47 | #----------------------------------------------------------------------------- | |
48 | # Functions and classes |
|
48 | # Functions and classes | |
49 | #----------------------------------------------------------------------------- |
|
49 | #----------------------------------------------------------------------------- | |
50 |
|
50 | |||
51 | class ZMQDisplayHook(DisplayHook): |
|
51 | class ZMQDisplayHook(DisplayHook): | |
|
52 | """A displayhook subclass that publishes data using ZeroMQ.""" | |||
52 |
|
53 | |||
53 | session = Instance(Session) |
|
54 | session = Instance(Session) | |
54 | pub_socket = Instance('zmq.Socket') |
|
55 | pub_socket = Instance('zmq.Socket') | |
55 | parent_header = Dict({}) |
|
56 | parent_header = Dict({}) | |
56 |
|
57 | |||
57 | def set_parent(self, parent): |
|
58 | def set_parent(self, parent): | |
58 | """Set the parent for outbound messages.""" |
|
59 | """Set the parent for outbound messages.""" | |
59 | self.parent_header = extract_header(parent) |
|
60 | self.parent_header = extract_header(parent) | |
60 |
|
61 | |||
61 | def start_displayhook(self): |
|
62 | def start_displayhook(self): | |
62 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) |
|
63 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) | |
63 |
|
64 | |||
64 | def write_output_prompt(self): |
|
65 | def write_output_prompt(self): | |
65 | """Write the output prompt.""" |
|
66 | """Write the output prompt.""" | |
66 | if self.do_full_cache: |
|
67 | if self.do_full_cache: | |
67 | self.msg['content']['execution_count'] = self.prompt_count |
|
68 | self.msg['content']['execution_count'] = self.prompt_count | |
68 |
|
69 | |||
69 |
def write_ |
|
70 | def write_format_data(self, format_dict): | |
70 |
self.msg['content']['data'] = |
|
71 | self.msg['content']['data'] = format_dict | |
71 | self.msg['content']['extra_formats'] = extra_formats |
|
|||
72 |
|
72 | |||
73 | def finish_displayhook(self): |
|
73 | def finish_displayhook(self): | |
74 | """Finish up all displayhook activities.""" |
|
74 | """Finish up all displayhook activities.""" | |
75 | self.session.send(self.pub_socket, self.msg) |
|
75 | self.session.send(self.pub_socket, self.msg) | |
76 | self.msg = None |
|
76 | self.msg = None | |
77 |
|
77 | |||
78 |
|
78 | |||
79 | class ZMQDisplayPublisher(DisplayPublisher): |
|
79 | class ZMQDisplayPublisher(DisplayPublisher): | |
80 |
"""A |
|
80 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" | |
81 |
|
81 | |||
82 | session = Instance(Session) |
|
82 | session = Instance(Session) | |
83 | pub_socket = Instance('zmq.Socket') |
|
83 | pub_socket = Instance('zmq.Socket') | |
84 | parent_header = Dict({}) |
|
84 | parent_header = Dict({}) | |
85 |
|
85 | |||
86 | def set_parent(self, parent): |
|
86 | def set_parent(self, parent): | |
87 | """Set the parent for outbound messages.""" |
|
87 | """Set the parent for outbound messages.""" | |
88 | self.parent_header = extract_header(parent) |
|
88 | self.parent_header = extract_header(parent) | |
89 |
|
89 | |||
90 | def publish(self, source, data, metadata=None): |
|
90 | def publish(self, source, data, metadata=None): | |
91 | if metadata is None: |
|
91 | if metadata is None: | |
92 | metadata = {} |
|
92 | metadata = {} | |
93 | self._validate_data(source, data, metadata) |
|
93 | self._validate_data(source, data, metadata) | |
94 | msg = self.session.msg(u'display_data', {}, parent=self.parent_header) |
|
94 | msg = self.session.msg(u'display_data', {}, parent=self.parent_header) | |
95 | msg['content']['source'] = source |
|
95 | msg['content']['source'] = source | |
96 | msg['content']['data'] = data |
|
96 | msg['content']['data'] = data | |
97 | msg['content']['metadata'] = metadata |
|
97 | msg['content']['metadata'] = metadata | |
98 | self.pub_socket.send_json(msg) |
|
98 | self.pub_socket.send_json(msg) | |
99 |
|
99 | |||
100 |
|
100 | |||
101 | class ZMQInteractiveShell(InteractiveShell): |
|
101 | class ZMQInteractiveShell(InteractiveShell): | |
102 | """A subclass of InteractiveShell for ZMQ.""" |
|
102 | """A subclass of InteractiveShell for ZMQ.""" | |
103 |
|
103 | |||
104 | displayhook_class = Type(ZMQDisplayHook) |
|
104 | displayhook_class = Type(ZMQDisplayHook) | |
105 | display_pub_class = Type(ZMQDisplayPublisher) |
|
105 | display_pub_class = Type(ZMQDisplayPublisher) | |
106 |
|
106 | |||
107 | keepkernel_on_exit = None |
|
107 | keepkernel_on_exit = None | |
108 |
|
108 | |||
109 | def init_environment(self): |
|
109 | def init_environment(self): | |
110 | """Configure the user's environment. |
|
110 | """Configure the user's environment. | |
111 |
|
111 | |||
112 | """ |
|
112 | """ | |
113 | env = os.environ |
|
113 | env = os.environ | |
114 | # These two ensure 'ls' produces nice coloring on BSD-derived systems |
|
114 | # These two ensure 'ls' produces nice coloring on BSD-derived systems | |
115 | env['TERM'] = 'xterm-color' |
|
115 | env['TERM'] = 'xterm-color' | |
116 | env['CLICOLOR'] = '1' |
|
116 | env['CLICOLOR'] = '1' | |
117 | # Since normal pagers don't work at all (over pexpect we don't have |
|
117 | # Since normal pagers don't work at all (over pexpect we don't have | |
118 | # single-key control of the subprocess), try to disable paging in |
|
118 | # single-key control of the subprocess), try to disable paging in | |
119 | # subprocesses as much as possible. |
|
119 | # subprocesses as much as possible. | |
120 | env['PAGER'] = 'cat' |
|
120 | env['PAGER'] = 'cat' | |
121 | env['GIT_PAGER'] = 'cat' |
|
121 | env['GIT_PAGER'] = 'cat' | |
122 |
|
122 | |||
123 | def auto_rewrite_input(self, cmd): |
|
123 | def auto_rewrite_input(self, cmd): | |
124 | """Called to show the auto-rewritten input for autocall and friends. |
|
124 | """Called to show the auto-rewritten input for autocall and friends. | |
125 |
|
125 | |||
126 | FIXME: this payload is currently not correctly processed by the |
|
126 | FIXME: this payload is currently not correctly processed by the | |
127 | frontend. |
|
127 | frontend. | |
128 | """ |
|
128 | """ | |
129 | new = self.displayhook.prompt1.auto_rewrite() + cmd |
|
129 | new = self.displayhook.prompt1.auto_rewrite() + cmd | |
130 | payload = dict( |
|
130 | payload = dict( | |
131 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', |
|
131 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', | |
132 | transformed_input=new, |
|
132 | transformed_input=new, | |
133 | ) |
|
133 | ) | |
134 | self.payload_manager.write_payload(payload) |
|
134 | self.payload_manager.write_payload(payload) | |
135 |
|
135 | |||
136 | def ask_exit(self): |
|
136 | def ask_exit(self): | |
137 | """Engage the exit actions.""" |
|
137 | """Engage the exit actions.""" | |
138 | payload = dict( |
|
138 | payload = dict( | |
139 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', |
|
139 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', | |
140 | exit=True, |
|
140 | exit=True, | |
141 | keepkernel=self.keepkernel_on_exit, |
|
141 | keepkernel=self.keepkernel_on_exit, | |
142 | ) |
|
142 | ) | |
143 | self.payload_manager.write_payload(payload) |
|
143 | self.payload_manager.write_payload(payload) | |
144 |
|
144 | |||
145 | def _showtraceback(self, etype, evalue, stb): |
|
145 | def _showtraceback(self, etype, evalue, stb): | |
146 |
|
146 | |||
147 | exc_content = { |
|
147 | exc_content = { | |
148 | u'traceback' : stb, |
|
148 | u'traceback' : stb, | |
149 | u'ename' : unicode(etype.__name__), |
|
149 | u'ename' : unicode(etype.__name__), | |
150 | u'evalue' : unicode(evalue) |
|
150 | u'evalue' : unicode(evalue) | |
151 | } |
|
151 | } | |
152 |
|
152 | |||
153 | dh = self.displayhook |
|
153 | dh = self.displayhook | |
154 | # Send exception info over pub socket for other clients than the caller |
|
154 | # Send exception info over pub socket for other clients than the caller | |
155 | # to pick up |
|
155 | # to pick up | |
156 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header) |
|
156 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header) | |
157 |
|
157 | |||
158 | # FIXME - Hack: store exception info in shell object. Right now, the |
|
158 | # FIXME - Hack: store exception info in shell object. Right now, the | |
159 | # caller is reading this info after the fact, we need to fix this logic |
|
159 | # caller is reading this info after the fact, we need to fix this logic | |
160 | # to remove this hack. Even uglier, we need to store the error status |
|
160 | # to remove this hack. Even uglier, we need to store the error status | |
161 | # here, because in the main loop, the logic that sets it is being |
|
161 | # here, because in the main loop, the logic that sets it is being | |
162 | # skipped because runlines swallows the exceptions. |
|
162 | # skipped because runlines swallows the exceptions. | |
163 | exc_content[u'status'] = u'error' |
|
163 | exc_content[u'status'] = u'error' | |
164 | self._reply_content = exc_content |
|
164 | self._reply_content = exc_content | |
165 | # /FIXME |
|
165 | # /FIXME | |
166 |
|
166 | |||
167 | return exc_content |
|
167 | return exc_content | |
168 |
|
168 | |||
169 | #------------------------------------------------------------------------ |
|
169 | #------------------------------------------------------------------------ | |
170 | # Magic overrides |
|
170 | # Magic overrides | |
171 | #------------------------------------------------------------------------ |
|
171 | #------------------------------------------------------------------------ | |
172 | # Once the base class stops inheriting from magic, this code needs to be |
|
172 | # Once the base class stops inheriting from magic, this code needs to be | |
173 | # moved into a separate machinery as well. For now, at least isolate here |
|
173 | # moved into a separate machinery as well. For now, at least isolate here | |
174 | # the magics which this class needs to implement differently from the base |
|
174 | # the magics which this class needs to implement differently from the base | |
175 | # class, or that are unique to it. |
|
175 | # class, or that are unique to it. | |
176 |
|
176 | |||
177 | def magic_doctest_mode(self,parameter_s=''): |
|
177 | def magic_doctest_mode(self,parameter_s=''): | |
178 | """Toggle doctest mode on and off. |
|
178 | """Toggle doctest mode on and off. | |
179 |
|
179 | |||
180 | This mode is intended to make IPython behave as much as possible like a |
|
180 | This mode is intended to make IPython behave as much as possible like a | |
181 | plain Python shell, from the perspective of how its prompts, exceptions |
|
181 | plain Python shell, from the perspective of how its prompts, exceptions | |
182 | and output look. This makes it easy to copy and paste parts of a |
|
182 | and output look. This makes it easy to copy and paste parts of a | |
183 | session into doctests. It does so by: |
|
183 | session into doctests. It does so by: | |
184 |
|
184 | |||
185 | - Changing the prompts to the classic ``>>>`` ones. |
|
185 | - Changing the prompts to the classic ``>>>`` ones. | |
186 | - Changing the exception reporting mode to 'Plain'. |
|
186 | - Changing the exception reporting mode to 'Plain'. | |
187 | - Disabling pretty-printing of output. |
|
187 | - Disabling pretty-printing of output. | |
188 |
|
188 | |||
189 | Note that IPython also supports the pasting of code snippets that have |
|
189 | Note that IPython also supports the pasting of code snippets that have | |
190 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
190 | leading '>>>' and '...' prompts in them. This means that you can paste | |
191 | doctests from files or docstrings (even if they have leading |
|
191 | doctests from files or docstrings (even if they have leading | |
192 | whitespace), and the code will execute correctly. You can then use |
|
192 | whitespace), and the code will execute correctly. You can then use | |
193 | '%history -t' to see the translated history; this will give you the |
|
193 | '%history -t' to see the translated history; this will give you the | |
194 | input after removal of all the leading prompts and whitespace, which |
|
194 | input after removal of all the leading prompts and whitespace, which | |
195 | can be pasted back into an editor. |
|
195 | can be pasted back into an editor. | |
196 |
|
196 | |||
197 | With these features, you can switch into this mode easily whenever you |
|
197 | With these features, you can switch into this mode easily whenever you | |
198 | need to do testing and changes to doctests, without having to leave |
|
198 | need to do testing and changes to doctests, without having to leave | |
199 | your existing IPython session. |
|
199 | your existing IPython session. | |
200 | """ |
|
200 | """ | |
201 |
|
201 | |||
202 | from IPython.utils.ipstruct import Struct |
|
202 | from IPython.utils.ipstruct import Struct | |
203 |
|
203 | |||
204 | # Shorthands |
|
204 | # Shorthands | |
205 | shell = self.shell |
|
205 | shell = self.shell | |
206 | # dstore is a data store kept in the instance metadata bag to track any |
|
206 | # dstore is a data store kept in the instance metadata bag to track any | |
207 | # changes we make, so we can undo them later. |
|
207 | # changes we make, so we can undo them later. | |
208 | dstore = shell.meta.setdefault('doctest_mode', Struct()) |
|
208 | dstore = shell.meta.setdefault('doctest_mode', Struct()) | |
209 | save_dstore = dstore.setdefault |
|
209 | save_dstore = dstore.setdefault | |
210 |
|
210 | |||
211 | # save a few values we'll need to recover later |
|
211 | # save a few values we'll need to recover later | |
212 | mode = save_dstore('mode', False) |
|
212 | mode = save_dstore('mode', False) | |
213 | save_dstore('rc_pprint', shell.pprint) |
|
213 | save_dstore('rc_pprint', shell.pprint) | |
214 | save_dstore('xmode', shell.InteractiveTB.mode) |
|
214 | save_dstore('xmode', shell.InteractiveTB.mode) | |
215 |
|
215 | |||
216 | if mode == False: |
|
216 | if mode == False: | |
217 | # turn on |
|
217 | # turn on | |
218 | shell.pprint = False |
|
218 | shell.pprint = False | |
219 | shell.magic_xmode('Plain') |
|
219 | shell.magic_xmode('Plain') | |
220 | else: |
|
220 | else: | |
221 | # turn off |
|
221 | # turn off | |
222 | shell.pprint = dstore.rc_pprint |
|
222 | shell.pprint = dstore.rc_pprint | |
223 | shell.magic_xmode(dstore.xmode) |
|
223 | shell.magic_xmode(dstore.xmode) | |
224 |
|
224 | |||
225 | # Store new mode and inform on console |
|
225 | # Store new mode and inform on console | |
226 | dstore.mode = bool(1-int(mode)) |
|
226 | dstore.mode = bool(1-int(mode)) | |
227 | mode_label = ['OFF','ON'][dstore.mode] |
|
227 | mode_label = ['OFF','ON'][dstore.mode] | |
228 | print('Doctest mode is:', mode_label) |
|
228 | print('Doctest mode is:', mode_label) | |
229 |
|
229 | |||
230 | # Send the payload back so that clients can modify their prompt display |
|
230 | # Send the payload back so that clients can modify their prompt display | |
231 | payload = dict( |
|
231 | payload = dict( | |
232 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', |
|
232 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', | |
233 | mode=dstore.mode) |
|
233 | mode=dstore.mode) | |
234 | self.payload_manager.write_payload(payload) |
|
234 | self.payload_manager.write_payload(payload) | |
235 |
|
235 | |||
236 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
236 | def magic_edit(self,parameter_s='',last_call=['','']): | |
237 | """Bring up an editor and execute the resulting code. |
|
237 | """Bring up an editor and execute the resulting code. | |
238 |
|
238 | |||
239 | Usage: |
|
239 | Usage: | |
240 | %edit [options] [args] |
|
240 | %edit [options] [args] | |
241 |
|
241 | |||
242 | %edit runs IPython's editor hook. The default version of this hook is |
|
242 | %edit runs IPython's editor hook. The default version of this hook is | |
243 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
243 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
244 | environment variable $EDITOR. If this isn't found, it will default to |
|
244 | environment variable $EDITOR. If this isn't found, it will default to | |
245 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
245 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
246 | docstring for how to change the editor hook. |
|
246 | docstring for how to change the editor hook. | |
247 |
|
247 | |||
248 | You can also set the value of this editor via the command line option |
|
248 | You can also set the value of this editor via the command line option | |
249 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
249 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
250 | specifically for IPython an editor different from your typical default |
|
250 | specifically for IPython an editor different from your typical default | |
251 | (and for Windows users who typically don't set environment variables). |
|
251 | (and for Windows users who typically don't set environment variables). | |
252 |
|
252 | |||
253 | This command allows you to conveniently edit multi-line code right in |
|
253 | This command allows you to conveniently edit multi-line code right in | |
254 | your IPython session. |
|
254 | your IPython session. | |
255 |
|
255 | |||
256 | If called without arguments, %edit opens up an empty editor with a |
|
256 | If called without arguments, %edit opens up an empty editor with a | |
257 | temporary file and will execute the contents of this file when you |
|
257 | temporary file and will execute the contents of this file when you | |
258 | close it (don't forget to save it!). |
|
258 | close it (don't forget to save it!). | |
259 |
|
259 | |||
260 |
|
260 | |||
261 | Options: |
|
261 | Options: | |
262 |
|
262 | |||
263 | -n <number>: open the editor at a specified line number. By default, |
|
263 | -n <number>: open the editor at a specified line number. By default, | |
264 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
264 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
265 | you can configure this by providing your own modified hook if your |
|
265 | you can configure this by providing your own modified hook if your | |
266 | favorite editor supports line-number specifications with a different |
|
266 | favorite editor supports line-number specifications with a different | |
267 | syntax. |
|
267 | syntax. | |
268 |
|
268 | |||
269 | -p: this will call the editor with the same data as the previous time |
|
269 | -p: this will call the editor with the same data as the previous time | |
270 | it was used, regardless of how long ago (in your current session) it |
|
270 | it was used, regardless of how long ago (in your current session) it | |
271 | was. |
|
271 | was. | |
272 |
|
272 | |||
273 | -r: use 'raw' input. This option only applies to input taken from the |
|
273 | -r: use 'raw' input. This option only applies to input taken from the | |
274 | user's history. By default, the 'processed' history is used, so that |
|
274 | user's history. By default, the 'processed' history is used, so that | |
275 | magics are loaded in their transformed version to valid Python. If |
|
275 | magics are loaded in their transformed version to valid Python. If | |
276 | this option is given, the raw input as typed as the command line is |
|
276 | this option is given, the raw input as typed as the command line is | |
277 | used instead. When you exit the editor, it will be executed by |
|
277 | used instead. When you exit the editor, it will be executed by | |
278 | IPython's own processor. |
|
278 | IPython's own processor. | |
279 |
|
279 | |||
280 | -x: do not execute the edited code immediately upon exit. This is |
|
280 | -x: do not execute the edited code immediately upon exit. This is | |
281 | mainly useful if you are editing programs which need to be called with |
|
281 | mainly useful if you are editing programs which need to be called with | |
282 | command line arguments, which you can then do using %run. |
|
282 | command line arguments, which you can then do using %run. | |
283 |
|
283 | |||
284 |
|
284 | |||
285 | Arguments: |
|
285 | Arguments: | |
286 |
|
286 | |||
287 | If arguments are given, the following possibilites exist: |
|
287 | If arguments are given, the following possibilites exist: | |
288 |
|
288 | |||
289 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
289 | - The arguments are numbers or pairs of colon-separated numbers (like | |
290 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
290 | 1 4:8 9). These are interpreted as lines of previous input to be | |
291 | loaded into the editor. The syntax is the same of the %macro command. |
|
291 | loaded into the editor. The syntax is the same of the %macro command. | |
292 |
|
292 | |||
293 | - If the argument doesn't start with a number, it is evaluated as a |
|
293 | - If the argument doesn't start with a number, it is evaluated as a | |
294 | variable and its contents loaded into the editor. You can thus edit |
|
294 | variable and its contents loaded into the editor. You can thus edit | |
295 | any string which contains python code (including the result of |
|
295 | any string which contains python code (including the result of | |
296 | previous edits). |
|
296 | previous edits). | |
297 |
|
297 | |||
298 | - If the argument is the name of an object (other than a string), |
|
298 | - If the argument is the name of an object (other than a string), | |
299 | IPython will try to locate the file where it was defined and open the |
|
299 | IPython will try to locate the file where it was defined and open the | |
300 | editor at the point where it is defined. You can use `%edit function` |
|
300 | editor at the point where it is defined. You can use `%edit function` | |
301 | to load an editor exactly at the point where 'function' is defined, |
|
301 | to load an editor exactly at the point where 'function' is defined, | |
302 | edit it and have the file be executed automatically. |
|
302 | edit it and have the file be executed automatically. | |
303 |
|
303 | |||
304 | If the object is a macro (see %macro for details), this opens up your |
|
304 | If the object is a macro (see %macro for details), this opens up your | |
305 | specified editor with a temporary file containing the macro's data. |
|
305 | specified editor with a temporary file containing the macro's data. | |
306 | Upon exit, the macro is reloaded with the contents of the file. |
|
306 | Upon exit, the macro is reloaded with the contents of the file. | |
307 |
|
307 | |||
308 | Note: opening at an exact line is only supported under Unix, and some |
|
308 | Note: opening at an exact line is only supported under Unix, and some | |
309 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
309 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
310 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
310 | '+NUMBER' parameter necessary for this feature. Good editors like | |
311 | (X)Emacs, vi, jed, pico and joe all do. |
|
311 | (X)Emacs, vi, jed, pico and joe all do. | |
312 |
|
312 | |||
313 | - If the argument is not found as a variable, IPython will look for a |
|
313 | - If the argument is not found as a variable, IPython will look for a | |
314 | file with that name (adding .py if necessary) and load it into the |
|
314 | file with that name (adding .py if necessary) and load it into the | |
315 | editor. It will execute its contents with execfile() when you exit, |
|
315 | editor. It will execute its contents with execfile() when you exit, | |
316 | loading any code in the file into your interactive namespace. |
|
316 | loading any code in the file into your interactive namespace. | |
317 |
|
317 | |||
318 | After executing your code, %edit will return as output the code you |
|
318 | After executing your code, %edit will return as output the code you | |
319 | typed in the editor (except when it was an existing file). This way |
|
319 | typed in the editor (except when it was an existing file). This way | |
320 | you can reload the code in further invocations of %edit as a variable, |
|
320 | you can reload the code in further invocations of %edit as a variable, | |
321 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
321 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
322 | the output. |
|
322 | the output. | |
323 |
|
323 | |||
324 | Note that %edit is also available through the alias %ed. |
|
324 | Note that %edit is also available through the alias %ed. | |
325 |
|
325 | |||
326 | This is an example of creating a simple function inside the editor and |
|
326 | This is an example of creating a simple function inside the editor and | |
327 | then modifying it. First, start up the editor: |
|
327 | then modifying it. First, start up the editor: | |
328 |
|
328 | |||
329 | In [1]: ed |
|
329 | In [1]: ed | |
330 | Editing... done. Executing edited code... |
|
330 | Editing... done. Executing edited code... | |
331 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
331 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
332 |
|
332 | |||
333 | We can then call the function foo(): |
|
333 | We can then call the function foo(): | |
334 |
|
334 | |||
335 | In [2]: foo() |
|
335 | In [2]: foo() | |
336 | foo() was defined in an editing session |
|
336 | foo() was defined in an editing session | |
337 |
|
337 | |||
338 | Now we edit foo. IPython automatically loads the editor with the |
|
338 | Now we edit foo. IPython automatically loads the editor with the | |
339 | (temporary) file where foo() was previously defined: |
|
339 | (temporary) file where foo() was previously defined: | |
340 |
|
340 | |||
341 | In [3]: ed foo |
|
341 | In [3]: ed foo | |
342 | Editing... done. Executing edited code... |
|
342 | Editing... done. Executing edited code... | |
343 |
|
343 | |||
344 | And if we call foo() again we get the modified version: |
|
344 | And if we call foo() again we get the modified version: | |
345 |
|
345 | |||
346 | In [4]: foo() |
|
346 | In [4]: foo() | |
347 | foo() has now been changed! |
|
347 | foo() has now been changed! | |
348 |
|
348 | |||
349 | Here is an example of how to edit a code snippet successive |
|
349 | Here is an example of how to edit a code snippet successive | |
350 | times. First we call the editor: |
|
350 | times. First we call the editor: | |
351 |
|
351 | |||
352 | In [5]: ed |
|
352 | In [5]: ed | |
353 | Editing... done. Executing edited code... |
|
353 | Editing... done. Executing edited code... | |
354 | hello |
|
354 | hello | |
355 | Out[5]: "print 'hello'n" |
|
355 | Out[5]: "print 'hello'n" | |
356 |
|
356 | |||
357 | Now we call it again with the previous output (stored in _): |
|
357 | Now we call it again with the previous output (stored in _): | |
358 |
|
358 | |||
359 | In [6]: ed _ |
|
359 | In [6]: ed _ | |
360 | Editing... done. Executing edited code... |
|
360 | Editing... done. Executing edited code... | |
361 | hello world |
|
361 | hello world | |
362 | Out[6]: "print 'hello world'n" |
|
362 | Out[6]: "print 'hello world'n" | |
363 |
|
363 | |||
364 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
364 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
365 |
|
365 | |||
366 | In [7]: ed _8 |
|
366 | In [7]: ed _8 | |
367 | Editing... done. Executing edited code... |
|
367 | Editing... done. Executing edited code... | |
368 | hello again |
|
368 | hello again | |
369 | Out[7]: "print 'hello again'n" |
|
369 | Out[7]: "print 'hello again'n" | |
370 |
|
370 | |||
371 |
|
371 | |||
372 | Changing the default editor hook: |
|
372 | Changing the default editor hook: | |
373 |
|
373 | |||
374 | If you wish to write your own editor hook, you can put it in a |
|
374 | If you wish to write your own editor hook, you can put it in a | |
375 | configuration file which you load at startup time. The default hook |
|
375 | configuration file which you load at startup time. The default hook | |
376 | is defined in the IPython.core.hooks module, and you can use that as a |
|
376 | is defined in the IPython.core.hooks module, and you can use that as a | |
377 | starting example for further modifications. That file also has |
|
377 | starting example for further modifications. That file also has | |
378 | general instructions on how to set a new hook for use once you've |
|
378 | general instructions on how to set a new hook for use once you've | |
379 | defined it.""" |
|
379 | defined it.""" | |
380 |
|
380 | |||
381 | # FIXME: This function has become a convoluted mess. It needs a |
|
381 | # FIXME: This function has become a convoluted mess. It needs a | |
382 | # ground-up rewrite with clean, simple logic. |
|
382 | # ground-up rewrite with clean, simple logic. | |
383 |
|
383 | |||
384 | def make_filename(arg): |
|
384 | def make_filename(arg): | |
385 | "Make a filename from the given args" |
|
385 | "Make a filename from the given args" | |
386 | try: |
|
386 | try: | |
387 | filename = get_py_filename(arg) |
|
387 | filename = get_py_filename(arg) | |
388 | except IOError: |
|
388 | except IOError: | |
389 | if args.endswith('.py'): |
|
389 | if args.endswith('.py'): | |
390 | filename = arg |
|
390 | filename = arg | |
391 | else: |
|
391 | else: | |
392 | filename = None |
|
392 | filename = None | |
393 | return filename |
|
393 | return filename | |
394 |
|
394 | |||
395 | # custom exceptions |
|
395 | # custom exceptions | |
396 | class DataIsObject(Exception): pass |
|
396 | class DataIsObject(Exception): pass | |
397 |
|
397 | |||
398 | opts,args = self.parse_options(parameter_s,'prn:') |
|
398 | opts,args = self.parse_options(parameter_s,'prn:') | |
399 | # Set a few locals from the options for convenience: |
|
399 | # Set a few locals from the options for convenience: | |
400 | opts_p = opts.has_key('p') |
|
400 | opts_p = opts.has_key('p') | |
401 | opts_r = opts.has_key('r') |
|
401 | opts_r = opts.has_key('r') | |
402 |
|
402 | |||
403 | # Default line number value |
|
403 | # Default line number value | |
404 | lineno = opts.get('n',None) |
|
404 | lineno = opts.get('n',None) | |
405 | if lineno is not None: |
|
405 | if lineno is not None: | |
406 | try: |
|
406 | try: | |
407 | lineno = int(lineno) |
|
407 | lineno = int(lineno) | |
408 | except: |
|
408 | except: | |
409 | warn("The -n argument must be an integer.") |
|
409 | warn("The -n argument must be an integer.") | |
410 | return |
|
410 | return | |
411 |
|
411 | |||
412 | if opts_p: |
|
412 | if opts_p: | |
413 | args = '_%s' % last_call[0] |
|
413 | args = '_%s' % last_call[0] | |
414 | if not self.shell.user_ns.has_key(args): |
|
414 | if not self.shell.user_ns.has_key(args): | |
415 | args = last_call[1] |
|
415 | args = last_call[1] | |
416 |
|
416 | |||
417 | # use last_call to remember the state of the previous call, but don't |
|
417 | # use last_call to remember the state of the previous call, but don't | |
418 | # let it be clobbered by successive '-p' calls. |
|
418 | # let it be clobbered by successive '-p' calls. | |
419 | try: |
|
419 | try: | |
420 | last_call[0] = self.shell.displayhook.prompt_count |
|
420 | last_call[0] = self.shell.displayhook.prompt_count | |
421 | if not opts_p: |
|
421 | if not opts_p: | |
422 | last_call[1] = parameter_s |
|
422 | last_call[1] = parameter_s | |
423 | except: |
|
423 | except: | |
424 | pass |
|
424 | pass | |
425 |
|
425 | |||
426 | # by default this is done with temp files, except when the given |
|
426 | # by default this is done with temp files, except when the given | |
427 | # arg is a filename |
|
427 | # arg is a filename | |
428 | use_temp = 1 |
|
428 | use_temp = 1 | |
429 |
|
429 | |||
430 | if re.match(r'\d',args): |
|
430 | if re.match(r'\d',args): | |
431 | # Mode where user specifies ranges of lines, like in %macro. |
|
431 | # Mode where user specifies ranges of lines, like in %macro. | |
432 | # This means that you can't edit files whose names begin with |
|
432 | # This means that you can't edit files whose names begin with | |
433 | # numbers this way. Tough. |
|
433 | # numbers this way. Tough. | |
434 | ranges = args.split() |
|
434 | ranges = args.split() | |
435 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
435 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
436 | elif args.endswith('.py'): |
|
436 | elif args.endswith('.py'): | |
437 | filename = make_filename(args) |
|
437 | filename = make_filename(args) | |
438 | data = '' |
|
438 | data = '' | |
439 | use_temp = 0 |
|
439 | use_temp = 0 | |
440 | elif args: |
|
440 | elif args: | |
441 | try: |
|
441 | try: | |
442 | # Load the parameter given as a variable. If not a string, |
|
442 | # Load the parameter given as a variable. If not a string, | |
443 | # process it as an object instead (below) |
|
443 | # process it as an object instead (below) | |
444 |
|
444 | |||
445 | #print '*** args',args,'type',type(args) # dbg |
|
445 | #print '*** args',args,'type',type(args) # dbg | |
446 | data = eval(args,self.shell.user_ns) |
|
446 | data = eval(args,self.shell.user_ns) | |
447 | if not type(data) in StringTypes: |
|
447 | if not type(data) in StringTypes: | |
448 | raise DataIsObject |
|
448 | raise DataIsObject | |
449 |
|
449 | |||
450 | except (NameError,SyntaxError): |
|
450 | except (NameError,SyntaxError): | |
451 | # given argument is not a variable, try as a filename |
|
451 | # given argument is not a variable, try as a filename | |
452 | filename = make_filename(args) |
|
452 | filename = make_filename(args) | |
453 | if filename is None: |
|
453 | if filename is None: | |
454 | warn("Argument given (%s) can't be found as a variable " |
|
454 | warn("Argument given (%s) can't be found as a variable " | |
455 | "or as a filename." % args) |
|
455 | "or as a filename." % args) | |
456 | return |
|
456 | return | |
457 |
|
457 | |||
458 | data = '' |
|
458 | data = '' | |
459 | use_temp = 0 |
|
459 | use_temp = 0 | |
460 | except DataIsObject: |
|
460 | except DataIsObject: | |
461 |
|
461 | |||
462 | # macros have a special edit function |
|
462 | # macros have a special edit function | |
463 | if isinstance(data,Macro): |
|
463 | if isinstance(data,Macro): | |
464 | self._edit_macro(args,data) |
|
464 | self._edit_macro(args,data) | |
465 | return |
|
465 | return | |
466 |
|
466 | |||
467 | # For objects, try to edit the file where they are defined |
|
467 | # For objects, try to edit the file where they are defined | |
468 | try: |
|
468 | try: | |
469 | filename = inspect.getabsfile(data) |
|
469 | filename = inspect.getabsfile(data) | |
470 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
470 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
471 | # class created by %edit? Try to find source |
|
471 | # class created by %edit? Try to find source | |
472 | # by looking for method definitions instead, the |
|
472 | # by looking for method definitions instead, the | |
473 | # __module__ in those classes is FakeModule. |
|
473 | # __module__ in those classes is FakeModule. | |
474 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
474 | attrs = [getattr(data, aname) for aname in dir(data)] | |
475 | for attr in attrs: |
|
475 | for attr in attrs: | |
476 | if not inspect.ismethod(attr): |
|
476 | if not inspect.ismethod(attr): | |
477 | continue |
|
477 | continue | |
478 | filename = inspect.getabsfile(attr) |
|
478 | filename = inspect.getabsfile(attr) | |
479 | if filename and 'fakemodule' not in filename.lower(): |
|
479 | if filename and 'fakemodule' not in filename.lower(): | |
480 | # change the attribute to be the edit target instead |
|
480 | # change the attribute to be the edit target instead | |
481 | data = attr |
|
481 | data = attr | |
482 | break |
|
482 | break | |
483 |
|
483 | |||
484 | datafile = 1 |
|
484 | datafile = 1 | |
485 | except TypeError: |
|
485 | except TypeError: | |
486 | filename = make_filename(args) |
|
486 | filename = make_filename(args) | |
487 | datafile = 1 |
|
487 | datafile = 1 | |
488 | warn('Could not find file where `%s` is defined.\n' |
|
488 | warn('Could not find file where `%s` is defined.\n' | |
489 | 'Opening a file named `%s`' % (args,filename)) |
|
489 | 'Opening a file named `%s`' % (args,filename)) | |
490 | # Now, make sure we can actually read the source (if it was in |
|
490 | # Now, make sure we can actually read the source (if it was in | |
491 | # a temp file it's gone by now). |
|
491 | # a temp file it's gone by now). | |
492 | if datafile: |
|
492 | if datafile: | |
493 | try: |
|
493 | try: | |
494 | if lineno is None: |
|
494 | if lineno is None: | |
495 | lineno = inspect.getsourcelines(data)[1] |
|
495 | lineno = inspect.getsourcelines(data)[1] | |
496 | except IOError: |
|
496 | except IOError: | |
497 | filename = make_filename(args) |
|
497 | filename = make_filename(args) | |
498 | if filename is None: |
|
498 | if filename is None: | |
499 | warn('The file `%s` where `%s` was defined cannot ' |
|
499 | warn('The file `%s` where `%s` was defined cannot ' | |
500 | 'be read.' % (filename,data)) |
|
500 | 'be read.' % (filename,data)) | |
501 | return |
|
501 | return | |
502 | use_temp = 0 |
|
502 | use_temp = 0 | |
503 | else: |
|
503 | else: | |
504 | data = '' |
|
504 | data = '' | |
505 |
|
505 | |||
506 | if use_temp: |
|
506 | if use_temp: | |
507 | filename = self.shell.mktempfile(data) |
|
507 | filename = self.shell.mktempfile(data) | |
508 | print('IPython will make a temporary file named:', filename) |
|
508 | print('IPython will make a temporary file named:', filename) | |
509 |
|
509 | |||
510 | # Make sure we send to the client an absolute path, in case the working |
|
510 | # Make sure we send to the client an absolute path, in case the working | |
511 | # directory of client and kernel don't match |
|
511 | # directory of client and kernel don't match | |
512 | filename = os.path.abspath(filename) |
|
512 | filename = os.path.abspath(filename) | |
513 |
|
513 | |||
514 | payload = { |
|
514 | payload = { | |
515 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
515 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', | |
516 | 'filename' : filename, |
|
516 | 'filename' : filename, | |
517 | 'line_number' : lineno |
|
517 | 'line_number' : lineno | |
518 | } |
|
518 | } | |
519 | self.payload_manager.write_payload(payload) |
|
519 | self.payload_manager.write_payload(payload) | |
520 |
|
520 | |||
521 | def magic_gui(self, *args, **kwargs): |
|
521 | def magic_gui(self, *args, **kwargs): | |
522 | raise NotImplementedError( |
|
522 | raise NotImplementedError( | |
523 | 'GUI support must be enabled in command line options.') |
|
523 | 'GUI support must be enabled in command line options.') | |
524 |
|
524 | |||
525 | def magic_pylab(self, *args, **kwargs): |
|
525 | def magic_pylab(self, *args, **kwargs): | |
526 | raise NotImplementedError( |
|
526 | raise NotImplementedError( | |
527 | 'pylab support must be enabled in command line options.') |
|
527 | 'pylab support must be enabled in command line options.') | |
528 |
|
528 | |||
529 | # A few magics that are adapted to the specifics of using pexpect and a |
|
529 | # A few magics that are adapted to the specifics of using pexpect and a | |
530 | # remote terminal |
|
530 | # remote terminal | |
531 |
|
531 | |||
532 | def magic_clear(self, arg_s): |
|
532 | def magic_clear(self, arg_s): | |
533 | """Clear the terminal.""" |
|
533 | """Clear the terminal.""" | |
534 | if os.name == 'posix': |
|
534 | if os.name == 'posix': | |
535 | self.shell.system("clear") |
|
535 | self.shell.system("clear") | |
536 | else: |
|
536 | else: | |
537 | self.shell.system("cls") |
|
537 | self.shell.system("cls") | |
538 |
|
538 | |||
539 | if os.name == 'nt': |
|
539 | if os.name == 'nt': | |
540 | # This is the usual name in windows |
|
540 | # This is the usual name in windows | |
541 | magic_cls = magic_clear |
|
541 | magic_cls = magic_clear | |
542 |
|
542 | |||
543 | # Terminal pagers won't work over pexpect, but we do have our own pager |
|
543 | # Terminal pagers won't work over pexpect, but we do have our own pager | |
544 |
|
544 | |||
545 | def magic_less(self, arg_s): |
|
545 | def magic_less(self, arg_s): | |
546 | """Show a file through the pager. |
|
546 | """Show a file through the pager. | |
547 |
|
547 | |||
548 | Files ending in .py are syntax-highlighted.""" |
|
548 | Files ending in .py are syntax-highlighted.""" | |
549 | cont = open(arg_s).read() |
|
549 | cont = open(arg_s).read() | |
550 | if arg_s.endswith('.py'): |
|
550 | if arg_s.endswith('.py'): | |
551 | cont = self.shell.pycolorize(cont) |
|
551 | cont = self.shell.pycolorize(cont) | |
552 | page.page(cont) |
|
552 | page.page(cont) | |
553 |
|
553 | |||
554 | magic_more = magic_less |
|
554 | magic_more = magic_less | |
555 |
|
555 | |||
556 | # Man calls a pager, so we also need to redefine it |
|
556 | # Man calls a pager, so we also need to redefine it | |
557 | if os.name == 'posix': |
|
557 | if os.name == 'posix': | |
558 | def magic_man(self, arg_s): |
|
558 | def magic_man(self, arg_s): | |
559 | """Find the man page for the given command and display in pager.""" |
|
559 | """Find the man page for the given command and display in pager.""" | |
560 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, |
|
560 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, | |
561 | split=False)) |
|
561 | split=False)) | |
562 |
|
562 | |||
563 | # FIXME: this is specific to the GUI, so we should let the gui app load |
|
563 | # FIXME: this is specific to the GUI, so we should let the gui app load | |
564 | # magics at startup that are only for the gui. Once the gui app has proper |
|
564 | # magics at startup that are only for the gui. Once the gui app has proper | |
565 | # profile and configuration management, we can have it initialize a kernel |
|
565 | # profile and configuration management, we can have it initialize a kernel | |
566 | # with a special config file that provides these. |
|
566 | # with a special config file that provides these. | |
567 | def magic_guiref(self, arg_s): |
|
567 | def magic_guiref(self, arg_s): | |
568 | """Show a basic reference about the GUI console.""" |
|
568 | """Show a basic reference about the GUI console.""" | |
569 | from IPython.core.usage import gui_reference |
|
569 | from IPython.core.usage import gui_reference | |
570 | page.page(gui_reference, auto_html=True) |
|
570 | page.page(gui_reference, auto_html=True) | |
571 |
|
571 | |||
572 | def magic_loadpy(self, arg_s): |
|
572 | def magic_loadpy(self, arg_s): | |
573 | """Load a .py python script into the GUI console. |
|
573 | """Load a .py python script into the GUI console. | |
574 |
|
574 | |||
575 | This magic command can either take a local filename or a url:: |
|
575 | This magic command can either take a local filename or a url:: | |
576 |
|
576 | |||
577 | %loadpy myscript.py |
|
577 | %loadpy myscript.py | |
578 | %loadpy http://www.example.com/myscript.py |
|
578 | %loadpy http://www.example.com/myscript.py | |
579 | """ |
|
579 | """ | |
580 | if not arg_s.endswith('.py'): |
|
580 | if not arg_s.endswith('.py'): | |
581 | raise ValueError('%%load only works with .py files: %s' % arg_s) |
|
581 | raise ValueError('%%load only works with .py files: %s' % arg_s) | |
582 | if arg_s.startswith('http'): |
|
582 | if arg_s.startswith('http'): | |
583 | import urllib2 |
|
583 | import urllib2 | |
584 | response = urllib2.urlopen(arg_s) |
|
584 | response = urllib2.urlopen(arg_s) | |
585 | content = response.read() |
|
585 | content = response.read() | |
586 | else: |
|
586 | else: | |
587 | content = open(arg_s).read() |
|
587 | content = open(arg_s).read() | |
588 | payload = dict( |
|
588 | payload = dict( | |
589 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy', |
|
589 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy', | |
590 | text=content |
|
590 | text=content | |
591 | ) |
|
591 | ) | |
592 | self.payload_manager.write_payload(payload) |
|
592 | self.payload_manager.write_payload(payload) | |
593 |
|
593 | |||
594 | def magic_Exit(self, parameter_s=''): |
|
594 | def magic_Exit(self, parameter_s=''): | |
595 | """Exit IPython. If the -k option is provided, the kernel will be left |
|
595 | """Exit IPython. If the -k option is provided, the kernel will be left | |
596 | running. Otherwise, it will shutdown without prompting. |
|
596 | running. Otherwise, it will shutdown without prompting. | |
597 | """ |
|
597 | """ | |
598 | opts,args = self.parse_options(parameter_s,'k') |
|
598 | opts,args = self.parse_options(parameter_s,'k') | |
599 | self.shell.keepkernel_on_exit = opts.has_key('k') |
|
599 | self.shell.keepkernel_on_exit = opts.has_key('k') | |
600 | self.shell.ask_exit() |
|
600 | self.shell.ask_exit() | |
601 |
|
601 | |||
602 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
602 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
603 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
603 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
604 |
|
604 | |||
605 | InteractiveShellABC.register(ZMQInteractiveShell) |
|
605 | InteractiveShellABC.register(ZMQInteractiveShell) |
@@ -1,936 +1,922 b'' | |||||
1 | .. _messaging: |
|
1 | .. _messaging: | |
2 |
|
2 | |||
3 | ====================== |
|
3 | ====================== | |
4 | Messaging in IPython |
|
4 | Messaging in IPython | |
5 | ====================== |
|
5 | ====================== | |
6 |
|
6 | |||
7 |
|
7 | |||
8 | Introduction |
|
8 | Introduction | |
9 | ============ |
|
9 | ============ | |
10 |
|
10 | |||
11 | This document explains the basic communications design and messaging |
|
11 | This document explains the basic communications design and messaging | |
12 | specification for how the various IPython objects interact over a network |
|
12 | specification for how the various IPython objects interact over a network | |
13 | transport. The current implementation uses the ZeroMQ_ library for messaging |
|
13 | transport. The current implementation uses the ZeroMQ_ library for messaging | |
14 | within and between hosts. |
|
14 | within and between hosts. | |
15 |
|
15 | |||
16 | .. Note:: |
|
16 | .. Note:: | |
17 |
|
17 | |||
18 | This document should be considered the authoritative description of the |
|
18 | This document should be considered the authoritative description of the | |
19 | IPython messaging protocol, and all developers are strongly encouraged to |
|
19 | IPython messaging protocol, and all developers are strongly encouraged to | |
20 | keep it updated as the implementation evolves, so that we have a single |
|
20 | keep it updated as the implementation evolves, so that we have a single | |
21 | common reference for all protocol details. |
|
21 | common reference for all protocol details. | |
22 |
|
22 | |||
23 | The basic design is explained in the following diagram: |
|
23 | The basic design is explained in the following diagram: | |
24 |
|
24 | |||
25 | .. image:: frontend-kernel.png |
|
25 | .. image:: frontend-kernel.png | |
26 | :width: 450px |
|
26 | :width: 450px | |
27 | :alt: IPython kernel/frontend messaging architecture. |
|
27 | :alt: IPython kernel/frontend messaging architecture. | |
28 | :align: center |
|
28 | :align: center | |
29 | :target: ../_images/frontend-kernel.png |
|
29 | :target: ../_images/frontend-kernel.png | |
30 |
|
30 | |||
31 | A single kernel can be simultaneously connected to one or more frontends. The |
|
31 | A single kernel can be simultaneously connected to one or more frontends. The | |
32 | kernel has three sockets that serve the following functions: |
|
32 | kernel has three sockets that serve the following functions: | |
33 |
|
33 | |||
34 | 1. REQ: this socket is connected to a *single* frontend at a time, and it allows |
|
34 | 1. REQ: this socket is connected to a *single* frontend at a time, and it allows | |
35 | the kernel to request input from a frontend when :func:`raw_input` is called. |
|
35 | the kernel to request input from a frontend when :func:`raw_input` is called. | |
36 | The frontend holding the matching REP socket acts as a 'virtual keyboard' |
|
36 | The frontend holding the matching REP socket acts as a 'virtual keyboard' | |
37 | for the kernel while this communication is happening (illustrated in the |
|
37 | for the kernel while this communication is happening (illustrated in the | |
38 | figure by the black outline around the central keyboard). In practice, |
|
38 | figure by the black outline around the central keyboard). In practice, | |
39 | frontends may display such kernel requests using a special input widget or |
|
39 | frontends may display such kernel requests using a special input widget or | |
40 | otherwise indicating that the user is to type input for the kernel instead |
|
40 | otherwise indicating that the user is to type input for the kernel instead | |
41 | of normal commands in the frontend. |
|
41 | of normal commands in the frontend. | |
42 |
|
42 | |||
43 | 2. XREP: this single sockets allows multiple incoming connections from |
|
43 | 2. XREP: this single sockets allows multiple incoming connections from | |
44 | frontends, and this is the socket where requests for code execution, object |
|
44 | frontends, and this is the socket where requests for code execution, object | |
45 | information, prompts, etc. are made to the kernel by any frontend. The |
|
45 | information, prompts, etc. are made to the kernel by any frontend. The | |
46 | communication on this socket is a sequence of request/reply actions from |
|
46 | communication on this socket is a sequence of request/reply actions from | |
47 | each frontend and the kernel. |
|
47 | each frontend and the kernel. | |
48 |
|
48 | |||
49 | 3. PUB: this socket is the 'broadcast channel' where the kernel publishes all |
|
49 | 3. PUB: this socket is the 'broadcast channel' where the kernel publishes all | |
50 | side effects (stdout, stderr, etc.) as well as the requests coming from any |
|
50 | side effects (stdout, stderr, etc.) as well as the requests coming from any | |
51 | client over the XREP socket and its own requests on the REP socket. There |
|
51 | client over the XREP socket and its own requests on the REP socket. There | |
52 | are a number of actions in Python which generate side effects: :func:`print` |
|
52 | are a number of actions in Python which generate side effects: :func:`print` | |
53 | writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in |
|
53 | writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in | |
54 | a multi-client scenario, we want all frontends to be able to know what each |
|
54 | a multi-client scenario, we want all frontends to be able to know what each | |
55 | other has sent to the kernel (this can be useful in collaborative scenarios, |
|
55 | other has sent to the kernel (this can be useful in collaborative scenarios, | |
56 | for example). This socket allows both side effects and the information |
|
56 | for example). This socket allows both side effects and the information | |
57 | about communications taking place with one client over the XREQ/XREP channel |
|
57 | about communications taking place with one client over the XREQ/XREP channel | |
58 | to be made available to all clients in a uniform manner. |
|
58 | to be made available to all clients in a uniform manner. | |
59 |
|
59 | |||
60 | All messages are tagged with enough information (details below) for clients |
|
60 | All messages are tagged with enough information (details below) for clients | |
61 | to know which messages come from their own interaction with the kernel and |
|
61 | to know which messages come from their own interaction with the kernel and | |
62 | which ones are from other clients, so they can display each type |
|
62 | which ones are from other clients, so they can display each type | |
63 | appropriately. |
|
63 | appropriately. | |
64 |
|
64 | |||
65 | The actual format of the messages allowed on each of these channels is |
|
65 | The actual format of the messages allowed on each of these channels is | |
66 | specified below. Messages are dicts of dicts with string keys and values that |
|
66 | specified below. Messages are dicts of dicts with string keys and values that | |
67 | are reasonably representable in JSON. Our current implementation uses JSON |
|
67 | are reasonably representable in JSON. Our current implementation uses JSON | |
68 | explicitly as its message format, but this shouldn't be considered a permanent |
|
68 | explicitly as its message format, but this shouldn't be considered a permanent | |
69 | feature. As we've discovered that JSON has non-trivial performance issues due |
|
69 | feature. As we've discovered that JSON has non-trivial performance issues due | |
70 | to excessive copying, we may in the future move to a pure pickle-based raw |
|
70 | to excessive copying, we may in the future move to a pure pickle-based raw | |
71 | message format. However, it should be possible to easily convert from the raw |
|
71 | message format. However, it should be possible to easily convert from the raw | |
72 | objects to JSON, since we may have non-python clients (e.g. a web frontend). |
|
72 | objects to JSON, since we may have non-python clients (e.g. a web frontend). | |
73 | As long as it's easy to make a JSON version of the objects that is a faithful |
|
73 | As long as it's easy to make a JSON version of the objects that is a faithful | |
74 | representation of all the data, we can communicate with such clients. |
|
74 | representation of all the data, we can communicate with such clients. | |
75 |
|
75 | |||
76 | .. Note:: |
|
76 | .. Note:: | |
77 |
|
77 | |||
78 | Not all of these have yet been fully fleshed out, but the key ones are, see |
|
78 | Not all of these have yet been fully fleshed out, but the key ones are, see | |
79 | kernel and frontend files for actual implementation details. |
|
79 | kernel and frontend files for actual implementation details. | |
80 |
|
80 | |||
81 |
|
81 | |||
82 | Python functional API |
|
82 | Python functional API | |
83 | ===================== |
|
83 | ===================== | |
84 |
|
84 | |||
85 | As messages are dicts, they map naturally to a ``func(**kw)`` call form. We |
|
85 | As messages are dicts, they map naturally to a ``func(**kw)`` call form. We | |
86 | should develop, at a few key points, functional forms of all the requests that |
|
86 | should develop, at a few key points, functional forms of all the requests that | |
87 | take arguments in this manner and automatically construct the necessary dict |
|
87 | take arguments in this manner and automatically construct the necessary dict | |
88 | for sending. |
|
88 | for sending. | |
89 |
|
89 | |||
90 |
|
90 | |||
91 | General Message Format |
|
91 | General Message Format | |
92 | ====================== |
|
92 | ====================== | |
93 |
|
93 | |||
94 | All messages send or received by any IPython process should have the following |
|
94 | All messages send or received by any IPython process should have the following | |
95 | generic structure:: |
|
95 | generic structure:: | |
96 |
|
96 | |||
97 | { |
|
97 | { | |
98 | # The message header contains a pair of unique identifiers for the |
|
98 | # The message header contains a pair of unique identifiers for the | |
99 | # originating session and the actual message id, in addition to the |
|
99 | # originating session and the actual message id, in addition to the | |
100 | # username for the process that generated the message. This is useful in |
|
100 | # username for the process that generated the message. This is useful in | |
101 | # collaborative settings where multiple users may be interacting with the |
|
101 | # collaborative settings where multiple users may be interacting with the | |
102 | # same kernel simultaneously, so that frontends can label the various |
|
102 | # same kernel simultaneously, so that frontends can label the various | |
103 | # messages in a meaningful way. |
|
103 | # messages in a meaningful way. | |
104 | 'header' : { 'msg_id' : uuid, |
|
104 | 'header' : { 'msg_id' : uuid, | |
105 | 'username' : str, |
|
105 | 'username' : str, | |
106 | 'session' : uuid |
|
106 | 'session' : uuid | |
107 | }, |
|
107 | }, | |
108 |
|
108 | |||
109 | # In a chain of messages, the header from the parent is copied so that |
|
109 | # In a chain of messages, the header from the parent is copied so that | |
110 | # clients can track where messages come from. |
|
110 | # clients can track where messages come from. | |
111 | 'parent_header' : dict, |
|
111 | 'parent_header' : dict, | |
112 |
|
112 | |||
113 | # All recognized message type strings are listed below. |
|
113 | # All recognized message type strings are listed below. | |
114 | 'msg_type' : str, |
|
114 | 'msg_type' : str, | |
115 |
|
115 | |||
116 | # The actual content of the message must be a dict, whose structure |
|
116 | # The actual content of the message must be a dict, whose structure | |
117 | # depends on the message type.x |
|
117 | # depends on the message type.x | |
118 | 'content' : dict, |
|
118 | 'content' : dict, | |
119 | } |
|
119 | } | |
120 |
|
120 | |||
121 | For each message type, the actual content will differ and all existing message |
|
121 | For each message type, the actual content will differ and all existing message | |
122 | types are specified in what follows of this document. |
|
122 | types are specified in what follows of this document. | |
123 |
|
123 | |||
124 |
|
124 | |||
125 | Messages on the XREP/XREQ socket |
|
125 | Messages on the XREP/XREQ socket | |
126 | ================================ |
|
126 | ================================ | |
127 |
|
127 | |||
128 | .. _execute: |
|
128 | .. _execute: | |
129 |
|
129 | |||
130 | Execute |
|
130 | Execute | |
131 | ------- |
|
131 | ------- | |
132 |
|
132 | |||
133 | This message type is used by frontends to ask the kernel to execute code on |
|
133 | This message type is used by frontends to ask the kernel to execute code on | |
134 | behalf of the user, in a namespace reserved to the user's variables (and thus |
|
134 | behalf of the user, in a namespace reserved to the user's variables (and thus | |
135 | separate from the kernel's own internal code and variables). |
|
135 | separate from the kernel's own internal code and variables). | |
136 |
|
136 | |||
137 | Message type: ``execute_request``:: |
|
137 | Message type: ``execute_request``:: | |
138 |
|
138 | |||
139 | content = { |
|
139 | content = { | |
140 | # Source code to be executed by the kernel, one or more lines. |
|
140 | # Source code to be executed by the kernel, one or more lines. | |
141 | 'code' : str, |
|
141 | 'code' : str, | |
142 |
|
142 | |||
143 | # A boolean flag which, if True, signals the kernel to execute this |
|
143 | # A boolean flag which, if True, signals the kernel to execute this | |
144 | # code as quietly as possible. This means that the kernel will compile |
|
144 | # code as quietly as possible. This means that the kernel will compile | |
145 | # the code witIPython/core/tests/h 'exec' instead of 'single' (so |
|
145 | # the code witIPython/core/tests/h 'exec' instead of 'single' (so | |
146 | # sys.displayhook will not fire), and will *not*: |
|
146 | # sys.displayhook will not fire), and will *not*: | |
147 | # - broadcast exceptions on the PUB socket |
|
147 | # - broadcast exceptions on the PUB socket | |
148 | # - do any logging |
|
148 | # - do any logging | |
149 | # - populate any history |
|
149 | # - populate any history | |
150 | # |
|
150 | # | |
151 | # The default is False. |
|
151 | # The default is False. | |
152 | 'silent' : bool, |
|
152 | 'silent' : bool, | |
153 |
|
153 | |||
154 | # A list of variable names from the user's namespace to be retrieved. What |
|
154 | # A list of variable names from the user's namespace to be retrieved. What | |
155 | # returns is a JSON string of the variable's repr(), not a python object. |
|
155 | # returns is a JSON string of the variable's repr(), not a python object. | |
156 | 'user_variables' : list, |
|
156 | 'user_variables' : list, | |
157 |
|
157 | |||
158 | # Similarly, a dict mapping names to expressions to be evaluated in the |
|
158 | # Similarly, a dict mapping names to expressions to be evaluated in the | |
159 | # user's dict. |
|
159 | # user's dict. | |
160 | 'user_expressions' : dict, |
|
160 | 'user_expressions' : dict, | |
161 | } |
|
161 | } | |
162 |
|
162 | |||
163 | The ``code`` field contains a single string (possibly multiline). The kernel |
|
163 | The ``code`` field contains a single string (possibly multiline). The kernel | |
164 | is responsible for splitting this into one or more independent execution blocks |
|
164 | is responsible for splitting this into one or more independent execution blocks | |
165 | and deciding whether to compile these in 'single' or 'exec' mode (see below for |
|
165 | and deciding whether to compile these in 'single' or 'exec' mode (see below for | |
166 | detailed execution semantics). |
|
166 | detailed execution semantics). | |
167 |
|
167 | |||
168 | The ``user_`` fields deserve a detailed explanation. In the past, IPython had |
|
168 | The ``user_`` fields deserve a detailed explanation. In the past, IPython had | |
169 | the notion of a prompt string that allowed arbitrary code to be evaluated, and |
|
169 | the notion of a prompt string that allowed arbitrary code to be evaluated, and | |
170 | this was put to good use by many in creating prompts that displayed system |
|
170 | this was put to good use by many in creating prompts that displayed system | |
171 | status, path information, and even more esoteric uses like remote instrument |
|
171 | status, path information, and even more esoteric uses like remote instrument | |
172 | status aqcuired over the network. But now that IPython has a clean separation |
|
172 | status aqcuired over the network. But now that IPython has a clean separation | |
173 | between the kernel and the clients, the kernel has no prompt knowledge; prompts |
|
173 | between the kernel and the clients, the kernel has no prompt knowledge; prompts | |
174 | are a frontend-side feature, and it should be even possible for different |
|
174 | are a frontend-side feature, and it should be even possible for different | |
175 | frontends to display different prompts while interacting with the same kernel. |
|
175 | frontends to display different prompts while interacting with the same kernel. | |
176 |
|
176 | |||
177 | The kernel now provides the ability to retrieve data from the user's namespace |
|
177 | The kernel now provides the ability to retrieve data from the user's namespace | |
178 | after the execution of the main ``code``, thanks to two fields in the |
|
178 | after the execution of the main ``code``, thanks to two fields in the | |
179 | ``execute_request`` message: |
|
179 | ``execute_request`` message: | |
180 |
|
180 | |||
181 | - ``user_variables``: If only variables from the user's namespace are needed, a |
|
181 | - ``user_variables``: If only variables from the user's namespace are needed, a | |
182 | list of variable names can be passed and a dict with these names as keys and |
|
182 | list of variable names can be passed and a dict with these names as keys and | |
183 | their :func:`repr()` as values will be returned. |
|
183 | their :func:`repr()` as values will be returned. | |
184 |
|
184 | |||
185 | - ``user_expressions``: For more complex expressions that require function |
|
185 | - ``user_expressions``: For more complex expressions that require function | |
186 | evaluations, a dict can be provided with string keys and arbitrary python |
|
186 | evaluations, a dict can be provided with string keys and arbitrary python | |
187 | expressions as values. The return message will contain also a dict with the |
|
187 | expressions as values. The return message will contain also a dict with the | |
188 | same keys and the :func:`repr()` of the evaluated expressions as value. |
|
188 | same keys and the :func:`repr()` of the evaluated expressions as value. | |
189 |
|
189 | |||
190 | With this information, frontends can display any status information they wish |
|
190 | With this information, frontends can display any status information they wish | |
191 | in the form that best suits each frontend (a status line, a popup, inline for a |
|
191 | in the form that best suits each frontend (a status line, a popup, inline for a | |
192 | terminal, etc). |
|
192 | terminal, etc). | |
193 |
|
193 | |||
194 | .. Note:: |
|
194 | .. Note:: | |
195 |
|
195 | |||
196 | In order to obtain the current execution counter for the purposes of |
|
196 | In order to obtain the current execution counter for the purposes of | |
197 | displaying input prompts, frontends simply make an execution request with an |
|
197 | displaying input prompts, frontends simply make an execution request with an | |
198 | empty code string and ``silent=True``. |
|
198 | empty code string and ``silent=True``. | |
199 |
|
199 | |||
200 | Execution semantics |
|
200 | Execution semantics | |
201 | ~~~~~~~~~~~~~~~~~~~ |
|
201 | ~~~~~~~~~~~~~~~~~~~ | |
202 |
|
202 | |||
203 | When the silent flag is false, the execution of use code consists of the |
|
203 | When the silent flag is false, the execution of use code consists of the | |
204 | following phases (in silent mode, only the ``code`` field is executed): |
|
204 | following phases (in silent mode, only the ``code`` field is executed): | |
205 |
|
205 | |||
206 | 1. Run the ``pre_runcode_hook``. |
|
206 | 1. Run the ``pre_runcode_hook``. | |
207 |
|
207 | |||
208 | 2. Execute the ``code`` field, see below for details. |
|
208 | 2. Execute the ``code`` field, see below for details. | |
209 |
|
209 | |||
210 | 3. If #2 succeeds, compute ``user_variables`` and ``user_expressions`` are |
|
210 | 3. If #2 succeeds, compute ``user_variables`` and ``user_expressions`` are | |
211 | computed. This ensures that any error in the latter don't harm the main |
|
211 | computed. This ensures that any error in the latter don't harm the main | |
212 | code execution. |
|
212 | code execution. | |
213 |
|
213 | |||
214 | 4. Call any method registered with :meth:`register_post_execute`. |
|
214 | 4. Call any method registered with :meth:`register_post_execute`. | |
215 |
|
215 | |||
216 | .. warning:: |
|
216 | .. warning:: | |
217 |
|
217 | |||
218 | The API for running code before/after the main code block is likely to |
|
218 | The API for running code before/after the main code block is likely to | |
219 | change soon. Both the ``pre_runcode_hook`` and the |
|
219 | change soon. Both the ``pre_runcode_hook`` and the | |
220 | :meth:`register_post_execute` are susceptible to modification, as we find a |
|
220 | :meth:`register_post_execute` are susceptible to modification, as we find a | |
221 | consistent model for both. |
|
221 | consistent model for both. | |
222 |
|
222 | |||
223 | To understand how the ``code`` field is executed, one must know that Python |
|
223 | To understand how the ``code`` field is executed, one must know that Python | |
224 | code can be compiled in one of three modes (controlled by the ``mode`` argument |
|
224 | code can be compiled in one of three modes (controlled by the ``mode`` argument | |
225 | to the :func:`compile` builtin): |
|
225 | to the :func:`compile` builtin): | |
226 |
|
226 | |||
227 | *single* |
|
227 | *single* | |
228 | Valid for a single interactive statement (though the source can contain |
|
228 | Valid for a single interactive statement (though the source can contain | |
229 | multiple lines, such as a for loop). When compiled in this mode, the |
|
229 | multiple lines, such as a for loop). When compiled in this mode, the | |
230 | generated bytecode contains special instructions that trigger the calling of |
|
230 | generated bytecode contains special instructions that trigger the calling of | |
231 | :func:`sys.displayhook` for any expression in the block that returns a value. |
|
231 | :func:`sys.displayhook` for any expression in the block that returns a value. | |
232 | This means that a single statement can actually produce multiple calls to |
|
232 | This means that a single statement can actually produce multiple calls to | |
233 | :func:`sys.displayhook`, if for example it contains a loop where each |
|
233 | :func:`sys.displayhook`, if for example it contains a loop where each | |
234 | iteration computes an unassigned expression would generate 10 calls:: |
|
234 | iteration computes an unassigned expression would generate 10 calls:: | |
235 |
|
235 | |||
236 | for i in range(10): |
|
236 | for i in range(10): | |
237 | i**2 |
|
237 | i**2 | |
238 |
|
238 | |||
239 | *exec* |
|
239 | *exec* | |
240 | An arbitrary amount of source code, this is how modules are compiled. |
|
240 | An arbitrary amount of source code, this is how modules are compiled. | |
241 | :func:`sys.displayhook` is *never* implicitly called. |
|
241 | :func:`sys.displayhook` is *never* implicitly called. | |
242 |
|
242 | |||
243 | *eval* |
|
243 | *eval* | |
244 | A single expression that returns a value. :func:`sys.displayhook` is *never* |
|
244 | A single expression that returns a value. :func:`sys.displayhook` is *never* | |
245 | implicitly called. |
|
245 | implicitly called. | |
246 |
|
246 | |||
247 |
|
247 | |||
248 | The ``code`` field is split into individual blocks each of which is valid for |
|
248 | The ``code`` field is split into individual blocks each of which is valid for | |
249 | execution in 'single' mode, and then: |
|
249 | execution in 'single' mode, and then: | |
250 |
|
250 | |||
251 | - If there is only a single block: it is executed in 'single' mode. |
|
251 | - If there is only a single block: it is executed in 'single' mode. | |
252 |
|
252 | |||
253 | - If there is more than one block: |
|
253 | - If there is more than one block: | |
254 |
|
254 | |||
255 | * if the last one is a single line long, run all but the last in 'exec' mode |
|
255 | * if the last one is a single line long, run all but the last in 'exec' mode | |
256 | and the very last one in 'single' mode. This makes it easy to type simple |
|
256 | and the very last one in 'single' mode. This makes it easy to type simple | |
257 | expressions at the end to see computed values. |
|
257 | expressions at the end to see computed values. | |
258 |
|
258 | |||
259 | * if the last one is no more than two lines long, run all but the last in |
|
259 | * if the last one is no more than two lines long, run all but the last in | |
260 | 'exec' mode and the very last one in 'single' mode. This makes it easy to |
|
260 | 'exec' mode and the very last one in 'single' mode. This makes it easy to | |
261 | type simple expressions at the end to see computed values. - otherwise |
|
261 | type simple expressions at the end to see computed values. - otherwise | |
262 | (last one is also multiline), run all in 'exec' mode |
|
262 | (last one is also multiline), run all in 'exec' mode | |
263 |
|
263 | |||
264 | * otherwise (last one is also multiline), run all in 'exec' mode as a single |
|
264 | * otherwise (last one is also multiline), run all in 'exec' mode as a single | |
265 | unit. |
|
265 | unit. | |
266 |
|
266 | |||
267 | Any error in retrieving the ``user_variables`` or evaluating the |
|
267 | Any error in retrieving the ``user_variables`` or evaluating the | |
268 | ``user_expressions`` will result in a simple error message in the return fields |
|
268 | ``user_expressions`` will result in a simple error message in the return fields | |
269 | of the form:: |
|
269 | of the form:: | |
270 |
|
270 | |||
271 | [ERROR] ExceptionType: Exception message |
|
271 | [ERROR] ExceptionType: Exception message | |
272 |
|
272 | |||
273 | The user can simply send the same variable name or expression for evaluation to |
|
273 | The user can simply send the same variable name or expression for evaluation to | |
274 | see a regular traceback. |
|
274 | see a regular traceback. | |
275 |
|
275 | |||
276 | Errors in any registered post_execute functions are also reported similarly, |
|
276 | Errors in any registered post_execute functions are also reported similarly, | |
277 | and the failing function is removed from the post_execution set so that it does |
|
277 | and the failing function is removed from the post_execution set so that it does | |
278 | not continue triggering failures. |
|
278 | not continue triggering failures. | |
279 |
|
279 | |||
280 | Upon completion of the execution request, the kernel *always* sends a reply, |
|
280 | Upon completion of the execution request, the kernel *always* sends a reply, | |
281 | with a status code indicating what happened and additional data depending on |
|
281 | with a status code indicating what happened and additional data depending on | |
282 | the outcome. See :ref:`below <execution_results>` for the possible return |
|
282 | the outcome. See :ref:`below <execution_results>` for the possible return | |
283 | codes and associated data. |
|
283 | codes and associated data. | |
284 |
|
284 | |||
285 |
|
285 | |||
286 | Execution counter (old prompt number) |
|
286 | Execution counter (old prompt number) | |
287 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
287 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
288 |
|
288 | |||
289 | The kernel has a single, monotonically increasing counter of all execution |
|
289 | The kernel has a single, monotonically increasing counter of all execution | |
290 | requests that are made with ``silent=False``. This counter is used to populate |
|
290 | requests that are made with ``silent=False``. This counter is used to populate | |
291 | the ``In[n]``, ``Out[n]`` and ``_n`` variables, so clients will likely want to |
|
291 | the ``In[n]``, ``Out[n]`` and ``_n`` variables, so clients will likely want to | |
292 | display it in some form to the user, which will typically (but not necessarily) |
|
292 | display it in some form to the user, which will typically (but not necessarily) | |
293 | be done in the prompts. The value of this counter will be returned as the |
|
293 | be done in the prompts. The value of this counter will be returned as the | |
294 | ``execution_count`` field of all ``execute_reply`` messages. |
|
294 | ``execution_count`` field of all ``execute_reply`` messages. | |
295 |
|
295 | |||
296 | .. _execution_results: |
|
296 | .. _execution_results: | |
297 |
|
297 | |||
298 | Execution results |
|
298 | Execution results | |
299 | ~~~~~~~~~~~~~~~~~ |
|
299 | ~~~~~~~~~~~~~~~~~ | |
300 |
|
300 | |||
301 | Message type: ``execute_reply``:: |
|
301 | Message type: ``execute_reply``:: | |
302 |
|
302 | |||
303 | content = { |
|
303 | content = { | |
304 | # One of: 'ok' OR 'error' OR 'abort' |
|
304 | # One of: 'ok' OR 'error' OR 'abort' | |
305 | 'status' : str, |
|
305 | 'status' : str, | |
306 |
|
306 | |||
307 | # The global kernel counter that increases by one with each non-silent |
|
307 | # The global kernel counter that increases by one with each non-silent | |
308 | # executed request. This will typically be used by clients to display |
|
308 | # executed request. This will typically be used by clients to display | |
309 | # prompt numbers to the user. If the request was a silent one, this will |
|
309 | # prompt numbers to the user. If the request was a silent one, this will | |
310 | # be the current value of the counter in the kernel. |
|
310 | # be the current value of the counter in the kernel. | |
311 | 'execution_count' : int, |
|
311 | 'execution_count' : int, | |
312 | } |
|
312 | } | |
313 |
|
313 | |||
314 | When status is 'ok', the following extra fields are present:: |
|
314 | When status is 'ok', the following extra fields are present:: | |
315 |
|
315 | |||
316 | { |
|
316 | { | |
317 | # The execution payload is a dict with string keys that may have been |
|
317 | # The execution payload is a dict with string keys that may have been | |
318 | # produced by the code being executed. It is retrieved by the kernel at |
|
318 | # produced by the code being executed. It is retrieved by the kernel at | |
319 | # the end of the execution and sent back to the front end, which can take |
|
319 | # the end of the execution and sent back to the front end, which can take | |
320 | # action on it as needed. See main text for further details. |
|
320 | # action on it as needed. See main text for further details. | |
321 | 'payload' : dict, |
|
321 | 'payload' : dict, | |
322 |
|
322 | |||
323 | # Results for the user_variables and user_expressions. |
|
323 | # Results for the user_variables and user_expressions. | |
324 | 'user_variables' : dict, |
|
324 | 'user_variables' : dict, | |
325 | 'user_expressions' : dict, |
|
325 | 'user_expressions' : dict, | |
326 |
|
326 | |||
327 | # The kernel will often transform the input provided to it. If the |
|
327 | # The kernel will often transform the input provided to it. If the | |
328 | # '---->' transform had been applied, this is filled, otherwise it's the |
|
328 | # '---->' transform had been applied, this is filled, otherwise it's the | |
329 | # empty string. So transformations like magics don't appear here, only |
|
329 | # empty string. So transformations like magics don't appear here, only | |
330 | # autocall ones. |
|
330 | # autocall ones. | |
331 | 'transformed_code' : str, |
|
331 | 'transformed_code' : str, | |
332 | } |
|
332 | } | |
333 |
|
333 | |||
334 | .. admonition:: Execution payloads |
|
334 | .. admonition:: Execution payloads | |
335 |
|
335 | |||
336 | The notion of an 'execution payload' is different from a return value of a |
|
336 | The notion of an 'execution payload' is different from a return value of a | |
337 | given set of code, which normally is just displayed on the pyout stream |
|
337 | given set of code, which normally is just displayed on the pyout stream | |
338 | through the PUB socket. The idea of a payload is to allow special types of |
|
338 | through the PUB socket. The idea of a payload is to allow special types of | |
339 | code, typically magics, to populate a data container in the IPython kernel |
|
339 | code, typically magics, to populate a data container in the IPython kernel | |
340 | that will be shipped back to the caller via this channel. The kernel will |
|
340 | that will be shipped back to the caller via this channel. The kernel will | |
341 | have an API for this, probably something along the lines of:: |
|
341 | have an API for this, probably something along the lines of:: | |
342 |
|
342 | |||
343 | ip.exec_payload_add(key, value) |
|
343 | ip.exec_payload_add(key, value) | |
344 |
|
344 | |||
345 | though this API is still in the design stages. The data returned in this |
|
345 | though this API is still in the design stages. The data returned in this | |
346 | payload will allow frontends to present special views of what just happened. |
|
346 | payload will allow frontends to present special views of what just happened. | |
347 |
|
347 | |||
348 |
|
348 | |||
349 | When status is 'error', the following extra fields are present:: |
|
349 | When status is 'error', the following extra fields are present:: | |
350 |
|
350 | |||
351 | { |
|
351 | { | |
352 | 'exc_name' : str, # Exception name, as a string |
|
352 | 'exc_name' : str, # Exception name, as a string | |
353 | 'exc_value' : str, # Exception value, as a string |
|
353 | 'exc_value' : str, # Exception value, as a string | |
354 |
|
354 | |||
355 | # The traceback will contain a list of frames, represented each as a |
|
355 | # The traceback will contain a list of frames, represented each as a | |
356 | # string. For now we'll stick to the existing design of ultraTB, which |
|
356 | # string. For now we'll stick to the existing design of ultraTB, which | |
357 | # controls exception level of detail statefully. But eventually we'll |
|
357 | # controls exception level of detail statefully. But eventually we'll | |
358 | # want to grow into a model where more information is collected and |
|
358 | # want to grow into a model where more information is collected and | |
359 | # packed into the traceback object, with clients deciding how little or |
|
359 | # packed into the traceback object, with clients deciding how little or | |
360 | # how much of it to unpack. But for now, let's start with a simple list |
|
360 | # how much of it to unpack. But for now, let's start with a simple list | |
361 | # of strings, since that requires only minimal changes to ultratb as |
|
361 | # of strings, since that requires only minimal changes to ultratb as | |
362 | # written. |
|
362 | # written. | |
363 | 'traceback' : list, |
|
363 | 'traceback' : list, | |
364 | } |
|
364 | } | |
365 |
|
365 | |||
366 |
|
366 | |||
367 | When status is 'abort', there are for now no additional data fields. This |
|
367 | When status is 'abort', there are for now no additional data fields. This | |
368 | happens when the kernel was interrupted by a signal. |
|
368 | happens when the kernel was interrupted by a signal. | |
369 |
|
369 | |||
370 | Kernel attribute access |
|
370 | Kernel attribute access | |
371 | ----------------------- |
|
371 | ----------------------- | |
372 |
|
372 | |||
373 | .. warning:: |
|
373 | .. warning:: | |
374 |
|
374 | |||
375 | This part of the messaging spec is not actually implemented in the kernel |
|
375 | This part of the messaging spec is not actually implemented in the kernel | |
376 | yet. |
|
376 | yet. | |
377 |
|
377 | |||
378 | While this protocol does not specify full RPC access to arbitrary methods of |
|
378 | While this protocol does not specify full RPC access to arbitrary methods of | |
379 | the kernel object, the kernel does allow read (and in some cases write) access |
|
379 | the kernel object, the kernel does allow read (and in some cases write) access | |
380 | to certain attributes. |
|
380 | to certain attributes. | |
381 |
|
381 | |||
382 | The policy for which attributes can be read is: any attribute of the kernel, or |
|
382 | The policy for which attributes can be read is: any attribute of the kernel, or | |
383 | its sub-objects, that belongs to a :class:`Configurable` object and has been |
|
383 | its sub-objects, that belongs to a :class:`Configurable` object and has been | |
384 | declared at the class-level with Traits validation, is in principle accessible |
|
384 | declared at the class-level with Traits validation, is in principle accessible | |
385 | as long as its name does not begin with a leading underscore. The attribute |
|
385 | as long as its name does not begin with a leading underscore. The attribute | |
386 | itself will have metadata indicating whether it allows remote read and/or write |
|
386 | itself will have metadata indicating whether it allows remote read and/or write | |
387 | access. The message spec follows for attribute read and write requests. |
|
387 | access. The message spec follows for attribute read and write requests. | |
388 |
|
388 | |||
389 | Message type: ``getattr_request``:: |
|
389 | Message type: ``getattr_request``:: | |
390 |
|
390 | |||
391 | content = { |
|
391 | content = { | |
392 | # The (possibly dotted) name of the attribute |
|
392 | # The (possibly dotted) name of the attribute | |
393 | 'name' : str, |
|
393 | 'name' : str, | |
394 | } |
|
394 | } | |
395 |
|
395 | |||
396 | When a ``getattr_request`` fails, there are two possible error types: |
|
396 | When a ``getattr_request`` fails, there are two possible error types: | |
397 |
|
397 | |||
398 | - AttributeError: this type of error was raised when trying to access the |
|
398 | - AttributeError: this type of error was raised when trying to access the | |
399 | given name by the kernel itself. This means that the attribute likely |
|
399 | given name by the kernel itself. This means that the attribute likely | |
400 | doesn't exist. |
|
400 | doesn't exist. | |
401 |
|
401 | |||
402 | - AccessError: the attribute exists but its value is not readable remotely. |
|
402 | - AccessError: the attribute exists but its value is not readable remotely. | |
403 |
|
403 | |||
404 |
|
404 | |||
405 | Message type: ``getattr_reply``:: |
|
405 | Message type: ``getattr_reply``:: | |
406 |
|
406 | |||
407 | content = { |
|
407 | content = { | |
408 | # One of ['ok', 'AttributeError', 'AccessError']. |
|
408 | # One of ['ok', 'AttributeError', 'AccessError']. | |
409 | 'status' : str, |
|
409 | 'status' : str, | |
410 | # If status is 'ok', a JSON object. |
|
410 | # If status is 'ok', a JSON object. | |
411 | 'value' : object, |
|
411 | 'value' : object, | |
412 | } |
|
412 | } | |
413 |
|
413 | |||
414 | Message type: ``setattr_request``:: |
|
414 | Message type: ``setattr_request``:: | |
415 |
|
415 | |||
416 | content = { |
|
416 | content = { | |
417 | # The (possibly dotted) name of the attribute |
|
417 | # The (possibly dotted) name of the attribute | |
418 | 'name' : str, |
|
418 | 'name' : str, | |
419 |
|
419 | |||
420 | # A JSON-encoded object, that will be validated by the Traits |
|
420 | # A JSON-encoded object, that will be validated by the Traits | |
421 | # information in the kernel |
|
421 | # information in the kernel | |
422 | 'value' : object, |
|
422 | 'value' : object, | |
423 | } |
|
423 | } | |
424 |
|
424 | |||
425 | When a ``setattr_request`` fails, there are also two possible error types with |
|
425 | When a ``setattr_request`` fails, there are also two possible error types with | |
426 | similar meanings as those of the ``getattr_request`` case, but for writing. |
|
426 | similar meanings as those of the ``getattr_request`` case, but for writing. | |
427 |
|
427 | |||
428 | Message type: ``setattr_reply``:: |
|
428 | Message type: ``setattr_reply``:: | |
429 |
|
429 | |||
430 | content = { |
|
430 | content = { | |
431 | # One of ['ok', 'AttributeError', 'AccessError']. |
|
431 | # One of ['ok', 'AttributeError', 'AccessError']. | |
432 | 'status' : str, |
|
432 | 'status' : str, | |
433 | } |
|
433 | } | |
434 |
|
434 | |||
435 |
|
435 | |||
436 |
|
436 | |||
437 | Object information |
|
437 | Object information | |
438 | ------------------ |
|
438 | ------------------ | |
439 |
|
439 | |||
440 | One of IPython's most used capabilities is the introspection of Python objects |
|
440 | One of IPython's most used capabilities is the introspection of Python objects | |
441 | in the user's namespace, typically invoked via the ``?`` and ``??`` characters |
|
441 | in the user's namespace, typically invoked via the ``?`` and ``??`` characters | |
442 | (which in reality are shorthands for the ``%pinfo`` magic). This is used often |
|
442 | (which in reality are shorthands for the ``%pinfo`` magic). This is used often | |
443 | enough that it warrants an explicit message type, especially because frontends |
|
443 | enough that it warrants an explicit message type, especially because frontends | |
444 | may want to get object information in response to user keystrokes (like Tab or |
|
444 | may want to get object information in response to user keystrokes (like Tab or | |
445 | F1) besides from the user explicitly typing code like ``x??``. |
|
445 | F1) besides from the user explicitly typing code like ``x??``. | |
446 |
|
446 | |||
447 | Message type: ``object_info_request``:: |
|
447 | Message type: ``object_info_request``:: | |
448 |
|
448 | |||
449 | content = { |
|
449 | content = { | |
450 | # The (possibly dotted) name of the object to be searched in all |
|
450 | # The (possibly dotted) name of the object to be searched in all | |
451 | # relevant namespaces |
|
451 | # relevant namespaces | |
452 | 'name' : str, |
|
452 | 'name' : str, | |
453 |
|
453 | |||
454 | # The level of detail desired. The default (0) is equivalent to typing |
|
454 | # The level of detail desired. The default (0) is equivalent to typing | |
455 | # 'x?' at the prompt, 1 is equivalent to 'x??'. |
|
455 | # 'x?' at the prompt, 1 is equivalent to 'x??'. | |
456 | 'detail_level' : int, |
|
456 | 'detail_level' : int, | |
457 | } |
|
457 | } | |
458 |
|
458 | |||
459 | The returned information will be a dictionary with keys very similar to the |
|
459 | The returned information will be a dictionary with keys very similar to the | |
460 | field names that IPython prints at the terminal. |
|
460 | field names that IPython prints at the terminal. | |
461 |
|
461 | |||
462 | Message type: ``object_info_reply``:: |
|
462 | Message type: ``object_info_reply``:: | |
463 |
|
463 | |||
464 | content = { |
|
464 | content = { | |
465 | # The name the object was requested under |
|
465 | # The name the object was requested under | |
466 | 'name' : str, |
|
466 | 'name' : str, | |
467 |
|
467 | |||
468 | # Boolean flag indicating whether the named object was found or not. If |
|
468 | # Boolean flag indicating whether the named object was found or not. If | |
469 | # it's false, all other fields will be empty. |
|
469 | # it's false, all other fields will be empty. | |
470 | 'found' : bool, |
|
470 | 'found' : bool, | |
471 |
|
471 | |||
472 | # Flags for magics and system aliases |
|
472 | # Flags for magics and system aliases | |
473 | 'ismagic' : bool, |
|
473 | 'ismagic' : bool, | |
474 | 'isalias' : bool, |
|
474 | 'isalias' : bool, | |
475 |
|
475 | |||
476 | # The name of the namespace where the object was found ('builtin', |
|
476 | # The name of the namespace where the object was found ('builtin', | |
477 | # 'magics', 'alias', 'interactive', etc.) |
|
477 | # 'magics', 'alias', 'interactive', etc.) | |
478 | 'namespace' : str, |
|
478 | 'namespace' : str, | |
479 |
|
479 | |||
480 | # The type name will be type.__name__ for normal Python objects, but it |
|
480 | # The type name will be type.__name__ for normal Python objects, but it | |
481 | # can also be a string like 'Magic function' or 'System alias' |
|
481 | # can also be a string like 'Magic function' or 'System alias' | |
482 | 'type_name' : str, |
|
482 | 'type_name' : str, | |
483 |
|
483 | |||
484 | 'string_form' : str, |
|
484 | 'string_form' : str, | |
485 |
|
485 | |||
486 | # For objects with a __class__ attribute this will be set |
|
486 | # For objects with a __class__ attribute this will be set | |
487 | 'base_class' : str, |
|
487 | 'base_class' : str, | |
488 |
|
488 | |||
489 | # For objects with a __len__ attribute this will be set |
|
489 | # For objects with a __len__ attribute this will be set | |
490 | 'length' : int, |
|
490 | 'length' : int, | |
491 |
|
491 | |||
492 | # If the object is a function, class or method whose file we can find, |
|
492 | # If the object is a function, class or method whose file we can find, | |
493 | # we give its full path |
|
493 | # we give its full path | |
494 | 'file' : str, |
|
494 | 'file' : str, | |
495 |
|
495 | |||
496 | # For pure Python callable objects, we can reconstruct the object |
|
496 | # For pure Python callable objects, we can reconstruct the object | |
497 | # definition line which provides its call signature. For convenience this |
|
497 | # definition line which provides its call signature. For convenience this | |
498 | # is returned as a single 'definition' field, but below the raw parts that |
|
498 | # is returned as a single 'definition' field, but below the raw parts that | |
499 | # compose it are also returned as the argspec field. |
|
499 | # compose it are also returned as the argspec field. | |
500 | 'definition' : str, |
|
500 | 'definition' : str, | |
501 |
|
501 | |||
502 | # The individual parts that together form the definition string. Clients |
|
502 | # The individual parts that together form the definition string. Clients | |
503 | # with rich display capabilities may use this to provide a richer and more |
|
503 | # with rich display capabilities may use this to provide a richer and more | |
504 | # precise representation of the definition line (e.g. by highlighting |
|
504 | # precise representation of the definition line (e.g. by highlighting | |
505 | # arguments based on the user's cursor position). For non-callable |
|
505 | # arguments based on the user's cursor position). For non-callable | |
506 | # objects, this field is empty. |
|
506 | # objects, this field is empty. | |
507 | 'argspec' : { # The names of all the arguments |
|
507 | 'argspec' : { # The names of all the arguments | |
508 | args : list, |
|
508 | args : list, | |
509 | # The name of the varargs (*args), if any |
|
509 | # The name of the varargs (*args), if any | |
510 | varargs : str, |
|
510 | varargs : str, | |
511 | # The name of the varkw (**kw), if any |
|
511 | # The name of the varkw (**kw), if any | |
512 | varkw : str, |
|
512 | varkw : str, | |
513 | # The values (as strings) of all default arguments. Note |
|
513 | # The values (as strings) of all default arguments. Note | |
514 | # that these must be matched *in reverse* with the 'args' |
|
514 | # that these must be matched *in reverse* with the 'args' | |
515 | # list above, since the first positional args have no default |
|
515 | # list above, since the first positional args have no default | |
516 | # value at all. |
|
516 | # value at all. | |
517 | defaults : list, |
|
517 | defaults : list, | |
518 | }, |
|
518 | }, | |
519 |
|
519 | |||
520 | # For instances, provide the constructor signature (the definition of |
|
520 | # For instances, provide the constructor signature (the definition of | |
521 | # the __init__ method): |
|
521 | # the __init__ method): | |
522 | 'init_definition' : str, |
|
522 | 'init_definition' : str, | |
523 |
|
523 | |||
524 | # Docstrings: for any object (function, method, module, package) with a |
|
524 | # Docstrings: for any object (function, method, module, package) with a | |
525 | # docstring, we show it. But in addition, we may provide additional |
|
525 | # docstring, we show it. But in addition, we may provide additional | |
526 | # docstrings. For example, for instances we will show the constructor |
|
526 | # docstrings. For example, for instances we will show the constructor | |
527 | # and class docstrings as well, if available. |
|
527 | # and class docstrings as well, if available. | |
528 | 'docstring' : str, |
|
528 | 'docstring' : str, | |
529 |
|
529 | |||
530 | # For instances, provide the constructor and class docstrings |
|
530 | # For instances, provide the constructor and class docstrings | |
531 | 'init_docstring' : str, |
|
531 | 'init_docstring' : str, | |
532 | 'class_docstring' : str, |
|
532 | 'class_docstring' : str, | |
533 |
|
533 | |||
534 | # If it's a callable object whose call method has a separate docstring and |
|
534 | # If it's a callable object whose call method has a separate docstring and | |
535 | # definition line: |
|
535 | # definition line: | |
536 | 'call_def' : str, |
|
536 | 'call_def' : str, | |
537 | 'call_docstring' : str, |
|
537 | 'call_docstring' : str, | |
538 |
|
538 | |||
539 | # If detail_level was 1, we also try to find the source code that |
|
539 | # If detail_level was 1, we also try to find the source code that | |
540 | # defines the object, if possible. The string 'None' will indicate |
|
540 | # defines the object, if possible. The string 'None' will indicate | |
541 | # that no source was found. |
|
541 | # that no source was found. | |
542 | 'source' : str, |
|
542 | 'source' : str, | |
543 | } |
|
543 | } | |
544 | ' |
|
544 | ' | |
545 |
|
545 | |||
546 | Complete |
|
546 | Complete | |
547 | -------- |
|
547 | -------- | |
548 |
|
548 | |||
549 | Message type: ``complete_request``:: |
|
549 | Message type: ``complete_request``:: | |
550 |
|
550 | |||
551 | content = { |
|
551 | content = { | |
552 | # The text to be completed, such as 'a.is' |
|
552 | # The text to be completed, such as 'a.is' | |
553 | 'text' : str, |
|
553 | 'text' : str, | |
554 |
|
554 | |||
555 | # The full line, such as 'print a.is'. This allows completers to |
|
555 | # The full line, such as 'print a.is'. This allows completers to | |
556 | # make decisions that may require information about more than just the |
|
556 | # make decisions that may require information about more than just the | |
557 | # current word. |
|
557 | # current word. | |
558 | 'line' : str, |
|
558 | 'line' : str, | |
559 |
|
559 | |||
560 | # The entire block of text where the line is. This may be useful in the |
|
560 | # The entire block of text where the line is. This may be useful in the | |
561 | # case of multiline completions where more context may be needed. Note: if |
|
561 | # case of multiline completions where more context may be needed. Note: if | |
562 | # in practice this field proves unnecessary, remove it to lighten the |
|
562 | # in practice this field proves unnecessary, remove it to lighten the | |
563 | # messages. |
|
563 | # messages. | |
564 |
|
564 | |||
565 | 'block' : str, |
|
565 | 'block' : str, | |
566 |
|
566 | |||
567 | # The position of the cursor where the user hit 'TAB' on the line. |
|
567 | # The position of the cursor where the user hit 'TAB' on the line. | |
568 | 'cursor_pos' : int, |
|
568 | 'cursor_pos' : int, | |
569 | } |
|
569 | } | |
570 |
|
570 | |||
571 | Message type: ``complete_reply``:: |
|
571 | Message type: ``complete_reply``:: | |
572 |
|
572 | |||
573 | content = { |
|
573 | content = { | |
574 | # The list of all matches to the completion request, such as |
|
574 | # The list of all matches to the completion request, such as | |
575 | # ['a.isalnum', 'a.isalpha'] for the above example. |
|
575 | # ['a.isalnum', 'a.isalpha'] for the above example. | |
576 | 'matches' : list |
|
576 | 'matches' : list | |
577 | } |
|
577 | } | |
578 |
|
578 | |||
579 |
|
579 | |||
580 | History |
|
580 | History | |
581 | ------- |
|
581 | ------- | |
582 |
|
582 | |||
583 | For clients to explicitly request history from a kernel. The kernel has all |
|
583 | For clients to explicitly request history from a kernel. The kernel has all | |
584 | the actual execution history stored in a single location, so clients can |
|
584 | the actual execution history stored in a single location, so clients can | |
585 | request it from the kernel when needed. |
|
585 | request it from the kernel when needed. | |
586 |
|
586 | |||
587 | Message type: ``history_request``:: |
|
587 | Message type: ``history_request``:: | |
588 |
|
588 | |||
589 | content = { |
|
589 | content = { | |
590 |
|
590 | |||
591 | # If True, also return output history in the resulting dict. |
|
591 | # If True, also return output history in the resulting dict. | |
592 | 'output' : bool, |
|
592 | 'output' : bool, | |
593 |
|
593 | |||
594 | # If True, return the raw input history, else the transformed input. |
|
594 | # If True, return the raw input history, else the transformed input. | |
595 | 'raw' : bool, |
|
595 | 'raw' : bool, | |
596 |
|
596 | |||
597 | # This parameter can be one of: A number, a pair of numbers, None |
|
597 | # This parameter can be one of: A number, a pair of numbers, None | |
598 | # If not given, last 40 are returned. |
|
598 | # If not given, last 40 are returned. | |
599 | # - number n: return the last n entries. |
|
599 | # - number n: return the last n entries. | |
600 | # - pair n1, n2: return entries in the range(n1, n2). |
|
600 | # - pair n1, n2: return entries in the range(n1, n2). | |
601 | # - None: return all history |
|
601 | # - None: return all history | |
602 | 'index' : n or (n1, n2) or None, |
|
602 | 'index' : n or (n1, n2) or None, | |
603 | } |
|
603 | } | |
604 |
|
604 | |||
605 | Message type: ``history_reply``:: |
|
605 | Message type: ``history_reply``:: | |
606 |
|
606 | |||
607 | content = { |
|
607 | content = { | |
608 | # A dict with prompt numbers as keys and either (input, output) or input |
|
608 | # A dict with prompt numbers as keys and either (input, output) or input | |
609 | # as the value depending on whether output was True or False, |
|
609 | # as the value depending on whether output was True or False, | |
610 | # respectively. |
|
610 | # respectively. | |
611 | 'history' : dict, |
|
611 | 'history' : dict, | |
612 | } |
|
612 | } | |
613 |
|
613 | |||
614 |
|
614 | |||
615 | Connect |
|
615 | Connect | |
616 | ------- |
|
616 | ------- | |
617 |
|
617 | |||
618 | When a client connects to the request/reply socket of the kernel, it can issue |
|
618 | When a client connects to the request/reply socket of the kernel, it can issue | |
619 | a connect request to get basic information about the kernel, such as the ports |
|
619 | a connect request to get basic information about the kernel, such as the ports | |
620 | the other ZeroMQ sockets are listening on. This allows clients to only have |
|
620 | the other ZeroMQ sockets are listening on. This allows clients to only have | |
621 | to know about a single port (the XREQ/XREP channel) to connect to a kernel. |
|
621 | to know about a single port (the XREQ/XREP channel) to connect to a kernel. | |
622 |
|
622 | |||
623 | Message type: ``connect_request``:: |
|
623 | Message type: ``connect_request``:: | |
624 |
|
624 | |||
625 | content = { |
|
625 | content = { | |
626 | } |
|
626 | } | |
627 |
|
627 | |||
628 | Message type: ``connect_reply``:: |
|
628 | Message type: ``connect_reply``:: | |
629 |
|
629 | |||
630 | content = { |
|
630 | content = { | |
631 | 'xrep_port' : int # The port the XREP socket is listening on. |
|
631 | 'xrep_port' : int # The port the XREP socket is listening on. | |
632 | 'pub_port' : int # The port the PUB socket is listening on. |
|
632 | 'pub_port' : int # The port the PUB socket is listening on. | |
633 | 'req_port' : int # The port the REQ socket is listening on. |
|
633 | 'req_port' : int # The port the REQ socket is listening on. | |
634 | 'hb_port' : int # The port the heartbeat socket is listening on. |
|
634 | 'hb_port' : int # The port the heartbeat socket is listening on. | |
635 | } |
|
635 | } | |
636 |
|
636 | |||
637 |
|
637 | |||
638 |
|
638 | |||
639 | Kernel shutdown |
|
639 | Kernel shutdown | |
640 | --------------- |
|
640 | --------------- | |
641 |
|
641 | |||
642 | The clients can request the kernel to shut itself down; this is used in |
|
642 | The clients can request the kernel to shut itself down; this is used in | |
643 | multiple cases: |
|
643 | multiple cases: | |
644 |
|
644 | |||
645 | - when the user chooses to close the client application via a menu or window |
|
645 | - when the user chooses to close the client application via a menu or window | |
646 | control. |
|
646 | control. | |
647 | - when the user types 'exit' or 'quit' (or their uppercase magic equivalents). |
|
647 | - when the user types 'exit' or 'quit' (or their uppercase magic equivalents). | |
648 | - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the |
|
648 | - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the | |
649 | IPythonQt client) to force a kernel restart to get a clean kernel without |
|
649 | IPythonQt client) to force a kernel restart to get a clean kernel without | |
650 | losing client-side state like history or inlined figures. |
|
650 | losing client-side state like history or inlined figures. | |
651 |
|
651 | |||
652 | The client sends a shutdown request to the kernel, and once it receives the |
|
652 | The client sends a shutdown request to the kernel, and once it receives the | |
653 | reply message (which is otherwise empty), it can assume that the kernel has |
|
653 | reply message (which is otherwise empty), it can assume that the kernel has | |
654 | completed shutdown safely. |
|
654 | completed shutdown safely. | |
655 |
|
655 | |||
656 | Upon their own shutdown, client applications will typically execute a last |
|
656 | Upon their own shutdown, client applications will typically execute a last | |
657 | minute sanity check and forcefully terminate any kernel that is still alive, to |
|
657 | minute sanity check and forcefully terminate any kernel that is still alive, to | |
658 | avoid leaving stray processes in the user's machine. |
|
658 | avoid leaving stray processes in the user's machine. | |
659 |
|
659 | |||
660 | For both shutdown request and reply, there is no actual content that needs to |
|
660 | For both shutdown request and reply, there is no actual content that needs to | |
661 | be sent, so the content dict is empty. |
|
661 | be sent, so the content dict is empty. | |
662 |
|
662 | |||
663 | Message type: ``shutdown_request``:: |
|
663 | Message type: ``shutdown_request``:: | |
664 |
|
664 | |||
665 | content = { |
|
665 | content = { | |
666 | 'restart' : bool # whether the shutdown is final, or precedes a restart |
|
666 | 'restart' : bool # whether the shutdown is final, or precedes a restart | |
667 | } |
|
667 | } | |
668 |
|
668 | |||
669 | Message type: ``shutdown_reply``:: |
|
669 | Message type: ``shutdown_reply``:: | |
670 |
|
670 | |||
671 | content = { |
|
671 | content = { | |
672 | 'restart' : bool # whether the shutdown is final, or precedes a restart |
|
672 | 'restart' : bool # whether the shutdown is final, or precedes a restart | |
673 | } |
|
673 | } | |
674 |
|
674 | |||
675 | .. Note:: |
|
675 | .. Note:: | |
676 |
|
676 | |||
677 | When the clients detect a dead kernel thanks to inactivity on the heartbeat |
|
677 | When the clients detect a dead kernel thanks to inactivity on the heartbeat | |
678 | socket, they simply send a forceful process termination signal, since a dead |
|
678 | socket, they simply send a forceful process termination signal, since a dead | |
679 | process is unlikely to respond in any useful way to messages. |
|
679 | process is unlikely to respond in any useful way to messages. | |
680 |
|
680 | |||
681 |
|
681 | |||
682 | Messages on the PUB/SUB socket |
|
682 | Messages on the PUB/SUB socket | |
683 | ============================== |
|
683 | ============================== | |
684 |
|
684 | |||
685 | Streams (stdout, stderr, etc) |
|
685 | Streams (stdout, stderr, etc) | |
686 | ------------------------------ |
|
686 | ------------------------------ | |
687 |
|
687 | |||
688 | Message type: ``stream``:: |
|
688 | Message type: ``stream``:: | |
689 |
|
689 | |||
690 | content = { |
|
690 | content = { | |
691 | # The name of the stream is one of 'stdin', 'stdout', 'stderr' |
|
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 |
|
694 | # The data is an arbitrary string to be written to that stream | |
695 | 'data' : str, |
|
695 | 'data' : str, | |
696 | } |
|
696 | } | |
697 |
|
697 | |||
698 | When a kernel receives a raw_input call, it should also broadcast it on the pub |
|
698 | When a kernel receives a raw_input call, it should also broadcast it on the pub | |
699 | socket with the names 'stdin' and 'stdin_reply'. This will allow other clients |
|
699 | socket with the names 'stdin' and 'stdin_reply'. This will allow other clients | |
700 | to monitor/display kernel interactions and possibly replay them to their user |
|
700 | to monitor/display kernel interactions and possibly replay them to their user | |
701 | or otherwise expose them. |
|
701 | or otherwise expose them. | |
702 |
|
702 | |||
703 | Display Data |
|
703 | Display Data | |
704 | ------------ |
|
704 | ------------ | |
705 |
|
705 | |||
706 | This type of message is used to bring back data that should be diplayed (text, |
|
706 | This type of message is used to bring back data that should be diplayed (text, | |
707 | html, svg, etc.) in the frontends. This data is published to all frontends. |
|
707 | html, svg, etc.) in the frontends. This data is published to all frontends. | |
708 | Each message can have multiple representations of the data; it is up to the |
|
708 | Each message can have multiple representations of the data; it is up to the | |
709 | frontend to decide which to use and how. A single message should contain all |
|
709 | frontend to decide which to use and how. A single message should contain all | |
710 | possible representations of the same information. Each representation should |
|
710 | possible representations of the same information. Each representation should | |
711 | be a JSON'able data structure, and should be a valid MIME type. |
|
711 | be a JSON'able data structure, and should be a valid MIME type. | |
712 |
|
712 | |||
713 | Some questions remain about this design: |
|
713 | Some questions remain about this design: | |
714 |
|
714 | |||
715 | * Do we use this message type for pyout/displayhook? Probably not, because |
|
715 | * Do we use this message type for pyout/displayhook? Probably not, because | |
716 | the displayhook also has to handle the Out prompt display. On the other hand |
|
716 | the displayhook also has to handle the Out prompt display. On the other hand | |
717 | we could put that information into the metadata secion. |
|
717 | we could put that information into the metadata secion. | |
718 |
|
718 | |||
719 | Message type: ``display_data``:: |
|
719 | Message type: ``display_data``:: | |
720 |
|
720 | |||
721 | content = { |
|
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, |
|
723 | # Who create the data | |
730 | but not keyed by anything. |
|
724 | 'source' : str, | |
731 | content = { |
|
|||
732 | 'data' = [(source, type, data), (source, type, data)] |
|
|||
733 | 'metadata' = dict |
|
|||
734 | } |
|
|||
735 |
|
725 | |||
736 | # Option 3: like option 2, but keyed by the MIME types. |
|
726 | # The data dict contains key/value pairs, where the kids are MIME | |
737 | content = { |
|
727 | # types and the values are the raw data of the representation in that | |
738 | 'data' = {'mimetype1' : (source, data), 'mimetype2' : (source, data)} |
|
728 | # format. The data dict must minimally contain the ``text/plain`` | |
739 | 'metadata' = dict |
|
729 | # MIME type which is used as a backup representation. | |
740 | } |
|
730 | 'data' : dict, | |
741 |
|
731 | |||
742 | # Option 4: like option 2, but keyed by the source. |
|
732 | # Any metadata that describes the data | |
743 | content = { |
|
733 | 'metadata' : dict | |
744 | 'data' = {'source' : (mimetype, data), 'source' : (mimetype, data)} |
|
|||
745 | 'metadata' = dict |
|
|||
746 | } |
|
734 | } | |
747 |
|
735 | |||
748 | Python inputs |
|
736 | Python inputs | |
749 | ------------- |
|
737 | ------------- | |
750 |
|
738 | |||
751 | These messages are the re-broadcast of the ``execute_request``. |
|
739 | These messages are the re-broadcast of the ``execute_request``. | |
752 |
|
740 | |||
753 | Message type: ``pyin``:: |
|
741 | Message type: ``pyin``:: | |
754 |
|
742 | |||
755 | content = { |
|
743 | content = { | |
756 | 'code' : str # Source code to be executed, one or more lines |
|
744 | 'code' : str # Source code to be executed, one or more lines | |
757 | } |
|
745 | } | |
758 |
|
746 | |||
759 | Python outputs |
|
747 | Python outputs | |
760 | -------------- |
|
748 | -------------- | |
761 |
|
749 | |||
762 | When Python produces output from code that has been compiled in with the |
|
750 | When Python produces output from code that has been compiled in with the | |
763 | 'single' flag to :func:`compile`, any expression that produces a value (such as |
|
751 | 'single' flag to :func:`compile`, any expression that produces a value (such as | |
764 | ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with |
|
752 | ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with | |
765 | this value whatever it wants. The default behavior of ``sys.displayhook`` in |
|
753 | this value whatever it wants. The default behavior of ``sys.displayhook`` in | |
766 | the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of |
|
754 | the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of | |
767 | the value as long as it is not ``None`` (which isn't printed at all). In our |
|
755 | the value as long as it is not ``None`` (which isn't printed at all). In our | |
768 | case, the kernel instantiates as ``sys.displayhook`` an object which has |
|
756 | case, the kernel instantiates as ``sys.displayhook`` an object which has | |
769 | similar behavior, but which instead of printing to stdout, broadcasts these |
|
757 | similar behavior, but which instead of printing to stdout, broadcasts these | |
770 | values as ``pyout`` messages for clients to display appropriately. |
|
758 | values as ``pyout`` messages for clients to display appropriately. | |
771 |
|
759 | |||
772 | IPython's displayhook can handle multiple simultaneous formats depending on its |
|
760 | IPython's displayhook can handle multiple simultaneous formats depending on its | |
773 | configuration. The default pretty-printed repr text is always given with the |
|
761 | configuration. The default pretty-printed repr text is always given with the | |
774 | ``data`` entry in this message. Any other formats are provided in the |
|
762 | ``data`` entry in this message. Any other formats are provided in the | |
775 | ``extra_formats`` list. Frontends are free to display any or all of these |
|
763 | ``extra_formats`` list. Frontends are free to display any or all of these | |
776 | according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID |
|
764 | according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID | |
777 | string, a type string, and the data. The ID is unique to the formatter |
|
765 | string, a type string, and the data. The ID is unique to the formatter | |
778 | implementation that created the data. Frontends will typically ignore the ID |
|
766 | implementation that created the data. Frontends will typically ignore the ID | |
779 | unless if it has requested a particular formatter. The type string tells the |
|
767 | unless if it has requested a particular formatter. The type string tells the | |
780 | frontend how to interpret the data. It is often, but not always a MIME type. |
|
768 | frontend how to interpret the data. It is often, but not always a MIME type. | |
781 | Frontends should ignore types that it does not understand. The data itself is |
|
769 | Frontends should ignore types that it does not understand. The data itself is | |
782 | any JSON object and depends on the format. It is often, but not always a string. |
|
770 | any JSON object and depends on the format. It is often, but not always a string. | |
783 |
|
771 | |||
784 | Message type: ``pyout``:: |
|
772 | Message type: ``pyout``:: | |
785 |
|
773 | |||
786 | content = { |
|
774 | content = { | |
787 | # The data is typically the repr() of the object. It should be displayed |
|
775 | ||
788 | # as monospaced text. |
|
|||
789 | 'data' : str, |
|
|||
790 |
|
||||
791 | # The counter for this execution is also provided so that clients can |
|
776 | # The counter for this execution is also provided so that clients can | |
792 | # display it, since IPython automatically creates variables called _N |
|
777 | # display it, since IPython automatically creates variables called _N | |
793 | # (for prompt N). |
|
778 | # (for prompt N). | |
794 | 'execution_count' : int, |
|
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 | Python errors |
|
789 | Python errors | |
804 | ------------- |
|
790 | ------------- | |
805 |
|
791 | |||
806 | When an error occurs during code execution |
|
792 | When an error occurs during code execution | |
807 |
|
793 | |||
808 | Message type: ``pyerr``:: |
|
794 | Message type: ``pyerr``:: | |
809 |
|
795 | |||
810 | content = { |
|
796 | content = { | |
811 | # Similar content to the execute_reply messages for the 'error' case, |
|
797 | # Similar content to the execute_reply messages for the 'error' case, | |
812 | # except the 'status' field is omitted. |
|
798 | # except the 'status' field is omitted. | |
813 | } |
|
799 | } | |
814 |
|
800 | |||
815 | Kernel status |
|
801 | Kernel status | |
816 | ------------- |
|
802 | ------------- | |
817 |
|
803 | |||
818 | This message type is used by frontends to monitor the status of the kernel. |
|
804 | This message type is used by frontends to monitor the status of the kernel. | |
819 |
|
805 | |||
820 | Message type: ``status``:: |
|
806 | Message type: ``status``:: | |
821 |
|
807 | |||
822 | content = { |
|
808 | content = { | |
823 | # When the kernel starts to execute code, it will enter the 'busy' |
|
809 | # When the kernel starts to execute code, it will enter the 'busy' | |
824 | # state and when it finishes, it will enter the 'idle' state. |
|
810 | # state and when it finishes, it will enter the 'idle' state. | |
825 | execution_state : ('busy', 'idle') |
|
811 | execution_state : ('busy', 'idle') | |
826 | } |
|
812 | } | |
827 |
|
813 | |||
828 | Kernel crashes |
|
814 | Kernel crashes | |
829 | -------------- |
|
815 | -------------- | |
830 |
|
816 | |||
831 | When the kernel has an unexpected exception, caught by the last-resort |
|
817 | When the kernel has an unexpected exception, caught by the last-resort | |
832 | sys.excepthook, we should broadcast the crash handler's output before exiting. |
|
818 | sys.excepthook, we should broadcast the crash handler's output before exiting. | |
833 | This will allow clients to notice that a kernel died, inform the user and |
|
819 | This will allow clients to notice that a kernel died, inform the user and | |
834 | propose further actions. |
|
820 | propose further actions. | |
835 |
|
821 | |||
836 | Message type: ``crash``:: |
|
822 | Message type: ``crash``:: | |
837 |
|
823 | |||
838 | content = { |
|
824 | content = { | |
839 | # Similarly to the 'error' case for execute_reply messages, this will |
|
825 | # Similarly to the 'error' case for execute_reply messages, this will | |
840 | # contain exc_name, exc_type and traceback fields. |
|
826 | # contain exc_name, exc_type and traceback fields. | |
841 |
|
827 | |||
842 | # An additional field with supplementary information such as where to |
|
828 | # An additional field with supplementary information such as where to | |
843 | # send the crash message |
|
829 | # send the crash message | |
844 | 'info' : str, |
|
830 | 'info' : str, | |
845 | } |
|
831 | } | |
846 |
|
832 | |||
847 |
|
833 | |||
848 | Future ideas |
|
834 | Future ideas | |
849 | ------------ |
|
835 | ------------ | |
850 |
|
836 | |||
851 | Other potential message types, currently unimplemented, listed below as ideas. |
|
837 | Other potential message types, currently unimplemented, listed below as ideas. | |
852 |
|
838 | |||
853 | Message type: ``file``:: |
|
839 | Message type: ``file``:: | |
854 |
|
840 | |||
855 | content = { |
|
841 | content = { | |
856 | 'path' : 'cool.jpg', |
|
842 | 'path' : 'cool.jpg', | |
857 | 'mimetype' : str, |
|
843 | 'mimetype' : str, | |
858 | 'data' : str, |
|
844 | 'data' : str, | |
859 | } |
|
845 | } | |
860 |
|
846 | |||
861 |
|
847 | |||
862 | Messages on the REQ/REP socket |
|
848 | Messages on the REQ/REP socket | |
863 | ============================== |
|
849 | ============================== | |
864 |
|
850 | |||
865 | This is a socket that goes in the opposite direction: from the kernel to a |
|
851 | This is a socket that goes in the opposite direction: from the kernel to a | |
866 | *single* frontend, and its purpose is to allow ``raw_input`` and similar |
|
852 | *single* frontend, and its purpose is to allow ``raw_input`` and similar | |
867 | operations that read from ``sys.stdin`` on the kernel to be fulfilled by the |
|
853 | operations that read from ``sys.stdin`` on the kernel to be fulfilled by the | |
868 | client. For now we will keep these messages as simple as possible, since they |
|
854 | client. For now we will keep these messages as simple as possible, since they | |
869 | basically only mean to convey the ``raw_input(prompt)`` call. |
|
855 | basically only mean to convey the ``raw_input(prompt)`` call. | |
870 |
|
856 | |||
871 | Message type: ``input_request``:: |
|
857 | Message type: ``input_request``:: | |
872 |
|
858 | |||
873 | content = { 'prompt' : str } |
|
859 | content = { 'prompt' : str } | |
874 |
|
860 | |||
875 | Message type: ``input_reply``:: |
|
861 | Message type: ``input_reply``:: | |
876 |
|
862 | |||
877 | content = { 'value' : str } |
|
863 | content = { 'value' : str } | |
878 |
|
864 | |||
879 | .. Note:: |
|
865 | .. Note:: | |
880 |
|
866 | |||
881 | We do not explicitly try to forward the raw ``sys.stdin`` object, because in |
|
867 | We do not explicitly try to forward the raw ``sys.stdin`` object, because in | |
882 | practice the kernel should behave like an interactive program. When a |
|
868 | practice the kernel should behave like an interactive program. When a | |
883 | program is opened on the console, the keyboard effectively takes over the |
|
869 | program is opened on the console, the keyboard effectively takes over the | |
884 | ``stdin`` file descriptor, and it can't be used for raw reading anymore. |
|
870 | ``stdin`` file descriptor, and it can't be used for raw reading anymore. | |
885 | Since the IPython kernel effectively behaves like a console program (albeit |
|
871 | Since the IPython kernel effectively behaves like a console program (albeit | |
886 | one whose "keyboard" is actually living in a separate process and |
|
872 | one whose "keyboard" is actually living in a separate process and | |
887 | transported over the zmq connection), raw ``stdin`` isn't expected to be |
|
873 | transported over the zmq connection), raw ``stdin`` isn't expected to be | |
888 | available. |
|
874 | available. | |
889 |
|
875 | |||
890 |
|
876 | |||
891 | Heartbeat for kernels |
|
877 | Heartbeat for kernels | |
892 | ===================== |
|
878 | ===================== | |
893 |
|
879 | |||
894 | Initially we had considered using messages like those above over ZMQ for a |
|
880 | Initially we had considered using messages like those above over ZMQ for a | |
895 | kernel 'heartbeat' (a way to detect quickly and reliably whether a kernel is |
|
881 | kernel 'heartbeat' (a way to detect quickly and reliably whether a kernel is | |
896 | alive at all, even if it may be busy executing user code). But this has the |
|
882 | alive at all, even if it may be busy executing user code). But this has the | |
897 | problem that if the kernel is locked inside extension code, it wouldn't execute |
|
883 | problem that if the kernel is locked inside extension code, it wouldn't execute | |
898 | the python heartbeat code. But it turns out that we can implement a basic |
|
884 | the python heartbeat code. But it turns out that we can implement a basic | |
899 | heartbeat with pure ZMQ, without using any Python messaging at all. |
|
885 | heartbeat with pure ZMQ, without using any Python messaging at all. | |
900 |
|
886 | |||
901 | The monitor sends out a single zmq message (right now, it is a str of the |
|
887 | The monitor sends out a single zmq message (right now, it is a str of the | |
902 | monitor's lifetime in seconds), and gets the same message right back, prefixed |
|
888 | monitor's lifetime in seconds), and gets the same message right back, prefixed | |
903 | with the zmq identity of the XREQ socket in the heartbeat process. This can be |
|
889 | with the zmq identity of the XREQ socket in the heartbeat process. This can be | |
904 | a uuid, or even a full message, but there doesn't seem to be a need for packing |
|
890 | a uuid, or even a full message, but there doesn't seem to be a need for packing | |
905 | up a message when the sender and receiver are the exact same Python object. |
|
891 | up a message when the sender and receiver are the exact same Python object. | |
906 |
|
892 | |||
907 | The model is this:: |
|
893 | The model is this:: | |
908 |
|
894 | |||
909 | monitor.send(str(self.lifetime)) # '1.2345678910' |
|
895 | monitor.send(str(self.lifetime)) # '1.2345678910' | |
910 |
|
896 | |||
911 | and the monitor receives some number of messages of the form:: |
|
897 | and the monitor receives some number of messages of the form:: | |
912 |
|
898 | |||
913 | ['uuid-abcd-dead-beef', '1.2345678910'] |
|
899 | ['uuid-abcd-dead-beef', '1.2345678910'] | |
914 |
|
900 | |||
915 | where the first part is the zmq.IDENTITY of the heart's XREQ on the engine, and |
|
901 | where the first part is the zmq.IDENTITY of the heart's XREQ on the engine, and | |
916 | the rest is the message sent by the monitor. No Python code ever has any |
|
902 | the rest is the message sent by the monitor. No Python code ever has any | |
917 | access to the message between the monitor's send, and the monitor's recv. |
|
903 | access to the message between the monitor's send, and the monitor's recv. | |
918 |
|
904 | |||
919 |
|
905 | |||
920 | ToDo |
|
906 | ToDo | |
921 | ==== |
|
907 | ==== | |
922 |
|
908 | |||
923 | Missing things include: |
|
909 | Missing things include: | |
924 |
|
910 | |||
925 | * Important: finish thinking through the payload concept and API. |
|
911 | * Important: finish thinking through the payload concept and API. | |
926 |
|
912 | |||
927 | * Important: ensure that we have a good solution for magics like %edit. It's |
|
913 | * Important: ensure that we have a good solution for magics like %edit. It's | |
928 | likely that with the payload concept we can build a full solution, but not |
|
914 | likely that with the payload concept we can build a full solution, but not | |
929 | 100% clear yet. |
|
915 | 100% clear yet. | |
930 |
|
916 | |||
931 | * Finishing the details of the heartbeat protocol. |
|
917 | * Finishing the details of the heartbeat protocol. | |
932 |
|
918 | |||
933 | * Signal handling: specify what kind of information kernel should broadcast (or |
|
919 | * Signal handling: specify what kind of information kernel should broadcast (or | |
934 | not) when it receives signals. |
|
920 | not) when it receives signals. | |
935 |
|
921 | |||
936 | .. include:: ../links.rst |
|
922 | .. include:: ../links.rst |
General Comments 0
You need to be logged in to leave comments.
Login now