Show More
@@ -1,331 +1,330 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Displayhook for IPython. |
|
2 | """Displayhook for IPython. | |
3 |
|
3 | |||
4 | This defines a callable class that IPython uses for `sys.displayhook`. |
|
4 | This defines a callable class that IPython uses for `sys.displayhook`. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Fernando Perez |
|
8 | * Fernando Perez | |
9 | * Brian Granger |
|
9 | * Brian Granger | |
10 | * Robert Kern |
|
10 | * Robert Kern | |
11 | """ |
|
11 | """ | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Copyright (C) 2008-2010 The IPython Development Team |
|
14 | # Copyright (C) 2008-2010 The IPython Development Team | |
15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
16 | # |
|
16 | # | |
17 | # 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 | |
18 | # the file COPYING, distributed as part of this software. |
|
18 | # the file COPYING, distributed as part of this software. | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 | # Imports |
|
22 | # Imports | |
23 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
24 |
|
24 | |||
25 | import __builtin__ |
|
25 | import __builtin__ | |
26 |
|
26 | |||
27 | from IPython.config.configurable import Configurable |
|
27 | from IPython.config.configurable import Configurable | |
28 | from IPython.core import prompts |
|
28 | from IPython.core import prompts | |
29 | import IPython.utils.generics |
|
29 | import IPython.utils.generics | |
30 | import IPython.utils.io |
|
30 | import IPython.utils.io | |
31 | from IPython.utils.traitlets import Instance, List |
|
31 | from IPython.utils.traitlets import Instance, List | |
32 | from IPython.utils.warn import warn |
|
32 | from IPython.utils.warn import warn | |
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # Main displayhook class |
|
35 | # Main displayhook class | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 | # 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 | |
39 | # 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 | |
40 | # displayhook logic and calls into the prompt manager. |
|
40 | # displayhook logic and calls into the prompt manager. | |
41 |
|
41 | |||
42 | # TODO: Move the various attributes (cache_size, colors, input_sep, |
|
42 | # TODO: Move the various attributes (cache_size, colors, input_sep, | |
43 | # 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 | |
44 | # 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 | |
45 | # other objects should ask that one object for their values. |
|
45 | # other objects should ask that one object for their values. | |
46 |
|
46 | |||
47 | class DisplayHook(Configurable): |
|
47 | class DisplayHook(Configurable): | |
48 | """The custom IPython displayhook to replace sys.displayhook. |
|
48 | """The custom IPython displayhook to replace sys.displayhook. | |
49 |
|
49 | |||
50 | 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 | |
51 | that gets called anytime user code returns a value. |
|
51 | that gets called anytime user code returns a value. | |
52 |
|
52 | |||
53 | 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 | |
54 | extra logic should eventually be moved out of here. |
|
54 | extra logic should eventually be moved out of here. | |
55 | """ |
|
55 | """ | |
56 |
|
56 | |||
57 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
57 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
58 |
|
58 | |||
59 | def __init__(self, shell=None, cache_size=1000, |
|
59 | def __init__(self, shell=None, cache_size=1000, | |
60 | colors='NoColor', input_sep='\n', |
|
60 | colors='NoColor', input_sep='\n', | |
61 | output_sep='\n', output_sep2='', |
|
61 | output_sep='\n', output_sep2='', | |
62 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, |
|
62 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, | |
63 | config=None): |
|
63 | config=None): | |
64 | super(DisplayHook, self).__init__(shell=shell, config=config) |
|
64 | super(DisplayHook, self).__init__(shell=shell, config=config) | |
65 |
|
65 | |||
66 | cache_size_min = 3 |
|
66 | cache_size_min = 3 | |
67 | if cache_size <= 0: |
|
67 | if cache_size <= 0: | |
68 | self.do_full_cache = 0 |
|
68 | self.do_full_cache = 0 | |
69 | cache_size = 0 |
|
69 | cache_size = 0 | |
70 | elif cache_size < cache_size_min: |
|
70 | elif cache_size < cache_size_min: | |
71 | self.do_full_cache = 0 |
|
71 | self.do_full_cache = 0 | |
72 | cache_size = 0 |
|
72 | cache_size = 0 | |
73 | warn('caching was disabled (min value for cache size is %s).' % |
|
73 | warn('caching was disabled (min value for cache size is %s).' % | |
74 | cache_size_min,level=3) |
|
74 | cache_size_min,level=3) | |
75 | else: |
|
75 | else: | |
76 | self.do_full_cache = 1 |
|
76 | self.do_full_cache = 1 | |
77 |
|
77 | |||
78 | self.cache_size = cache_size |
|
78 | self.cache_size = cache_size | |
79 | self.input_sep = input_sep |
|
79 | self.input_sep = input_sep | |
80 |
|
80 | |||
81 | # we need a reference to the user-level namespace |
|
81 | # we need a reference to the user-level namespace | |
82 | self.shell = shell |
|
82 | self.shell = shell | |
83 |
|
83 | |||
84 | # Set input prompt strings and colors |
|
84 | # Set input prompt strings and colors | |
85 | if cache_size == 0: |
|
85 | if cache_size == 0: | |
86 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ |
|
86 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ | |
87 | or ps1.find(r'\N') > -1: |
|
87 | or ps1.find(r'\N') > -1: | |
88 | ps1 = '>>> ' |
|
88 | ps1 = '>>> ' | |
89 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ |
|
89 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ | |
90 | or ps2.find(r'\N') > -1: |
|
90 | or ps2.find(r'\N') > -1: | |
91 | ps2 = '... ' |
|
91 | ps2 = '... ' | |
92 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') |
|
92 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') | |
93 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') |
|
93 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') | |
94 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') |
|
94 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') | |
95 |
|
95 | |||
96 | self.color_table = prompts.PromptColors |
|
96 | self.color_table = prompts.PromptColors | |
97 | 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, | |
98 | pad_left=pad_left) |
|
98 | pad_left=pad_left) | |
99 | 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) | |
100 | 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, | |
101 | pad_left=pad_left) |
|
101 | pad_left=pad_left) | |
102 | self.set_colors(colors) |
|
102 | self.set_colors(colors) | |
103 |
|
103 | |||
104 | # 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 | |
105 | # continuation and auto-rewrite prompts |
|
105 | # continuation and auto-rewrite prompts | |
106 | self.last_prompt = '' |
|
106 | self.last_prompt = '' | |
107 | self.output_sep = output_sep |
|
107 | self.output_sep = output_sep | |
108 | self.output_sep2 = output_sep2 |
|
108 | self.output_sep2 = output_sep2 | |
109 | self._,self.__,self.___ = '','','' |
|
109 | self._,self.__,self.___ = '','','' | |
110 |
|
110 | |||
111 | # these are deliberately global: |
|
111 | # these are deliberately global: | |
112 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
112 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} | |
113 | self.shell.user_ns.update(to_user_ns) |
|
113 | self.shell.user_ns.update(to_user_ns) | |
114 |
|
114 | |||
115 | @property |
|
115 | @property | |
116 | def prompt_count(self): |
|
116 | def prompt_count(self): | |
117 | return self.shell.execution_count |
|
117 | return self.shell.execution_count | |
118 |
|
118 | |||
119 | 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): | |
120 | if p_str is None: |
|
120 | if p_str is None: | |
121 | if self.do_full_cache: |
|
121 | if self.do_full_cache: | |
122 | return cache_def |
|
122 | return cache_def | |
123 | else: |
|
123 | else: | |
124 | return no_cache_def |
|
124 | return no_cache_def | |
125 | else: |
|
125 | else: | |
126 | return p_str |
|
126 | return p_str | |
127 |
|
127 | |||
128 | def set_colors(self, colors): |
|
128 | def set_colors(self, colors): | |
129 | """Set the active color scheme and configure colors for the three |
|
129 | """Set the active color scheme and configure colors for the three | |
130 | prompt subsystems.""" |
|
130 | prompt subsystems.""" | |
131 |
|
131 | |||
132 | # FIXME: This modifying of the global prompts.prompt_specials needs |
|
132 | # FIXME: This modifying of the global prompts.prompt_specials needs | |
133 | # 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 | |
134 | # proper configuration and traits notifications. |
|
134 | # proper configuration and traits notifications. | |
135 | if colors.lower()=='nocolor': |
|
135 | if colors.lower()=='nocolor': | |
136 | prompts.prompt_specials = prompts.prompt_specials_nocolor |
|
136 | prompts.prompt_specials = prompts.prompt_specials_nocolor | |
137 | else: |
|
137 | else: | |
138 | prompts.prompt_specials = prompts.prompt_specials_color |
|
138 | prompts.prompt_specials = prompts.prompt_specials_color | |
139 |
|
139 | |||
140 | self.color_table.set_active_scheme(colors) |
|
140 | self.color_table.set_active_scheme(colors) | |
141 | self.prompt1.set_colors() |
|
141 | self.prompt1.set_colors() | |
142 | self.prompt2.set_colors() |
|
142 | self.prompt2.set_colors() | |
143 | self.prompt_out.set_colors() |
|
143 | self.prompt_out.set_colors() | |
144 |
|
144 | |||
145 | #------------------------------------------------------------------------- |
|
145 | #------------------------------------------------------------------------- | |
146 | # Methods used in __call__. Override these methods to modify the behavior |
|
146 | # Methods used in __call__. Override these methods to modify the behavior | |
147 | # of the displayhook. |
|
147 | # of the displayhook. | |
148 | #------------------------------------------------------------------------- |
|
148 | #------------------------------------------------------------------------- | |
149 |
|
149 | |||
150 | def check_for_underscore(self): |
|
150 | def check_for_underscore(self): | |
151 | """Check if the user has set the '_' variable by hand.""" |
|
151 | """Check if the user has set the '_' variable by hand.""" | |
152 | # If something injected a '_' variable in __builtin__, delete |
|
152 | # If something injected a '_' variable in __builtin__, delete | |
153 | # 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 | |
154 | # particular uses _, so we need to stay away from it. |
|
154 | # particular uses _, so we need to stay away from it. | |
155 | if '_' in __builtin__.__dict__: |
|
155 | if '_' in __builtin__.__dict__: | |
156 | try: |
|
156 | try: | |
157 | del self.shell.user_ns['_'] |
|
157 | del self.shell.user_ns['_'] | |
158 | except KeyError: |
|
158 | except KeyError: | |
159 | pass |
|
159 | pass | |
160 |
|
160 | |||
161 | def quiet(self): |
|
161 | def quiet(self): | |
162 | """Should we silence the display hook because of ';'?""" |
|
162 | """Should we silence the display hook because of ';'?""" | |
163 | # do not print output if input ends in ';' |
|
163 | # do not print output if input ends in ';' | |
164 | try: |
|
164 | try: | |
165 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] |
|
165 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] | |
166 | if cell.rstrip().endswith(';'): |
|
166 | if cell.rstrip().endswith(';'): | |
167 | return True |
|
167 | return True | |
168 | except IndexError: |
|
168 | except IndexError: | |
169 | # some uses of ipshellembed may fail here |
|
169 | # some uses of ipshellembed may fail here | |
170 | pass |
|
170 | pass | |
171 | return False |
|
171 | return False | |
172 |
|
172 | |||
173 | def start_displayhook(self): |
|
173 | def start_displayhook(self): | |
174 | """Start the displayhook, initializing resources.""" |
|
174 | """Start the displayhook, initializing resources.""" | |
175 | pass |
|
175 | pass | |
176 |
|
176 | |||
177 | def write_output_prompt(self): |
|
177 | def write_output_prompt(self): | |
178 | """Write the output prompt. |
|
178 | """Write the output prompt. | |
179 |
|
179 | |||
180 | The default implementation simply writes the prompt to |
|
180 | The default implementation simply writes the prompt to | |
181 | ``io.Term.cout``. |
|
181 | ``io.Term.cout``. | |
182 | """ |
|
182 | """ | |
183 | # Use write, not print which adds an extra space. |
|
183 | # Use write, not print which adds an extra space. | |
184 | IPython.utils.io.Term.cout.write(self.output_sep) |
|
184 | IPython.utils.io.Term.cout.write(self.output_sep) | |
185 | outprompt = str(self.prompt_out) |
|
185 | outprompt = str(self.prompt_out) | |
186 | if self.do_full_cache: |
|
186 | if self.do_full_cache: | |
187 | IPython.utils.io.Term.cout.write(outprompt) |
|
187 | IPython.utils.io.Term.cout.write(outprompt) | |
188 |
|
188 | |||
189 | def compute_format_data(self, result): |
|
189 | def compute_format_data(self, result): | |
190 | """Compute format data of the object to be displayed. |
|
190 | """Compute format data of the object to be displayed. | |
191 |
|
191 | |||
192 | The format data is a generalization of the :func:`repr` of an object. |
|
192 | The format data is a generalization of the :func:`repr` of an object. | |
193 | In the default implementation the format data is a :class:`dict` of |
|
193 | In the default implementation the format data is a :class:`dict` of | |
194 | key value pair where the keys are valid MIME types and the values |
|
194 | key value pair where the keys are valid MIME types and the values | |
195 | are JSON'able data structure containing the raw data for that MIME |
|
195 | are JSON'able data structure containing the raw data for that MIME | |
196 | type. It is up to frontends to determine pick a MIME to to use and |
|
196 | type. It is up to frontends to determine pick a MIME to to use and | |
197 | display that data in an appropriate manner. |
|
197 | display that data in an appropriate manner. | |
198 |
|
198 | |||
199 | This method only computes the format data for the object and should |
|
199 | This method only computes the format data for the object and should | |
200 | NOT actually print or write that to a stream. |
|
200 | NOT actually print or write that to a stream. | |
201 |
|
201 | |||
202 | Parameters |
|
202 | Parameters | |
203 | ---------- |
|
203 | ---------- | |
204 | result : object |
|
204 | result : object | |
205 | The Python object passed to the display hook, whose format will be |
|
205 | The Python object passed to the display hook, whose format will be | |
206 | computed. |
|
206 | computed. | |
207 |
|
207 | |||
208 | Returns |
|
208 | Returns | |
209 | ------- |
|
209 | ------- | |
210 | format_data : dict |
|
210 | format_data : dict | |
211 | A :class:`dict` whose keys are valid MIME types and values are |
|
211 | A :class:`dict` whose keys are valid MIME types and values are | |
212 | JSON'able raw data for that MIME type. It is recommended that |
|
212 | JSON'able raw data for that MIME type. It is recommended that | |
213 | all return values of this should always include the "text/plain" |
|
213 | all return values of this should always include the "text/plain" | |
214 | MIME type representation of the object. |
|
214 | MIME type representation of the object. | |
215 | """ |
|
215 | """ | |
216 | return self.shell.display_formatter.format(result) |
|
216 | return self.shell.display_formatter.format(result) | |
217 |
|
217 | |||
218 | def write_format_data(self, format_dict): |
|
218 | def write_format_data(self, format_dict): | |
219 | """Write the format data dict to the frontend. |
|
219 | """Write the format data dict to the frontend. | |
220 |
|
220 | |||
221 | This default version of this method simply writes the plain text |
|
221 | This default version of this method simply writes the plain text | |
222 | representation of the object to ``io.Term.cout``. Subclasses should |
|
222 | representation of the object to ``io.Term.cout``. Subclasses should | |
223 | override this method to send the entire `format_dict` to the |
|
223 | override this method to send the entire `format_dict` to the | |
224 | frontends. |
|
224 | frontends. | |
225 |
|
225 | |||
226 | Parameters |
|
226 | Parameters | |
227 | ---------- |
|
227 | ---------- | |
228 | format_dict : dict |
|
228 | format_dict : dict | |
229 | The format dict for the object passed to `sys.displayhook`. |
|
229 | The format dict for the object passed to `sys.displayhook`. | |
230 | """ |
|
230 | """ | |
231 | # 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 | |
232 | # newline, even if all the prompt separators are ''. This is the |
|
232 | # newline, even if all the prompt separators are ''. This is the | |
233 | # standard IPython behavior. |
|
233 | # standard IPython behavior. | |
234 | result_repr = format_dict['text/plain'] |
|
234 | result_repr = format_dict['text/plain'] | |
235 | if '\n' in result_repr: |
|
235 | if '\n' in result_repr: | |
236 | # 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 | |
237 | # the screen, instead of having the output prompt mess up |
|
237 | # the screen, instead of having the output prompt mess up | |
238 | # their first line. |
|
238 | # their first line. | |
239 | # 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 | |
240 | # because the expansion may add ANSI escapes that will interfere |
|
240 | # because the expansion may add ANSI escapes that will interfere | |
241 | # with our ability to determine whether or not we should add |
|
241 | # with our ability to determine whether or not we should add | |
242 | # a newline. |
|
242 | # a newline. | |
243 | 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'): | |
244 | # But avoid extraneous empty lines. |
|
244 | # But avoid extraneous empty lines. | |
245 | result_repr = '\n' + result_repr |
|
245 | result_repr = '\n' + result_repr | |
246 |
|
246 | |||
247 | print >>IPython.utils.io.Term.cout, result_repr |
|
247 | print >>IPython.utils.io.Term.cout, result_repr | |
248 |
|
248 | |||
249 | def update_user_ns(self, result): |
|
249 | def update_user_ns(self, result): | |
250 | """Update user_ns with various things like _, __, _1, etc.""" |
|
250 | """Update user_ns with various things like _, __, _1, etc.""" | |
251 |
|
251 | |||
252 | # Avoid recursive reference when displaying _oh/Out |
|
252 | # Avoid recursive reference when displaying _oh/Out | |
253 | if result is not self.shell.user_ns['_oh']: |
|
253 | if result is not self.shell.user_ns['_oh']: | |
254 | 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: | |
255 | warn('Output cache limit (currently '+ |
|
255 | warn('Output cache limit (currently '+ | |
256 | `self.cache_size`+' entries) hit.\n' |
|
256 | `self.cache_size`+' entries) hit.\n' | |
257 | 'Flushing cache and resetting history counter...\n' |
|
257 | 'Flushing cache and resetting history counter...\n' | |
258 | 'The only history variables available will be _,__,___ and _1\n' |
|
258 | 'The only history variables available will be _,__,___ and _1\n' | |
259 | 'with the current result.') |
|
259 | 'with the current result.') | |
260 |
|
260 | |||
261 | self.flush() |
|
261 | self.flush() | |
262 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
262 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise | |
263 | # we cause buggy behavior for things like gettext). |
|
263 | # we cause buggy behavior for things like gettext). | |
264 |
|
264 | |||
265 | if '_' not in __builtin__.__dict__: |
|
265 | if '_' not in __builtin__.__dict__: | |
266 | self.___ = self.__ |
|
266 | self.___ = self.__ | |
267 | self.__ = self._ |
|
267 | self.__ = self._ | |
268 | self._ = result |
|
268 | self._ = result | |
269 | self.shell.user_ns.update({'_':self._, |
|
269 | self.shell.user_ns.update({'_':self._, | |
270 | '__':self.__, |
|
270 | '__':self.__, | |
271 | '___':self.___}) |
|
271 | '___':self.___}) | |
272 |
|
272 | |||
273 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
273 | # hackish access to top-level namespace to create _1,_2... dynamically | |
274 | to_main = {} |
|
274 | to_main = {} | |
275 | if self.do_full_cache: |
|
275 | if self.do_full_cache: | |
276 | new_result = '_'+`self.prompt_count` |
|
276 | new_result = '_'+`self.prompt_count` | |
277 | to_main[new_result] = result |
|
277 | to_main[new_result] = result | |
278 | self.shell.user_ns.update(to_main) |
|
278 | self.shell.user_ns.update(to_main) | |
279 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
279 | self.shell.user_ns['_oh'][self.prompt_count] = result | |
280 |
|
280 | |||
281 | def log_output(self, format_dict): |
|
281 | def log_output(self, format_dict): | |
282 | """Log the output.""" |
|
282 | """Log the output.""" | |
283 | if self.shell.logger.log_output: |
|
283 | if self.shell.logger.log_output: | |
284 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
284 | self.shell.logger.log_write(format_dict['text/plain'], 'output') | |
285 | # This is a defaultdict of lists, so we can always append |
|
285 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ | |
286 | self.shell.history_manager.output_hist_reprs[self.prompt_count]\ |
|
286 | format_dict['text/plain'] | |
287 | .append(format_dict['text/plain']) |
|
|||
288 |
|
287 | |||
289 | def finish_displayhook(self): |
|
288 | def finish_displayhook(self): | |
290 | """Finish up all displayhook activities.""" |
|
289 | """Finish up all displayhook activities.""" | |
291 | IPython.utils.io.Term.cout.write(self.output_sep2) |
|
290 | IPython.utils.io.Term.cout.write(self.output_sep2) | |
292 | IPython.utils.io.Term.cout.flush() |
|
291 | IPython.utils.io.Term.cout.flush() | |
293 |
|
292 | |||
294 | def __call__(self, result=None): |
|
293 | def __call__(self, result=None): | |
295 | """Printing with history cache management. |
|
294 | """Printing with history cache management. | |
296 |
|
295 | |||
297 | This is invoked everytime the interpreter needs to print, and is |
|
296 | This is invoked everytime the interpreter needs to print, and is | |
298 | activated by setting the variable sys.displayhook to it. |
|
297 | activated by setting the variable sys.displayhook to it. | |
299 | """ |
|
298 | """ | |
300 | self.check_for_underscore() |
|
299 | self.check_for_underscore() | |
301 | if result is not None and not self.quiet(): |
|
300 | if result is not None and not self.quiet(): | |
302 | self.start_displayhook() |
|
301 | self.start_displayhook() | |
303 | self.write_output_prompt() |
|
302 | self.write_output_prompt() | |
304 | format_dict = self.compute_format_data(result) |
|
303 | format_dict = self.compute_format_data(result) | |
305 | self.write_format_data(format_dict) |
|
304 | self.write_format_data(format_dict) | |
306 | self.update_user_ns(result) |
|
305 | self.update_user_ns(result) | |
307 | self.log_output(format_dict) |
|
306 | self.log_output(format_dict) | |
308 | self.finish_displayhook() |
|
307 | self.finish_displayhook() | |
309 |
|
308 | |||
310 | def flush(self): |
|
309 | def flush(self): | |
311 | if not self.do_full_cache: |
|
310 | if not self.do_full_cache: | |
312 | raise ValueError,"You shouldn't have reached the cache flush "\ |
|
311 | raise ValueError,"You shouldn't have reached the cache flush "\ | |
313 | "if full caching is not enabled!" |
|
312 | "if full caching is not enabled!" | |
314 | # delete auto-generated vars from global namespace |
|
313 | # delete auto-generated vars from global namespace | |
315 |
|
314 | |||
316 | for n in range(1,self.prompt_count + 1): |
|
315 | for n in range(1,self.prompt_count + 1): | |
317 | key = '_'+`n` |
|
316 | key = '_'+`n` | |
318 | try: |
|
317 | try: | |
319 | del self.shell.user_ns[key] |
|
318 | del self.shell.user_ns[key] | |
320 | except: pass |
|
319 | except: pass | |
321 | self.shell.user_ns['_oh'].clear() |
|
320 | self.shell.user_ns['_oh'].clear() | |
322 |
|
321 | |||
323 | # Release our own references to objects: |
|
322 | # Release our own references to objects: | |
324 | self._, self.__, self.___ = '', '', '' |
|
323 | self._, self.__, self.___ = '', '', '' | |
325 |
|
324 | |||
326 | if '_' not in __builtin__.__dict__: |
|
325 | if '_' not in __builtin__.__dict__: | |
327 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
326 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) | |
328 | import gc |
|
327 | import gc | |
329 | # TODO: Is this really needed? |
|
328 | # TODO: Is this really needed? | |
330 | gc.collect() |
|
329 | gc.collect() | |
331 |
|
330 |
@@ -1,810 +1,803 b'' | |||||
1 | """ History related magics and functionality """ |
|
1 | """ History related magics and functionality """ | |
2 | #----------------------------------------------------------------------------- |
|
2 | #----------------------------------------------------------------------------- | |
3 | # Copyright (C) 2010 The IPython Development Team. |
|
3 | # Copyright (C) 2010 The IPython Development Team. | |
4 | # |
|
4 | # | |
5 | # Distributed under the terms of the BSD License. |
|
5 | # Distributed under the terms of the BSD License. | |
6 | # |
|
6 | # | |
7 | # The full license is in the file COPYING.txt, distributed with this software. |
|
7 | # The full license is in the file COPYING.txt, distributed with this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | from __future__ import print_function |
|
13 | from __future__ import print_function | |
14 |
|
14 | |||
15 | # Stdlib imports |
|
15 | # Stdlib imports | |
16 | import atexit |
|
16 | import atexit | |
17 | import datetime |
|
17 | import datetime | |
18 | import json |
|
|||
19 | import os |
|
18 | import os | |
20 | import re |
|
19 | import re | |
21 | import sqlite3 |
|
20 | import sqlite3 | |
22 | import threading |
|
21 | import threading | |
23 |
|
22 | |||
24 | from collections import defaultdict |
|
|||
25 |
|
||||
26 | # Our own packages |
|
23 | # Our own packages | |
27 | from IPython.config.configurable import Configurable |
|
24 | from IPython.config.configurable import Configurable | |
28 | import IPython.utils.io |
|
25 | import IPython.utils.io | |
29 |
|
26 | |||
30 | from IPython.testing import decorators as testdec |
|
27 | from IPython.testing import decorators as testdec | |
31 | from IPython.utils.io import ask_yes_no |
|
28 | from IPython.utils.io import ask_yes_no | |
32 | from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode |
|
29 | from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode | |
33 | from IPython.utils.warn import warn |
|
30 | from IPython.utils.warn import warn | |
34 |
|
31 | |||
35 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
36 | # Classes and functions |
|
33 | # Classes and functions | |
37 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
38 |
|
35 | |||
39 | class HistoryManager(Configurable): |
|
36 | class HistoryManager(Configurable): | |
40 | """A class to organize all history-related functionality in one place. |
|
37 | """A class to organize all history-related functionality in one place. | |
41 | """ |
|
38 | """ | |
42 | # Public interface |
|
39 | # Public interface | |
43 |
|
40 | |||
44 | # An instance of the IPython shell we are attached to |
|
41 | # An instance of the IPython shell we are attached to | |
45 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
42 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
46 | # Lists to hold processed and raw history. These start with a blank entry |
|
43 | # Lists to hold processed and raw history. These start with a blank entry | |
47 | # so that we can index them starting from 1 |
|
44 | # so that we can index them starting from 1 | |
48 | input_hist_parsed = List([""]) |
|
45 | input_hist_parsed = List([""]) | |
49 | input_hist_raw = List([""]) |
|
46 | input_hist_raw = List([""]) | |
50 | # A list of directories visited during session |
|
47 | # A list of directories visited during session | |
51 | dir_hist = List() |
|
48 | dir_hist = List() | |
52 | def _dir_hist_default(self): |
|
49 | def _dir_hist_default(self): | |
53 | try: |
|
50 | try: | |
54 | return [os.getcwd()] |
|
51 | return [os.getcwd()] | |
55 | except OSError: |
|
52 | except OSError: | |
56 | return [] |
|
53 | return [] | |
57 |
|
54 | |||
58 | # A dict of output history, keyed with ints from the shell's |
|
55 | # A dict of output history, keyed with ints from the shell's | |
59 | # execution count. If there are several outputs from one command, |
|
56 | # execution count. | |
60 | # only the last one is stored. |
|
|||
61 | output_hist = Dict() |
|
57 | output_hist = Dict() | |
62 | # Contains all outputs, in lists of reprs. |
|
58 | # The text/plain repr of outputs. | |
63 |
output_hist_reprs = |
|
59 | output_hist_reprs = Dict() | |
64 |
|
60 | |||
65 | # String holding the path to the history file |
|
61 | # String holding the path to the history file | |
66 | hist_file = Unicode(config=True) |
|
62 | hist_file = Unicode(config=True) | |
67 |
|
63 | |||
68 | # The SQLite database |
|
64 | # The SQLite database | |
69 | db = Instance(sqlite3.Connection) |
|
65 | db = Instance(sqlite3.Connection) | |
70 | # The number of the current session in the history database |
|
66 | # The number of the current session in the history database | |
71 | session_number = Int() |
|
67 | session_number = Int() | |
72 | # Should we log output to the database? (default no) |
|
68 | # Should we log output to the database? (default no) | |
73 | db_log_output = Bool(False, config=True) |
|
69 | db_log_output = Bool(False, config=True) | |
74 | # Write to database every x commands (higher values save disk access & power) |
|
70 | # Write to database every x commands (higher values save disk access & power) | |
75 | # Values of 1 or less effectively disable caching. |
|
71 | # Values of 1 or less effectively disable caching. | |
76 | db_cache_size = Int(0, config=True) |
|
72 | db_cache_size = Int(0, config=True) | |
77 | # The input and output caches |
|
73 | # The input and output caches | |
78 | db_input_cache = List() |
|
74 | db_input_cache = List() | |
79 | db_output_cache = List() |
|
75 | db_output_cache = List() | |
80 |
|
76 | |||
81 | # History saving in separate thread |
|
77 | # History saving in separate thread | |
82 | save_thread = Instance('IPython.core.history.HistorySavingThread') |
|
78 | save_thread = Instance('IPython.core.history.HistorySavingThread') | |
83 | # N.B. Event is a function returning an instance of _Event. |
|
79 | # N.B. Event is a function returning an instance of _Event. | |
84 | save_flag = Instance(threading._Event) |
|
80 | save_flag = Instance(threading._Event) | |
85 |
|
81 | |||
86 | # Private interface |
|
82 | # Private interface | |
87 | # Variables used to store the three last inputs from the user. On each new |
|
83 | # Variables used to store the three last inputs from the user. On each new | |
88 | # history update, we populate the user's namespace with these, shifted as |
|
84 | # history update, we populate the user's namespace with these, shifted as | |
89 | # necessary. |
|
85 | # necessary. | |
90 | _i00 = Unicode(u'') |
|
86 | _i00 = Unicode(u'') | |
91 | _i = Unicode(u'') |
|
87 | _i = Unicode(u'') | |
92 | _ii = Unicode(u'') |
|
88 | _ii = Unicode(u'') | |
93 | _iii = Unicode(u'') |
|
89 | _iii = Unicode(u'') | |
94 |
|
90 | |||
95 |
# A |
|
91 | # A regex matching all forms of the exit command, so that we don't store | |
96 |
# the history (it's annoying to rewind the first entry and land on |
|
92 | # them in the history (it's annoying to rewind the first entry and land on | |
97 | # call). |
|
93 | # an exit call). | |
98 | _exit_commands = Instance(set, args=(['Quit', 'quit', 'Exit', 'exit', |
|
94 | _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$") | |
99 | '%Quit', '%quit', '%Exit', '%exit'],)) |
|
|||
100 |
|
95 | |||
101 | def __init__(self, shell, config=None, **traits): |
|
96 | def __init__(self, shell, config=None, **traits): | |
102 | """Create a new history manager associated with a shell instance. |
|
97 | """Create a new history manager associated with a shell instance. | |
103 | """ |
|
98 | """ | |
104 | # We need a pointer back to the shell for various tasks. |
|
99 | # We need a pointer back to the shell for various tasks. | |
105 | super(HistoryManager, self).__init__(shell=shell, config=config, |
|
100 | super(HistoryManager, self).__init__(shell=shell, config=config, | |
106 | **traits) |
|
101 | **traits) | |
107 |
|
102 | |||
108 | if self.hist_file == u'': |
|
103 | if self.hist_file == u'': | |
109 | # No one has set the hist_file, yet. |
|
104 | # No one has set the hist_file, yet. | |
110 | if shell.profile: |
|
105 | if shell.profile: | |
111 | histfname = 'history-%s' % shell.profile |
|
106 | histfname = 'history-%s' % shell.profile | |
112 | else: |
|
107 | else: | |
113 | histfname = 'history' |
|
108 | histfname = 'history' | |
114 | self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite') |
|
109 | self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite') | |
115 |
|
110 | |||
116 | try: |
|
111 | try: | |
117 | self.init_db() |
|
112 | self.init_db() | |
118 | except sqlite3.DatabaseError: |
|
113 | except sqlite3.DatabaseError: | |
119 | if os.path.isfile(self.hist_file): |
|
114 | if os.path.isfile(self.hist_file): | |
120 | # Try to move the file out of the way. |
|
115 | # Try to move the file out of the way. | |
121 | newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite") |
|
116 | newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite") | |
122 | os.rename(self.hist_file, newpath) |
|
117 | os.rename(self.hist_file, newpath) | |
123 | print("ERROR! History file wasn't a valid SQLite database.", |
|
118 | print("ERROR! History file wasn't a valid SQLite database.", | |
124 | "It was moved to %s" % newpath, "and a new file created.") |
|
119 | "It was moved to %s" % newpath, "and a new file created.") | |
125 | self.init_db() |
|
120 | self.init_db() | |
126 | else: |
|
121 | else: | |
127 | # The hist_file is probably :memory: or something else. |
|
122 | # The hist_file is probably :memory: or something else. | |
128 | raise |
|
123 | raise | |
129 |
|
124 | |||
130 | self.save_flag = threading.Event() |
|
125 | self.save_flag = threading.Event() | |
131 | self.db_input_cache_lock = threading.Lock() |
|
126 | self.db_input_cache_lock = threading.Lock() | |
132 | self.db_output_cache_lock = threading.Lock() |
|
127 | self.db_output_cache_lock = threading.Lock() | |
133 | self.save_thread = HistorySavingThread(self) |
|
128 | self.save_thread = HistorySavingThread(self) | |
134 | self.save_thread.start() |
|
129 | self.save_thread.start() | |
135 |
|
130 | |||
136 | self.new_session() |
|
131 | self.new_session() | |
137 |
|
132 | |||
138 |
|
133 | |||
139 | def init_db(self): |
|
134 | def init_db(self): | |
140 | """Connect to the database, and create tables if necessary.""" |
|
135 | """Connect to the database, and create tables if necessary.""" | |
141 | self.db = sqlite3.connect(self.hist_file) |
|
136 | self.db = sqlite3.connect(self.hist_file) | |
142 | self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer |
|
137 | self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer | |
143 | primary key autoincrement, start timestamp, |
|
138 | primary key autoincrement, start timestamp, | |
144 | end timestamp, num_cmds integer, remark text)""") |
|
139 | end timestamp, num_cmds integer, remark text)""") | |
145 | self.db.execute("""CREATE TABLE IF NOT EXISTS history |
|
140 | self.db.execute("""CREATE TABLE IF NOT EXISTS history | |
146 | (session integer, line integer, source text, source_raw text, |
|
141 | (session integer, line integer, source text, source_raw text, | |
147 | PRIMARY KEY (session, line))""") |
|
142 | PRIMARY KEY (session, line))""") | |
148 | # Output history is optional, but ensure the table's there so it can be |
|
143 | # Output history is optional, but ensure the table's there so it can be | |
149 | # enabled later. |
|
144 | # enabled later. | |
150 | self.db.execute("""CREATE TABLE IF NOT EXISTS output_history |
|
145 | self.db.execute("""CREATE TABLE IF NOT EXISTS output_history | |
151 | (session integer, line integer, output text, |
|
146 | (session integer, line integer, output text, | |
152 | PRIMARY KEY (session, line))""") |
|
147 | PRIMARY KEY (session, line))""") | |
153 | self.db.commit() |
|
148 | self.db.commit() | |
154 |
|
149 | |||
155 | def new_session(self, conn=None): |
|
150 | def new_session(self, conn=None): | |
156 | """Get a new session number.""" |
|
151 | """Get a new session number.""" | |
157 | if conn is None: |
|
152 | if conn is None: | |
158 | conn = self.db |
|
153 | conn = self.db | |
159 |
|
154 | |||
160 | with conn: |
|
155 | with conn: | |
161 | cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL, |
|
156 | cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL, | |
162 | NULL, "") """, (datetime.datetime.now(),)) |
|
157 | NULL, "") """, (datetime.datetime.now(),)) | |
163 | self.session_number = cur.lastrowid |
|
158 | self.session_number = cur.lastrowid | |
164 |
|
159 | |||
165 | def end_session(self): |
|
160 | def end_session(self): | |
166 | """Close the database session, filling in the end time and line count.""" |
|
161 | """Close the database session, filling in the end time and line count.""" | |
167 | self.writeout_cache() |
|
162 | self.writeout_cache() | |
168 | with self.db: |
|
163 | with self.db: | |
169 | self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE |
|
164 | self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE | |
170 | session==?""", (datetime.datetime.now(), |
|
165 | session==?""", (datetime.datetime.now(), | |
171 | len(self.input_hist_parsed)-1, self.session_number)) |
|
166 | len(self.input_hist_parsed)-1, self.session_number)) | |
172 | self.session_number = 0 |
|
167 | self.session_number = 0 | |
173 |
|
168 | |||
174 | def name_session(self, name): |
|
169 | def name_session(self, name): | |
175 | """Give the current session a name in the history database.""" |
|
170 | """Give the current session a name in the history database.""" | |
176 | with self.db: |
|
171 | with self.db: | |
177 | self.db.execute("UPDATE sessions SET remark=? WHERE session==?", |
|
172 | self.db.execute("UPDATE sessions SET remark=? WHERE session==?", | |
178 | (name, self.session_number)) |
|
173 | (name, self.session_number)) | |
179 |
|
174 | |||
180 | def reset(self, new_session=True): |
|
175 | def reset(self, new_session=True): | |
181 | """Clear the session history, releasing all object references, and |
|
176 | """Clear the session history, releasing all object references, and | |
182 | optionally open a new session.""" |
|
177 | optionally open a new session.""" | |
183 | self.output_hist.clear() |
|
178 | self.output_hist.clear() | |
184 | # The directory history can't be completely empty |
|
179 | # The directory history can't be completely empty | |
185 | self.dir_hist[:] = [os.getcwd()] |
|
180 | self.dir_hist[:] = [os.getcwd()] | |
186 |
|
181 | |||
187 | if new_session: |
|
182 | if new_session: | |
188 | if self.session_number: |
|
183 | if self.session_number: | |
189 | self.end_session() |
|
184 | self.end_session() | |
190 | self.input_hist_parsed[:] = [""] |
|
185 | self.input_hist_parsed[:] = [""] | |
191 | self.input_hist_raw[:] = [""] |
|
186 | self.input_hist_raw[:] = [""] | |
192 | self.new_session() |
|
187 | self.new_session() | |
193 |
|
188 | |||
194 | ## ------------------------------- |
|
189 | ## ------------------------------- | |
195 | ## Methods for retrieving history: |
|
190 | ## Methods for retrieving history: | |
196 | ## ------------------------------- |
|
191 | ## ------------------------------- | |
197 | def _run_sql(self, sql, params, raw=True, output=False): |
|
192 | def _run_sql(self, sql, params, raw=True, output=False): | |
198 | """Prepares and runs an SQL query for the history database. |
|
193 | """Prepares and runs an SQL query for the history database. | |
199 |
|
194 | |||
200 | Parameters |
|
195 | Parameters | |
201 | ---------- |
|
196 | ---------- | |
202 | sql : str |
|
197 | sql : str | |
203 | Any filtering expressions to go after SELECT ... FROM ... |
|
198 | Any filtering expressions to go after SELECT ... FROM ... | |
204 | params : tuple |
|
199 | params : tuple | |
205 | Parameters passed to the SQL query (to replace "?") |
|
200 | Parameters passed to the SQL query (to replace "?") | |
206 | raw, output : bool |
|
201 | raw, output : bool | |
207 | See :meth:`get_range` |
|
202 | See :meth:`get_range` | |
208 |
|
203 | |||
209 | Returns |
|
204 | Returns | |
210 | ------- |
|
205 | ------- | |
211 | Tuples as :meth:`get_range` |
|
206 | Tuples as :meth:`get_range` | |
212 | """ |
|
207 | """ | |
213 | toget = 'source_raw' if raw else 'source' |
|
208 | toget = 'source_raw' if raw else 'source' | |
214 | sqlfrom = "history" |
|
209 | sqlfrom = "history" | |
215 | if output: |
|
210 | if output: | |
216 | sqlfrom = "history LEFT JOIN output_history USING (session, line)" |
|
211 | sqlfrom = "history LEFT JOIN output_history USING (session, line)" | |
217 | toget = "history.%s, output_history.output" % toget |
|
212 | toget = "history.%s, output_history.output" % toget | |
218 | cur = self.db.execute("SELECT session, line, %s FROM %s " %\ |
|
213 | cur = self.db.execute("SELECT session, line, %s FROM %s " %\ | |
219 | (toget, sqlfrom) + sql, params) |
|
214 | (toget, sqlfrom) + sql, params) | |
220 | if output: # Regroup into 3-tuples, and parse JSON |
|
215 | if output: # Regroup into 3-tuples, and parse JSON | |
221 | loads = lambda out: json.loads(out) if out else None |
|
216 | return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur) | |
222 | return ((ses, lin, (inp, loads(out))) \ |
|
|||
223 | for ses, lin, inp, out in cur) |
|
|||
224 | return cur |
|
217 | return cur | |
225 |
|
218 | |||
226 |
|
219 | |||
227 | def get_tail(self, n=10, raw=True, output=False, include_latest=False): |
|
220 | def get_tail(self, n=10, raw=True, output=False, include_latest=False): | |
228 | """Get the last n lines from the history database. |
|
221 | """Get the last n lines from the history database. | |
229 |
|
222 | |||
230 | Parameters |
|
223 | Parameters | |
231 | ---------- |
|
224 | ---------- | |
232 | n : int |
|
225 | n : int | |
233 | The number of lines to get |
|
226 | The number of lines to get | |
234 | raw, output : bool |
|
227 | raw, output : bool | |
235 | See :meth:`get_range` |
|
228 | See :meth:`get_range` | |
236 | include_latest : bool |
|
229 | include_latest : bool | |
237 | If False (default), n+1 lines are fetched, and the latest one |
|
230 | If False (default), n+1 lines are fetched, and the latest one | |
238 | is discarded. This is intended to be used where the function |
|
231 | is discarded. This is intended to be used where the function | |
239 | is called by a user command, which it should not return. |
|
232 | is called by a user command, which it should not return. | |
240 |
|
233 | |||
241 | Returns |
|
234 | Returns | |
242 | ------- |
|
235 | ------- | |
243 | Tuples as :meth:`get_range` |
|
236 | Tuples as :meth:`get_range` | |
244 | """ |
|
237 | """ | |
245 | self.writeout_cache() |
|
238 | self.writeout_cache() | |
246 | if not include_latest: |
|
239 | if not include_latest: | |
247 | n += 1 |
|
240 | n += 1 | |
248 | cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?", |
|
241 | cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?", | |
249 | (n,), raw=raw, output=output) |
|
242 | (n,), raw=raw, output=output) | |
250 | if not include_latest: |
|
243 | if not include_latest: | |
251 | return reversed(list(cur)[1:]) |
|
244 | return reversed(list(cur)[1:]) | |
252 | return reversed(list(cur)) |
|
245 | return reversed(list(cur)) | |
253 |
|
246 | |||
254 | def search(self, pattern="*", raw=True, search_raw=True, |
|
247 | def search(self, pattern="*", raw=True, search_raw=True, | |
255 | output=False): |
|
248 | output=False): | |
256 | """Search the database using unix glob-style matching (wildcards |
|
249 | """Search the database using unix glob-style matching (wildcards | |
257 | * and ?). |
|
250 | * and ?). | |
258 |
|
251 | |||
259 | Parameters |
|
252 | Parameters | |
260 | ---------- |
|
253 | ---------- | |
261 | pattern : str |
|
254 | pattern : str | |
262 | The wildcarded pattern to match when searching |
|
255 | The wildcarded pattern to match when searching | |
263 | search_raw : bool |
|
256 | search_raw : bool | |
264 | If True, search the raw input, otherwise, the parsed input |
|
257 | If True, search the raw input, otherwise, the parsed input | |
265 | raw, output : bool |
|
258 | raw, output : bool | |
266 | See :meth:`get_range` |
|
259 | See :meth:`get_range` | |
267 |
|
260 | |||
268 | Returns |
|
261 | Returns | |
269 | ------- |
|
262 | ------- | |
270 | Tuples as :meth:`get_range` |
|
263 | Tuples as :meth:`get_range` | |
271 | """ |
|
264 | """ | |
272 | tosearch = "source_raw" if search_raw else "source" |
|
265 | tosearch = "source_raw" if search_raw else "source" | |
273 | if output: |
|
266 | if output: | |
274 | tosearch = "history." + tosearch |
|
267 | tosearch = "history." + tosearch | |
275 | self.writeout_cache() |
|
268 | self.writeout_cache() | |
276 | return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,), |
|
269 | return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,), | |
277 | raw=raw, output=output) |
|
270 | raw=raw, output=output) | |
278 |
|
271 | |||
279 | def _get_range_session(self, start=1, stop=None, raw=True, output=False): |
|
272 | def _get_range_session(self, start=1, stop=None, raw=True, output=False): | |
280 | """Get input and output history from the current session. Called by |
|
273 | """Get input and output history from the current session. Called by | |
281 | get_range, and takes similar parameters.""" |
|
274 | get_range, and takes similar parameters.""" | |
282 | input_hist = self.input_hist_raw if raw else self.input_hist_parsed |
|
275 | input_hist = self.input_hist_raw if raw else self.input_hist_parsed | |
283 |
|
276 | |||
284 | n = len(input_hist) |
|
277 | n = len(input_hist) | |
285 | if start < 0: |
|
278 | if start < 0: | |
286 | start += n |
|
279 | start += n | |
287 | if not stop: |
|
280 | if not stop: | |
288 | stop = n |
|
281 | stop = n | |
289 | elif stop < 0: |
|
282 | elif stop < 0: | |
290 | stop += n |
|
283 | stop += n | |
291 |
|
284 | |||
292 | for i in range(start, stop): |
|
285 | for i in range(start, stop): | |
293 | if output: |
|
286 | if output: | |
294 | line = (input_hist[i], self.output_hist_reprs.get(i)) |
|
287 | line = (input_hist[i], self.output_hist_reprs.get(i)) | |
295 | else: |
|
288 | else: | |
296 | line = input_hist[i] |
|
289 | line = input_hist[i] | |
297 | yield (0, i, line) |
|
290 | yield (0, i, line) | |
298 |
|
291 | |||
299 | def get_range(self, session=0, start=1, stop=None, raw=True,output=False): |
|
292 | def get_range(self, session=0, start=1, stop=None, raw=True,output=False): | |
300 | """Retrieve input by session. |
|
293 | """Retrieve input by session. | |
301 |
|
294 | |||
302 | Parameters |
|
295 | Parameters | |
303 | ---------- |
|
296 | ---------- | |
304 | session : int |
|
297 | session : int | |
305 | Session number to retrieve. The current session is 0, and negative |
|
298 | Session number to retrieve. The current session is 0, and negative | |
306 | numbers count back from current session, so -1 is previous session. |
|
299 | numbers count back from current session, so -1 is previous session. | |
307 | start : int |
|
300 | start : int | |
308 | First line to retrieve. |
|
301 | First line to retrieve. | |
309 | stop : int |
|
302 | stop : int | |
310 | End of line range (excluded from output itself). If None, retrieve |
|
303 | End of line range (excluded from output itself). If None, retrieve | |
311 | to the end of the session. |
|
304 | to the end of the session. | |
312 | raw : bool |
|
305 | raw : bool | |
313 | If True, return untranslated input |
|
306 | If True, return untranslated input | |
314 | output : bool |
|
307 | output : bool | |
315 | If True, attempt to include output. This will be 'real' Python |
|
308 | If True, attempt to include output. This will be 'real' Python | |
316 | objects for the current session, or text reprs from previous |
|
309 | objects for the current session, or text reprs from previous | |
317 | sessions if db_log_output was enabled at the time. Where no output |
|
310 | sessions if db_log_output was enabled at the time. Where no output | |
318 | is found, None is used. |
|
311 | is found, None is used. | |
319 |
|
312 | |||
320 | Returns |
|
313 | Returns | |
321 | ------- |
|
314 | ------- | |
322 | An iterator over the desired lines. Each line is a 3-tuple, either |
|
315 | An iterator over the desired lines. Each line is a 3-tuple, either | |
323 | (session, line, input) if output is False, or |
|
316 | (session, line, input) if output is False, or | |
324 | (session, line, (input, output)) if output is True. |
|
317 | (session, line, (input, output)) if output is True. | |
325 | """ |
|
318 | """ | |
326 | if session == 0 or session==self.session_number: # Current session |
|
319 | if session == 0 or session==self.session_number: # Current session | |
327 | return self._get_range_session(start, stop, raw, output) |
|
320 | return self._get_range_session(start, stop, raw, output) | |
328 | if session < 0: |
|
321 | if session < 0: | |
329 | session += self.session_number |
|
322 | session += self.session_number | |
330 |
|
323 | |||
331 | if stop: |
|
324 | if stop: | |
332 | lineclause = "line >= ? AND line < ?" |
|
325 | lineclause = "line >= ? AND line < ?" | |
333 | params = (session, start, stop) |
|
326 | params = (session, start, stop) | |
334 | else: |
|
327 | else: | |
335 | lineclause = "line>=?" |
|
328 | lineclause = "line>=?" | |
336 | params = (session, start) |
|
329 | params = (session, start) | |
337 |
|
330 | |||
338 | return self._run_sql("WHERE session==? AND %s""" % lineclause, |
|
331 | return self._run_sql("WHERE session==? AND %s""" % lineclause, | |
339 | params, raw=raw, output=output) |
|
332 | params, raw=raw, output=output) | |
340 |
|
333 | |||
341 | def get_range_by_str(self, rangestr, raw=True, output=False): |
|
334 | def get_range_by_str(self, rangestr, raw=True, output=False): | |
342 | """Get lines of history from a string of ranges, as used by magic |
|
335 | """Get lines of history from a string of ranges, as used by magic | |
343 | commands %hist, %save, %macro, etc. |
|
336 | commands %hist, %save, %macro, etc. | |
344 |
|
337 | |||
345 | Parameters |
|
338 | Parameters | |
346 | ---------- |
|
339 | ---------- | |
347 | rangestr : str |
|
340 | rangestr : str | |
348 | A string specifying ranges, e.g. "5 ~2/1-4". See |
|
341 | A string specifying ranges, e.g. "5 ~2/1-4". See | |
349 | :func:`magic_history` for full details. |
|
342 | :func:`magic_history` for full details. | |
350 | raw, output : bool |
|
343 | raw, output : bool | |
351 | As :meth:`get_range` |
|
344 | As :meth:`get_range` | |
352 |
|
345 | |||
353 | Returns |
|
346 | Returns | |
354 | ------- |
|
347 | ------- | |
355 | Tuples as :meth:`get_range` |
|
348 | Tuples as :meth:`get_range` | |
356 | """ |
|
349 | """ | |
357 | for sess, s, e in extract_hist_ranges(rangestr): |
|
350 | for sess, s, e in extract_hist_ranges(rangestr): | |
358 | for line in self.get_range(sess, s, e, raw=raw, output=output): |
|
351 | for line in self.get_range(sess, s, e, raw=raw, output=output): | |
359 | yield line |
|
352 | yield line | |
360 |
|
353 | |||
361 | ## ---------------------------- |
|
354 | ## ---------------------------- | |
362 | ## Methods for storing history: |
|
355 | ## Methods for storing history: | |
363 | ## ---------------------------- |
|
356 | ## ---------------------------- | |
364 | def store_inputs(self, line_num, source, source_raw=None): |
|
357 | def store_inputs(self, line_num, source, source_raw=None): | |
365 | """Store source and raw input in history and create input cache |
|
358 | """Store source and raw input in history and create input cache | |
366 | variables _i*. |
|
359 | variables _i*. | |
367 |
|
360 | |||
368 | Parameters |
|
361 | Parameters | |
369 | ---------- |
|
362 | ---------- | |
370 | line_num : int |
|
363 | line_num : int | |
371 | The prompt number of this input. |
|
364 | The prompt number of this input. | |
372 |
|
365 | |||
373 | source : str |
|
366 | source : str | |
374 | Python input. |
|
367 | Python input. | |
375 |
|
368 | |||
376 | source_raw : str, optional |
|
369 | source_raw : str, optional | |
377 | If given, this is the raw input without any IPython transformations |
|
370 | If given, this is the raw input without any IPython transformations | |
378 | applied to it. If not given, ``source`` is used. |
|
371 | applied to it. If not given, ``source`` is used. | |
379 | """ |
|
372 | """ | |
380 | if source_raw is None: |
|
373 | if source_raw is None: | |
381 | source_raw = source |
|
374 | source_raw = source | |
382 | source = source.rstrip('\n') |
|
375 | source = source.rstrip('\n') | |
383 | source_raw = source_raw.rstrip('\n') |
|
376 | source_raw = source_raw.rstrip('\n') | |
384 |
|
377 | |||
385 | # do not store exit/quit commands |
|
378 | # do not store exit/quit commands | |
386 | if source_raw.strip() in self._exit_commands: |
|
379 | if self._exit_re.match(source_raw.strip()): | |
387 | return |
|
380 | return | |
388 |
|
381 | |||
389 | self.input_hist_parsed.append(source) |
|
382 | self.input_hist_parsed.append(source) | |
390 | self.input_hist_raw.append(source_raw) |
|
383 | self.input_hist_raw.append(source_raw) | |
391 |
|
384 | |||
392 | with self.db_input_cache_lock: |
|
385 | with self.db_input_cache_lock: | |
393 | self.db_input_cache.append((line_num, source, source_raw)) |
|
386 | self.db_input_cache.append((line_num, source, source_raw)) | |
394 | # Trigger to flush cache and write to DB. |
|
387 | # Trigger to flush cache and write to DB. | |
395 | if len(self.db_input_cache) >= self.db_cache_size: |
|
388 | if len(self.db_input_cache) >= self.db_cache_size: | |
396 | self.save_flag.set() |
|
389 | self.save_flag.set() | |
397 |
|
390 | |||
398 | # update the auto _i variables |
|
391 | # update the auto _i variables | |
399 | self._iii = self._ii |
|
392 | self._iii = self._ii | |
400 | self._ii = self._i |
|
393 | self._ii = self._i | |
401 | self._i = self._i00 |
|
394 | self._i = self._i00 | |
402 | self._i00 = source_raw |
|
395 | self._i00 = source_raw | |
403 |
|
396 | |||
404 | # hackish access to user namespace to create _i1,_i2... dynamically |
|
397 | # hackish access to user namespace to create _i1,_i2... dynamically | |
405 | new_i = '_i%s' % line_num |
|
398 | new_i = '_i%s' % line_num | |
406 | to_main = {'_i': self._i, |
|
399 | to_main = {'_i': self._i, | |
407 | '_ii': self._ii, |
|
400 | '_ii': self._ii, | |
408 | '_iii': self._iii, |
|
401 | '_iii': self._iii, | |
409 | new_i : self._i00 } |
|
402 | new_i : self._i00 } | |
410 | self.shell.user_ns.update(to_main) |
|
403 | self.shell.user_ns.update(to_main) | |
411 |
|
404 | |||
412 | def store_output(self, line_num): |
|
405 | def store_output(self, line_num): | |
413 | """If database output logging is enabled, this saves all the |
|
406 | """If database output logging is enabled, this saves all the | |
414 | outputs from the indicated prompt number to the database. It's |
|
407 | outputs from the indicated prompt number to the database. It's | |
415 | called by run_cell after code has been executed. |
|
408 | called by run_cell after code has been executed. | |
416 |
|
409 | |||
417 | Parameters |
|
410 | Parameters | |
418 | ---------- |
|
411 | ---------- | |
419 | line_num : int |
|
412 | line_num : int | |
420 | The line number from which to save outputs |
|
413 | The line number from which to save outputs | |
421 | """ |
|
414 | """ | |
422 |
if (not self.db_log_output) or not self.output_hist_reprs |
|
415 | if (not self.db_log_output) or (line_num not in self.output_hist_reprs): | |
423 | return |
|
416 | return | |
424 |
output = |
|
417 | output = self.output_hist_reprs[line_num] | |
425 |
|
418 | |||
426 | with self.db_output_cache_lock: |
|
419 | with self.db_output_cache_lock: | |
427 | self.db_output_cache.append((line_num, output)) |
|
420 | self.db_output_cache.append((line_num, output)) | |
428 | if self.db_cache_size <= 1: |
|
421 | if self.db_cache_size <= 1: | |
429 | self.save_flag.set() |
|
422 | self.save_flag.set() | |
430 |
|
423 | |||
431 | def _writeout_input_cache(self, conn): |
|
424 | def _writeout_input_cache(self, conn): | |
432 | with conn: |
|
425 | with conn: | |
433 | for line in self.db_input_cache: |
|
426 | for line in self.db_input_cache: | |
434 | conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)", |
|
427 | conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)", | |
435 | (self.session_number,)+line) |
|
428 | (self.session_number,)+line) | |
436 |
|
429 | |||
437 | def _writeout_output_cache(self, conn): |
|
430 | def _writeout_output_cache(self, conn): | |
438 | with conn: |
|
431 | with conn: | |
439 | for line in self.db_output_cache: |
|
432 | for line in self.db_output_cache: | |
440 | conn.execute("INSERT INTO output_history VALUES (?, ?, ?)", |
|
433 | conn.execute("INSERT INTO output_history VALUES (?, ?, ?)", | |
441 | (self.session_number,)+line) |
|
434 | (self.session_number,)+line) | |
442 |
|
435 | |||
443 | def writeout_cache(self, conn=None): |
|
436 | def writeout_cache(self, conn=None): | |
444 | """Write any entries in the cache to the database.""" |
|
437 | """Write any entries in the cache to the database.""" | |
445 | if conn is None: |
|
438 | if conn is None: | |
446 | conn = self.db |
|
439 | conn = self.db | |
447 |
|
440 | |||
448 | with self.db_input_cache_lock: |
|
441 | with self.db_input_cache_lock: | |
449 | try: |
|
442 | try: | |
450 | self._writeout_input_cache(conn) |
|
443 | self._writeout_input_cache(conn) | |
451 | except sqlite3.IntegrityError: |
|
444 | except sqlite3.IntegrityError: | |
452 | self.new_session(conn) |
|
445 | self.new_session(conn) | |
453 | print("ERROR! Session/line number was not unique in", |
|
446 | print("ERROR! Session/line number was not unique in", | |
454 | "database. History logging moved to new session", |
|
447 | "database. History logging moved to new session", | |
455 | self.session_number) |
|
448 | self.session_number) | |
456 | try: # Try writing to the new session. If this fails, don't recurse |
|
449 | try: # Try writing to the new session. If this fails, don't recurse | |
457 | self._writeout_input_cache(conn) |
|
450 | self._writeout_input_cache(conn) | |
458 | except sqlite3.IntegrityError: |
|
451 | except sqlite3.IntegrityError: | |
459 | pass |
|
452 | pass | |
460 | finally: |
|
453 | finally: | |
461 | self.db_input_cache = [] |
|
454 | self.db_input_cache = [] | |
462 |
|
455 | |||
463 | with self.db_output_cache_lock: |
|
456 | with self.db_output_cache_lock: | |
464 | try: |
|
457 | try: | |
465 | self._writeout_output_cache(conn) |
|
458 | self._writeout_output_cache(conn) | |
466 | except sqlite3.IntegrityError: |
|
459 | except sqlite3.IntegrityError: | |
467 | print("!! Session/line number for output was not unique", |
|
460 | print("!! Session/line number for output was not unique", | |
468 | "in database. Output will not be stored.") |
|
461 | "in database. Output will not be stored.") | |
469 | finally: |
|
462 | finally: | |
470 | self.db_output_cache = [] |
|
463 | self.db_output_cache = [] | |
471 |
|
464 | |||
472 |
|
465 | |||
473 | class HistorySavingThread(threading.Thread): |
|
466 | class HistorySavingThread(threading.Thread): | |
474 | """This thread takes care of writing history to the database, so that |
|
467 | """This thread takes care of writing history to the database, so that | |
475 | the UI isn't held up while that happens. |
|
468 | the UI isn't held up while that happens. | |
476 |
|
469 | |||
477 | It waits for the HistoryManager's save_flag to be set, then writes out |
|
470 | It waits for the HistoryManager's save_flag to be set, then writes out | |
478 | the history cache. The main thread is responsible for setting the flag when |
|
471 | the history cache. The main thread is responsible for setting the flag when | |
479 | the cache size reaches a defined threshold.""" |
|
472 | the cache size reaches a defined threshold.""" | |
480 | daemon = True |
|
473 | daemon = True | |
481 | stop_now = False |
|
474 | stop_now = False | |
482 | def __init__(self, history_manager): |
|
475 | def __init__(self, history_manager): | |
483 | super(HistorySavingThread, self).__init__() |
|
476 | super(HistorySavingThread, self).__init__() | |
484 | self.history_manager = history_manager |
|
477 | self.history_manager = history_manager | |
485 | atexit.register(self.stop) |
|
478 | atexit.register(self.stop) | |
486 |
|
479 | |||
487 | def run(self): |
|
480 | def run(self): | |
488 | # We need a separate db connection per thread: |
|
481 | # We need a separate db connection per thread: | |
489 | try: |
|
482 | try: | |
490 | self.db = sqlite3.connect(self.history_manager.hist_file) |
|
483 | self.db = sqlite3.connect(self.history_manager.hist_file) | |
491 | while True: |
|
484 | while True: | |
492 | self.history_manager.save_flag.wait() |
|
485 | self.history_manager.save_flag.wait() | |
493 | if self.stop_now: |
|
486 | if self.stop_now: | |
494 | return |
|
487 | return | |
495 | self.history_manager.save_flag.clear() |
|
488 | self.history_manager.save_flag.clear() | |
496 | self.history_manager.writeout_cache(self.db) |
|
489 | self.history_manager.writeout_cache(self.db) | |
497 | except Exception as e: |
|
490 | except Exception as e: | |
498 | print(("The history saving thread hit an unexpected error (%s)." |
|
491 | print(("The history saving thread hit an unexpected error (%s)." | |
499 | "History will not be written to the database.") % repr(e)) |
|
492 | "History will not be written to the database.") % repr(e)) | |
500 |
|
493 | |||
501 | def stop(self): |
|
494 | def stop(self): | |
502 | """This can be called from the main thread to safely stop this thread. |
|
495 | """This can be called from the main thread to safely stop this thread. | |
503 |
|
496 | |||
504 | Note that it does not attempt to write out remaining history before |
|
497 | Note that it does not attempt to write out remaining history before | |
505 | exiting. That should be done by calling the HistoryManager's |
|
498 | exiting. That should be done by calling the HistoryManager's | |
506 | end_session method.""" |
|
499 | end_session method.""" | |
507 | self.stop_now = True |
|
500 | self.stop_now = True | |
508 | self.history_manager.save_flag.set() |
|
501 | self.history_manager.save_flag.set() | |
509 | self.join() |
|
502 | self.join() | |
510 |
|
503 | |||
511 |
|
504 | |||
512 | # To match, e.g. ~5/8-~2/3 |
|
505 | # To match, e.g. ~5/8-~2/3 | |
513 | range_re = re.compile(r""" |
|
506 | range_re = re.compile(r""" | |
514 | ((?P<startsess>~?\d+)/)? |
|
507 | ((?P<startsess>~?\d+)/)? | |
515 | (?P<start>\d+) # Only the start line num is compulsory |
|
508 | (?P<start>\d+) # Only the start line num is compulsory | |
516 | ((?P<sep>[\-:]) |
|
509 | ((?P<sep>[\-:]) | |
517 | ((?P<endsess>~?\d+)/)? |
|
510 | ((?P<endsess>~?\d+)/)? | |
518 | (?P<end>\d+))? |
|
511 | (?P<end>\d+))? | |
519 | $""", re.VERBOSE) |
|
512 | $""", re.VERBOSE) | |
520 |
|
513 | |||
521 | def extract_hist_ranges(ranges_str): |
|
514 | def extract_hist_ranges(ranges_str): | |
522 | """Turn a string of history ranges into 3-tuples of (session, start, stop). |
|
515 | """Turn a string of history ranges into 3-tuples of (session, start, stop). | |
523 |
|
516 | |||
524 | Examples |
|
517 | Examples | |
525 | -------- |
|
518 | -------- | |
526 | list(extract_input_ranges("~8/5-~7/4 2")) |
|
519 | list(extract_input_ranges("~8/5-~7/4 2")) | |
527 | [(-8, 5, None), (-7, 1, 4), (0, 2, 3)] |
|
520 | [(-8, 5, None), (-7, 1, 4), (0, 2, 3)] | |
528 | """ |
|
521 | """ | |
529 | for range_str in ranges_str.split(): |
|
522 | for range_str in ranges_str.split(): | |
530 | rmatch = range_re.match(range_str) |
|
523 | rmatch = range_re.match(range_str) | |
531 | if not rmatch: |
|
524 | if not rmatch: | |
532 | continue |
|
525 | continue | |
533 | start = int(rmatch.group("start")) |
|
526 | start = int(rmatch.group("start")) | |
534 | end = rmatch.group("end") |
|
527 | end = rmatch.group("end") | |
535 | end = int(end) if end else start+1 # If no end specified, get (a, a+1) |
|
528 | end = int(end) if end else start+1 # If no end specified, get (a, a+1) | |
536 | if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3] |
|
529 | if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3] | |
537 | end += 1 |
|
530 | end += 1 | |
538 | startsess = rmatch.group("startsess") or "0" |
|
531 | startsess = rmatch.group("startsess") or "0" | |
539 | endsess = rmatch.group("endsess") or startsess |
|
532 | endsess = rmatch.group("endsess") or startsess | |
540 | startsess = int(startsess.replace("~","-")) |
|
533 | startsess = int(startsess.replace("~","-")) | |
541 | endsess = int(endsess.replace("~","-")) |
|
534 | endsess = int(endsess.replace("~","-")) | |
542 | assert endsess >= startsess |
|
535 | assert endsess >= startsess | |
543 |
|
536 | |||
544 | if endsess == startsess: |
|
537 | if endsess == startsess: | |
545 | yield (startsess, start, end) |
|
538 | yield (startsess, start, end) | |
546 | continue |
|
539 | continue | |
547 | # Multiple sessions in one range: |
|
540 | # Multiple sessions in one range: | |
548 | yield (startsess, start, None) |
|
541 | yield (startsess, start, None) | |
549 | for sess in range(startsess+1, endsess): |
|
542 | for sess in range(startsess+1, endsess): | |
550 | yield (sess, 1, None) |
|
543 | yield (sess, 1, None) | |
551 | yield (endsess, 1, end) |
|
544 | yield (endsess, 1, end) | |
552 |
|
545 | |||
553 | def _format_lineno(session, line): |
|
546 | def _format_lineno(session, line): | |
554 | """Helper function to format line numbers properly.""" |
|
547 | """Helper function to format line numbers properly.""" | |
555 | if session == 0: |
|
548 | if session == 0: | |
556 | return str(line) |
|
549 | return str(line) | |
557 | return "%s#%s" % (session, line) |
|
550 | return "%s#%s" % (session, line) | |
558 |
|
551 | |||
559 | @testdec.skip_doctest |
|
552 | @testdec.skip_doctest | |
560 | def magic_history(self, parameter_s = ''): |
|
553 | def magic_history(self, parameter_s = ''): | |
561 | """Print input history (_i<n> variables), with most recent last. |
|
554 | """Print input history (_i<n> variables), with most recent last. | |
562 |
|
555 | |||
563 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
556 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
564 | %history n -> print at most n inputs\\ |
|
557 | %history n -> print at most n inputs\\ | |
565 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
558 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
566 |
|
559 | |||
567 | By default, input history is printed without line numbers so it can be |
|
560 | By default, input history is printed without line numbers so it can be | |
568 | directly pasted into an editor. Use -n to show them. |
|
561 | directly pasted into an editor. Use -n to show them. | |
569 |
|
562 | |||
570 | Ranges of history can be indicated using the syntax: |
|
563 | Ranges of history can be indicated using the syntax: | |
571 | 4 : Line 4, current session |
|
564 | 4 : Line 4, current session | |
572 | 4-6 : Lines 4-6, current session |
|
565 | 4-6 : Lines 4-6, current session | |
573 | 243/1-5: Lines 1-5, session 243 |
|
566 | 243/1-5: Lines 1-5, session 243 | |
574 | ~2/7 : Line 7, session 2 before current |
|
567 | ~2/7 : Line 7, session 2 before current | |
575 | ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line |
|
568 | ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line | |
576 | of 6 sessions ago. |
|
569 | of 6 sessions ago. | |
577 | Multiple ranges can be entered, separated by spaces |
|
570 | Multiple ranges can be entered, separated by spaces | |
578 |
|
571 | |||
579 | The same syntax is used by %macro, %save, %edit, %rerun |
|
572 | The same syntax is used by %macro, %save, %edit, %rerun | |
580 |
|
573 | |||
581 | Options: |
|
574 | Options: | |
582 |
|
575 | |||
583 | -n: print line numbers for each input. |
|
576 | -n: print line numbers for each input. | |
584 | This feature is only available if numbered prompts are in use. |
|
577 | This feature is only available if numbered prompts are in use. | |
585 |
|
578 | |||
586 | -o: also print outputs for each input. |
|
579 | -o: also print outputs for each input. | |
587 |
|
580 | |||
588 | -p: print classic '>>>' python prompts before each input. This is useful |
|
581 | -p: print classic '>>>' python prompts before each input. This is useful | |
589 | for making documentation, and in conjunction with -o, for producing |
|
582 | for making documentation, and in conjunction with -o, for producing | |
590 | doctest-ready output. |
|
583 | doctest-ready output. | |
591 |
|
584 | |||
592 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. |
|
585 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. | |
593 |
|
586 | |||
594 | -t: print the 'translated' history, as IPython understands it. IPython |
|
587 | -t: print the 'translated' history, as IPython understands it. IPython | |
595 | filters your input and converts it all into valid Python source before |
|
588 | filters your input and converts it all into valid Python source before | |
596 | executing it (things like magics or aliases are turned into function |
|
589 | executing it (things like magics or aliases are turned into function | |
597 | calls, for example). With this option, you'll see the native history |
|
590 | calls, for example). With this option, you'll see the native history | |
598 | instead of the user-entered version: '%cd /' will be seen as |
|
591 | instead of the user-entered version: '%cd /' will be seen as | |
599 | 'get_ipython().magic("%cd /")' instead of '%cd /'. |
|
592 | 'get_ipython().magic("%cd /")' instead of '%cd /'. | |
600 |
|
593 | |||
601 | -g: treat the arg as a pattern to grep for in (full) history. |
|
594 | -g: treat the arg as a pattern to grep for in (full) history. | |
602 | This includes the saved history (almost all commands ever written). |
|
595 | This includes the saved history (almost all commands ever written). | |
603 | Use '%hist -g' to show full saved history (may be very long). |
|
596 | Use '%hist -g' to show full saved history (may be very long). | |
604 |
|
597 | |||
605 | -l: get the last n lines from all sessions. Specify n as a single arg, or |
|
598 | -l: get the last n lines from all sessions. Specify n as a single arg, or | |
606 | the default is the last 10 lines. |
|
599 | the default is the last 10 lines. | |
607 |
|
600 | |||
608 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
601 | -f FILENAME: instead of printing the output to the screen, redirect it to | |
609 | the given file. The file is always overwritten, though IPython asks for |
|
602 | the given file. The file is always overwritten, though IPython asks for | |
610 | confirmation first if it already exists. |
|
603 | confirmation first if it already exists. | |
611 |
|
604 | |||
612 | Examples |
|
605 | Examples | |
613 | -------- |
|
606 | -------- | |
614 | :: |
|
607 | :: | |
615 |
|
608 | |||
616 | In [6]: %hist -n 4 6 |
|
609 | In [6]: %hist -n 4 6 | |
617 | 4:a = 12 |
|
610 | 4:a = 12 | |
618 | 5:print a**2 |
|
611 | 5:print a**2 | |
619 |
|
612 | |||
620 | """ |
|
613 | """ | |
621 |
|
614 | |||
622 | if not self.shell.displayhook.do_full_cache: |
|
615 | if not self.shell.displayhook.do_full_cache: | |
623 | print('This feature is only available if numbered prompts are in use.') |
|
616 | print('This feature is only available if numbered prompts are in use.') | |
624 | return |
|
617 | return | |
625 | opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string') |
|
618 | opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string') | |
626 |
|
619 | |||
627 | # For brevity |
|
620 | # For brevity | |
628 | history_manager = self.shell.history_manager |
|
621 | history_manager = self.shell.history_manager | |
629 |
|
622 | |||
630 | def _format_lineno(session, line): |
|
623 | def _format_lineno(session, line): | |
631 | """Helper function to format line numbers properly.""" |
|
624 | """Helper function to format line numbers properly.""" | |
632 | if session in (0, history_manager.session_number): |
|
625 | if session in (0, history_manager.session_number): | |
633 | return str(line) |
|
626 | return str(line) | |
634 | return "%s/%s" % (session, line) |
|
627 | return "%s/%s" % (session, line) | |
635 |
|
628 | |||
636 | # Check if output to specific file was requested. |
|
629 | # Check if output to specific file was requested. | |
637 | try: |
|
630 | try: | |
638 | outfname = opts['f'] |
|
631 | outfname = opts['f'] | |
639 | except KeyError: |
|
632 | except KeyError: | |
640 | outfile = IPython.utils.io.Term.cout # default |
|
633 | outfile = IPython.utils.io.Term.cout # default | |
641 | # We don't want to close stdout at the end! |
|
634 | # We don't want to close stdout at the end! | |
642 | close_at_end = False |
|
635 | close_at_end = False | |
643 | else: |
|
636 | else: | |
644 | if os.path.exists(outfname): |
|
637 | if os.path.exists(outfname): | |
645 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): |
|
638 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): | |
646 | print('Aborting.') |
|
639 | print('Aborting.') | |
647 | return |
|
640 | return | |
648 |
|
641 | |||
649 | outfile = open(outfname,'w') |
|
642 | outfile = open(outfname,'w') | |
650 | close_at_end = True |
|
643 | close_at_end = True | |
651 |
|
644 | |||
652 | print_nums = 'n' in opts |
|
645 | print_nums = 'n' in opts | |
653 | get_output = 'o' in opts |
|
646 | get_output = 'o' in opts | |
654 | pyprompts = 'p' in opts |
|
647 | pyprompts = 'p' in opts | |
655 | # Raw history is the default |
|
648 | # Raw history is the default | |
656 | raw = not('t' in opts) |
|
649 | raw = not('t' in opts) | |
657 |
|
650 | |||
658 | default_length = 40 |
|
651 | default_length = 40 | |
659 | pattern = None |
|
652 | pattern = None | |
660 |
|
653 | |||
661 | if 'g' in opts: # Glob search |
|
654 | if 'g' in opts: # Glob search | |
662 | pattern = "*" + args + "*" if args else "*" |
|
655 | pattern = "*" + args + "*" if args else "*" | |
663 | hist = history_manager.search(pattern, raw=raw, output=get_output) |
|
656 | hist = history_manager.search(pattern, raw=raw, output=get_output) | |
664 | elif 'l' in opts: # Get 'tail' |
|
657 | elif 'l' in opts: # Get 'tail' | |
665 | try: |
|
658 | try: | |
666 | n = int(args) |
|
659 | n = int(args) | |
667 | except ValueError, IndexError: |
|
660 | except ValueError, IndexError: | |
668 | n = 10 |
|
661 | n = 10 | |
669 | hist = history_manager.get_tail(n, raw=raw, output=get_output) |
|
662 | hist = history_manager.get_tail(n, raw=raw, output=get_output) | |
670 | else: |
|
663 | else: | |
671 | if args: # Get history by ranges |
|
664 | if args: # Get history by ranges | |
672 | hist = history_manager.get_range_by_str(args, raw, get_output) |
|
665 | hist = history_manager.get_range_by_str(args, raw, get_output) | |
673 | else: # Just get history for the current session |
|
666 | else: # Just get history for the current session | |
674 | hist = history_manager.get_range(raw=raw, output=get_output) |
|
667 | hist = history_manager.get_range(raw=raw, output=get_output) | |
675 |
|
668 | |||
676 | # We could be displaying the entire history, so let's not try to pull it |
|
669 | # We could be displaying the entire history, so let's not try to pull it | |
677 | # into a list in memory. Anything that needs more space will just misalign. |
|
670 | # into a list in memory. Anything that needs more space will just misalign. | |
678 | width = 4 |
|
671 | width = 4 | |
679 |
|
672 | |||
680 | for session, lineno, inline in hist: |
|
673 | for session, lineno, inline in hist: | |
681 | # Print user history with tabs expanded to 4 spaces. The GUI clients |
|
674 | # Print user history with tabs expanded to 4 spaces. The GUI clients | |
682 | # use hard tabs for easier usability in auto-indented code, but we want |
|
675 | # use hard tabs for easier usability in auto-indented code, but we want | |
683 | # to produce PEP-8 compliant history for safe pasting into an editor. |
|
676 | # to produce PEP-8 compliant history for safe pasting into an editor. | |
684 | if get_output: |
|
677 | if get_output: | |
685 | inline, output = inline |
|
678 | inline, output = inline | |
686 | inline = inline.expandtabs(4).rstrip() |
|
679 | inline = inline.expandtabs(4).rstrip() | |
687 |
|
680 | |||
688 | multiline = "\n" in inline |
|
681 | multiline = "\n" in inline | |
689 | line_sep = '\n' if multiline else ' ' |
|
682 | line_sep = '\n' if multiline else ' ' | |
690 | if print_nums: |
|
683 | if print_nums: | |
691 | print('%s:%s' % (_format_lineno(session, lineno).rjust(width), |
|
684 | print('%s:%s' % (_format_lineno(session, lineno).rjust(width), | |
692 | line_sep), file=outfile, end='') |
|
685 | line_sep), file=outfile, end='') | |
693 | if pyprompts: |
|
686 | if pyprompts: | |
694 | print(">>> ", end="", file=outfile) |
|
687 | print(">>> ", end="", file=outfile) | |
695 | if multiline: |
|
688 | if multiline: | |
696 | inline = "\n... ".join(inline.splitlines()) + "\n..." |
|
689 | inline = "\n... ".join(inline.splitlines()) + "\n..." | |
697 | print(inline, file=outfile) |
|
690 | print(inline, file=outfile) | |
698 | if get_output and output: |
|
691 | if get_output and output: | |
699 |
print( |
|
692 | print(output, file=outfile) | |
700 |
|
693 | |||
701 | if close_at_end: |
|
694 | if close_at_end: | |
702 | outfile.close() |
|
695 | outfile.close() | |
703 |
|
696 | |||
704 |
|
697 | |||
705 | def magic_rep(self, arg): |
|
698 | def magic_rep(self, arg): | |
706 | r""" Repeat a command, or get command to input line for editing |
|
699 | r""" Repeat a command, or get command to input line for editing | |
707 |
|
700 | |||
708 | - %rep (no arguments): |
|
701 | - %rep (no arguments): | |
709 |
|
702 | |||
710 | Place a string version of last computation result (stored in the special '_' |
|
703 | Place a string version of last computation result (stored in the special '_' | |
711 | variable) to the next input prompt. Allows you to create elaborate command |
|
704 | variable) to the next input prompt. Allows you to create elaborate command | |
712 | lines without using copy-paste:: |
|
705 | lines without using copy-paste:: | |
713 |
|
706 | |||
714 | In[1]: l = ["hei", "vaan"] |
|
707 | In[1]: l = ["hei", "vaan"] | |
715 | In[2]: "".join(l) |
|
708 | In[2]: "".join(l) | |
716 | Out[2]: heivaan |
|
709 | Out[2]: heivaan | |
717 | In[3]: %rep |
|
710 | In[3]: %rep | |
718 | In[4]: heivaan_ <== cursor blinking |
|
711 | In[4]: heivaan_ <== cursor blinking | |
719 |
|
712 | |||
720 | %rep 45 |
|
713 | %rep 45 | |
721 |
|
714 | |||
722 | Place history line 45 on the next input prompt. Use %hist to find |
|
715 | Place history line 45 on the next input prompt. Use %hist to find | |
723 | out the number. |
|
716 | out the number. | |
724 |
|
717 | |||
725 | %rep 1-4 |
|
718 | %rep 1-4 | |
726 |
|
719 | |||
727 | Combine the specified lines into one cell, and place it on the next |
|
720 | Combine the specified lines into one cell, and place it on the next | |
728 | input prompt. See %history for the slice syntax. |
|
721 | input prompt. See %history for the slice syntax. | |
729 |
|
722 | |||
730 | %rep foo+bar |
|
723 | %rep foo+bar | |
731 |
|
724 | |||
732 | If foo+bar can be evaluated in the user namespace, the result is |
|
725 | If foo+bar can be evaluated in the user namespace, the result is | |
733 | placed at the next input prompt. Otherwise, the history is searched |
|
726 | placed at the next input prompt. Otherwise, the history is searched | |
734 | for lines which contain that substring, and the most recent one is |
|
727 | for lines which contain that substring, and the most recent one is | |
735 | placed at the next input prompt. |
|
728 | placed at the next input prompt. | |
736 | """ |
|
729 | """ | |
737 | if not arg: # Last output |
|
730 | if not arg: # Last output | |
738 | self.set_next_input(str(self.shell.user_ns["_"])) |
|
731 | self.set_next_input(str(self.shell.user_ns["_"])) | |
739 | return |
|
732 | return | |
740 | # Get history range |
|
733 | # Get history range | |
741 | histlines = self.history_manager.get_range_by_str(arg) |
|
734 | histlines = self.history_manager.get_range_by_str(arg) | |
742 | cmd = "\n".join(x[2] for x in histlines) |
|
735 | cmd = "\n".join(x[2] for x in histlines) | |
743 | if cmd: |
|
736 | if cmd: | |
744 | self.set_next_input(cmd.rstrip()) |
|
737 | self.set_next_input(cmd.rstrip()) | |
745 | return |
|
738 | return | |
746 |
|
739 | |||
747 | try: # Variable in user namespace |
|
740 | try: # Variable in user namespace | |
748 | cmd = str(eval(arg, self.shell.user_ns)) |
|
741 | cmd = str(eval(arg, self.shell.user_ns)) | |
749 | except Exception: # Search for term in history |
|
742 | except Exception: # Search for term in history | |
750 | histlines = self.history_manager.search("*"+arg+"*") |
|
743 | histlines = self.history_manager.search("*"+arg+"*") | |
751 | for h in reversed([x[2] for x in histlines]): |
|
744 | for h in reversed([x[2] for x in histlines]): | |
752 | if 'rep' in h: |
|
745 | if 'rep' in h: | |
753 | continue |
|
746 | continue | |
754 | self.set_next_input(h.rstrip()) |
|
747 | self.set_next_input(h.rstrip()) | |
755 | return |
|
748 | return | |
756 | else: |
|
749 | else: | |
757 | self.set_next_input(cmd.rstrip()) |
|
750 | self.set_next_input(cmd.rstrip()) | |
758 | print("Couldn't evaluate or find in history:", arg) |
|
751 | print("Couldn't evaluate or find in history:", arg) | |
759 |
|
752 | |||
760 | def magic_rerun(self, parameter_s=''): |
|
753 | def magic_rerun(self, parameter_s=''): | |
761 | """Re-run previous input |
|
754 | """Re-run previous input | |
762 |
|
755 | |||
763 | By default, you can specify ranges of input history to be repeated |
|
756 | By default, you can specify ranges of input history to be repeated | |
764 | (as with %history). With no arguments, it will repeat the last line. |
|
757 | (as with %history). With no arguments, it will repeat the last line. | |
765 |
|
758 | |||
766 | Options: |
|
759 | Options: | |
767 |
|
760 | |||
768 | -l <n> : Repeat the last n lines of input, not including the |
|
761 | -l <n> : Repeat the last n lines of input, not including the | |
769 | current command. |
|
762 | current command. | |
770 |
|
763 | |||
771 | -g foo : Repeat the most recent line which contains foo |
|
764 | -g foo : Repeat the most recent line which contains foo | |
772 | """ |
|
765 | """ | |
773 | opts, args = self.parse_options(parameter_s, 'l:g:', mode='string') |
|
766 | opts, args = self.parse_options(parameter_s, 'l:g:', mode='string') | |
774 | if "l" in opts: # Last n lines |
|
767 | if "l" in opts: # Last n lines | |
775 | n = int(opts['l']) |
|
768 | n = int(opts['l']) | |
776 | hist = self.history_manager.get_tail(n) |
|
769 | hist = self.history_manager.get_tail(n) | |
777 | elif "g" in opts: # Search |
|
770 | elif "g" in opts: # Search | |
778 | p = "*"+opts['g']+"*" |
|
771 | p = "*"+opts['g']+"*" | |
779 | hist = list(self.history_manager.search(p)) |
|
772 | hist = list(self.history_manager.search(p)) | |
780 | for l in reversed(hist): |
|
773 | for l in reversed(hist): | |
781 | if "rerun" not in l[2]: |
|
774 | if "rerun" not in l[2]: | |
782 | hist = [l] # The last match which isn't a %rerun |
|
775 | hist = [l] # The last match which isn't a %rerun | |
783 | break |
|
776 | break | |
784 | else: |
|
777 | else: | |
785 | hist = [] # No matches except %rerun |
|
778 | hist = [] # No matches except %rerun | |
786 | elif args: # Specify history ranges |
|
779 | elif args: # Specify history ranges | |
787 | hist = self.history_manager.get_range_by_str(args) |
|
780 | hist = self.history_manager.get_range_by_str(args) | |
788 | else: # Last line |
|
781 | else: # Last line | |
789 | hist = self.history_manager.get_tail(1) |
|
782 | hist = self.history_manager.get_tail(1) | |
790 | hist = [x[2] for x in hist] |
|
783 | hist = [x[2] for x in hist] | |
791 | if not hist: |
|
784 | if not hist: | |
792 | print("No lines in history match specification") |
|
785 | print("No lines in history match specification") | |
793 | return |
|
786 | return | |
794 | histlines = "\n".join(hist) |
|
787 | histlines = "\n".join(hist) | |
795 | print("=== Executing: ===") |
|
788 | print("=== Executing: ===") | |
796 | print(histlines) |
|
789 | print(histlines) | |
797 | print("=== Output: ===") |
|
790 | print("=== Output: ===") | |
798 | self.run_cell("\n".join(hist), store_history=False) |
|
791 | self.run_cell("\n".join(hist), store_history=False) | |
799 |
|
792 | |||
800 |
|
793 | |||
801 | def init_ipython(ip): |
|
794 | def init_ipython(ip): | |
802 | ip.define_magic("rep", magic_rep) |
|
795 | ip.define_magic("rep", magic_rep) | |
803 | ip.define_magic("recall", magic_rep) |
|
796 | ip.define_magic("recall", magic_rep) | |
804 | ip.define_magic("rerun", magic_rerun) |
|
797 | ip.define_magic("rerun", magic_rerun) | |
805 | ip.define_magic("hist",magic_history) # Alternative name |
|
798 | ip.define_magic("hist",magic_history) # Alternative name | |
806 | ip.define_magic("history",magic_history) |
|
799 | ip.define_magic("history",magic_history) | |
807 |
|
800 | |||
808 | # XXX - ipy_completers are in quarantine, need to be updated to new apis |
|
801 | # XXX - ipy_completers are in quarantine, need to be updated to new apis | |
809 | #import ipy_completers |
|
802 | #import ipy_completers | |
810 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
|
803 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
@@ -1,2603 +1,2608 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
7 | # Copyright (C) 2008-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
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 ast |
|
23 | import ast | |
24 | import atexit |
|
24 | import atexit | |
25 | import codeop |
|
25 | import codeop | |
26 | import inspect |
|
26 | import inspect | |
27 | import os |
|
27 | import os | |
28 | import re |
|
28 | import re | |
29 | import sys |
|
29 | import sys | |
30 | import tempfile |
|
30 | import tempfile | |
31 | import types |
|
31 | import types | |
32 | from contextlib import nested |
|
32 | from contextlib import nested | |
33 |
|
33 | |||
34 | from IPython.config.configurable import Configurable |
|
34 | from IPython.config.configurable import Configurable | |
35 | from IPython.core import debugger, oinspect |
|
35 | from IPython.core import debugger, oinspect | |
36 | from IPython.core import history as ipcorehist |
|
36 | from IPython.core import history as ipcorehist | |
37 | from IPython.core import page |
|
37 | from IPython.core import page | |
38 | from IPython.core import prefilter |
|
38 | from IPython.core import prefilter | |
39 | from IPython.core import shadowns |
|
39 | from IPython.core import shadowns | |
40 | from IPython.core import ultratb |
|
40 | from IPython.core import ultratb | |
41 | from IPython.core.alias import AliasManager |
|
41 | from IPython.core.alias import AliasManager | |
42 | from IPython.core.autocall import ExitAutocall |
|
42 | from IPython.core.autocall import ExitAutocall | |
43 | from IPython.core.builtin_trap import BuiltinTrap |
|
43 | from IPython.core.builtin_trap import BuiltinTrap | |
44 | from IPython.core.compilerop import CachingCompiler |
|
44 | from IPython.core.compilerop import CachingCompiler | |
45 | from IPython.core.display_trap import DisplayTrap |
|
45 | from IPython.core.display_trap import DisplayTrap | |
46 | from IPython.core.displayhook import DisplayHook |
|
46 | from IPython.core.displayhook import DisplayHook | |
47 | from IPython.core.displaypub import DisplayPublisher |
|
47 | from IPython.core.displaypub import DisplayPublisher | |
48 | from IPython.core.error import TryNext, UsageError |
|
48 | from IPython.core.error import TryNext, UsageError | |
49 | from IPython.core.extensions import ExtensionManager |
|
49 | from IPython.core.extensions import ExtensionManager | |
50 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
50 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
51 | from IPython.core.formatters import DisplayFormatter |
|
51 | from IPython.core.formatters import DisplayFormatter | |
52 | from IPython.core.history import HistoryManager |
|
52 | from IPython.core.history import HistoryManager | |
53 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
53 | from IPython.core.inputsplitter import IPythonInputSplitter | |
54 | from IPython.core.logger import Logger |
|
54 | from IPython.core.logger import Logger | |
55 | from IPython.core.macro import Macro |
|
55 | from IPython.core.macro import Macro | |
56 | from IPython.core.magic import Magic |
|
56 | from IPython.core.magic import Magic | |
57 | from IPython.core.payload import PayloadManager |
|
57 | from IPython.core.payload import PayloadManager | |
58 | from IPython.core.plugin import PluginManager |
|
58 | from IPython.core.plugin import PluginManager | |
59 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
59 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
60 | from IPython.external.Itpl import ItplNS |
|
60 | from IPython.external.Itpl import ItplNS | |
61 | from IPython.utils import PyColorize |
|
61 | from IPython.utils import PyColorize | |
62 | from IPython.utils import io |
|
62 | from IPython.utils import io | |
63 | from IPython.utils.doctestreload import doctest_reload |
|
63 | from IPython.utils.doctestreload import doctest_reload | |
64 | from IPython.utils.io import ask_yes_no, rprint |
|
64 | from IPython.utils.io import ask_yes_no, rprint | |
65 | from IPython.utils.ipstruct import Struct |
|
65 | from IPython.utils.ipstruct import Struct | |
66 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
66 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
67 | from IPython.utils.pickleshare import PickleShareDB |
|
67 | from IPython.utils.pickleshare import PickleShareDB | |
68 | from IPython.utils.process import system, getoutput |
|
68 | from IPython.utils.process import system, getoutput | |
69 | from IPython.utils.strdispatch import StrDispatch |
|
69 | from IPython.utils.strdispatch import StrDispatch | |
70 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
70 | from IPython.utils.syspathcontext import prepended_to_syspath | |
71 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
71 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList | |
72 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
72 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
73 | List, Unicode, Instance, Type) |
|
73 | List, Unicode, Instance, Type) | |
74 | from IPython.utils.warn import warn, error, fatal |
|
74 | from IPython.utils.warn import warn, error, fatal | |
75 | import IPython.core.hooks |
|
75 | import IPython.core.hooks | |
76 |
|
76 | |||
77 | #----------------------------------------------------------------------------- |
|
77 | #----------------------------------------------------------------------------- | |
78 | # Globals |
|
78 | # Globals | |
79 | #----------------------------------------------------------------------------- |
|
79 | #----------------------------------------------------------------------------- | |
80 |
|
80 | |||
81 | # compiled regexps for autoindent management |
|
81 | # compiled regexps for autoindent management | |
82 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
82 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
83 |
|
83 | |||
84 | #----------------------------------------------------------------------------- |
|
84 | #----------------------------------------------------------------------------- | |
85 | # Utilities |
|
85 | # Utilities | |
86 | #----------------------------------------------------------------------------- |
|
86 | #----------------------------------------------------------------------------- | |
87 |
|
87 | |||
88 | # store the builtin raw_input globally, and use this always, in case user code |
|
88 | # store the builtin raw_input globally, and use this always, in case user code | |
89 | # overwrites it (like wx.py.PyShell does) |
|
89 | # overwrites it (like wx.py.PyShell does) | |
90 | raw_input_original = raw_input |
|
90 | raw_input_original = raw_input | |
91 |
|
91 | |||
92 | def softspace(file, newvalue): |
|
92 | def softspace(file, newvalue): | |
93 | """Copied from code.py, to remove the dependency""" |
|
93 | """Copied from code.py, to remove the dependency""" | |
94 |
|
94 | |||
95 | oldvalue = 0 |
|
95 | oldvalue = 0 | |
96 | try: |
|
96 | try: | |
97 | oldvalue = file.softspace |
|
97 | oldvalue = file.softspace | |
98 | except AttributeError: |
|
98 | except AttributeError: | |
99 | pass |
|
99 | pass | |
100 | try: |
|
100 | try: | |
101 | file.softspace = newvalue |
|
101 | file.softspace = newvalue | |
102 | except (AttributeError, TypeError): |
|
102 | except (AttributeError, TypeError): | |
103 | # "attribute-less object" or "read-only attributes" |
|
103 | # "attribute-less object" or "read-only attributes" | |
104 | pass |
|
104 | pass | |
105 | return oldvalue |
|
105 | return oldvalue | |
106 |
|
106 | |||
107 |
|
107 | |||
108 | def no_op(*a, **kw): pass |
|
108 | def no_op(*a, **kw): pass | |
109 |
|
109 | |||
110 | class SpaceInInput(Exception): pass |
|
110 | class SpaceInInput(Exception): pass | |
111 |
|
111 | |||
112 | class Bunch: pass |
|
112 | class Bunch: pass | |
113 |
|
113 | |||
114 |
|
114 | |||
115 | def get_default_colors(): |
|
115 | def get_default_colors(): | |
116 | if sys.platform=='darwin': |
|
116 | if sys.platform=='darwin': | |
117 | return "LightBG" |
|
117 | return "LightBG" | |
118 | elif os.name=='nt': |
|
118 | elif os.name=='nt': | |
119 | return 'Linux' |
|
119 | return 'Linux' | |
120 | else: |
|
120 | else: | |
121 | return 'Linux' |
|
121 | return 'Linux' | |
122 |
|
122 | |||
123 |
|
123 | |||
124 | class SeparateStr(Str): |
|
124 | class SeparateStr(Str): | |
125 | """A Str subclass to validate separate_in, separate_out, etc. |
|
125 | """A Str subclass to validate separate_in, separate_out, etc. | |
126 |
|
126 | |||
127 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
127 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
128 | """ |
|
128 | """ | |
129 |
|
129 | |||
130 | def validate(self, obj, value): |
|
130 | def validate(self, obj, value): | |
131 | if value == '0': value = '' |
|
131 | if value == '0': value = '' | |
132 | value = value.replace('\\n','\n') |
|
132 | value = value.replace('\\n','\n') | |
133 | return super(SeparateStr, self).validate(obj, value) |
|
133 | return super(SeparateStr, self).validate(obj, value) | |
134 |
|
134 | |||
135 | class MultipleInstanceError(Exception): |
|
135 | class MultipleInstanceError(Exception): | |
136 | pass |
|
136 | pass | |
137 |
|
137 | |||
138 | class ReadlineNoRecord(object): |
|
138 | class ReadlineNoRecord(object): | |
139 | """Context manager to execute some code, then reload readline history |
|
139 | """Context manager to execute some code, then reload readline history | |
140 | so that interactive input to the code doesn't appear when pressing up.""" |
|
140 | so that interactive input to the code doesn't appear when pressing up.""" | |
141 | def __init__(self, shell): |
|
141 | def __init__(self, shell): | |
142 | self.shell = shell |
|
142 | self.shell = shell | |
143 | self._nested_level = 0 |
|
143 | self._nested_level = 0 | |
144 |
|
144 | |||
145 | def __enter__(self): |
|
145 | def __enter__(self): | |
146 | if self._nested_level == 0: |
|
146 | if self._nested_level == 0: | |
147 | self.orig_length = self.current_length() |
|
147 | self.orig_length = self.current_length() | |
148 | self.readline_tail = self.get_readline_tail() |
|
148 | self.readline_tail = self.get_readline_tail() | |
149 | self._nested_level += 1 |
|
149 | self._nested_level += 1 | |
150 |
|
150 | |||
151 | def __exit__(self, type, value, traceback): |
|
151 | def __exit__(self, type, value, traceback): | |
152 | self._nested_level -= 1 |
|
152 | self._nested_level -= 1 | |
153 | if self._nested_level == 0: |
|
153 | if self._nested_level == 0: | |
154 | # Try clipping the end if it's got longer |
|
154 | # Try clipping the end if it's got longer | |
155 | e = self.current_length() - self.orig_length |
|
155 | e = self.current_length() - self.orig_length | |
156 | if e > 0: |
|
156 | if e > 0: | |
157 | for _ in range(e): |
|
157 | for _ in range(e): | |
158 | self.shell.readline.remove_history_item(self.orig_length) |
|
158 | self.shell.readline.remove_history_item(self.orig_length) | |
159 |
|
159 | |||
160 | # If it still doesn't match, just reload readline history. |
|
160 | # If it still doesn't match, just reload readline history. | |
161 | if self.current_length() != self.orig_length \ |
|
161 | if self.current_length() != self.orig_length \ | |
162 | or self.get_readline_tail() != self.readline_tail: |
|
162 | or self.get_readline_tail() != self.readline_tail: | |
163 | self.shell.refill_readline_hist() |
|
163 | self.shell.refill_readline_hist() | |
164 | # Returning False will cause exceptions to propagate |
|
164 | # Returning False will cause exceptions to propagate | |
165 | return False |
|
165 | return False | |
166 |
|
166 | |||
167 | def current_length(self): |
|
167 | def current_length(self): | |
168 | return self.shell.readline.get_current_history_length() |
|
168 | return self.shell.readline.get_current_history_length() | |
169 |
|
169 | |||
170 | def get_readline_tail(self, n=10): |
|
170 | def get_readline_tail(self, n=10): | |
171 | """Get the last n items in readline history.""" |
|
171 | """Get the last n items in readline history.""" | |
172 | end = self.shell.readline.get_current_history_length() + 1 |
|
172 | end = self.shell.readline.get_current_history_length() + 1 | |
173 | start = max(end-n, 1) |
|
173 | start = max(end-n, 1) | |
174 | ghi = self.shell.readline.get_history_item |
|
174 | ghi = self.shell.readline.get_history_item | |
175 | return [ghi(x) for x in range(start, end)] |
|
175 | return [ghi(x) for x in range(start, end)] | |
176 |
|
176 | |||
177 |
|
177 | |||
178 | #----------------------------------------------------------------------------- |
|
178 | #----------------------------------------------------------------------------- | |
179 | # Main IPython class |
|
179 | # Main IPython class | |
180 | #----------------------------------------------------------------------------- |
|
180 | #----------------------------------------------------------------------------- | |
181 |
|
181 | |||
182 | class InteractiveShell(Configurable, Magic): |
|
182 | class InteractiveShell(Configurable, Magic): | |
183 | """An enhanced, interactive shell for Python.""" |
|
183 | """An enhanced, interactive shell for Python.""" | |
184 |
|
184 | |||
185 | _instance = None |
|
185 | _instance = None | |
186 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
186 | autocall = Enum((0,1,2), default_value=1, config=True) | |
187 | # TODO: remove all autoindent logic and put into frontends. |
|
187 | # TODO: remove all autoindent logic and put into frontends. | |
188 | # We can't do this yet because even runlines uses the autoindent. |
|
188 | # We can't do this yet because even runlines uses the autoindent. | |
189 | autoindent = CBool(True, config=True) |
|
189 | autoindent = CBool(True, config=True) | |
190 | automagic = CBool(True, config=True) |
|
190 | automagic = CBool(True, config=True) | |
191 | cache_size = Int(1000, config=True) |
|
191 | cache_size = Int(1000, config=True) | |
192 | color_info = CBool(True, config=True) |
|
192 | color_info = CBool(True, config=True) | |
193 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
193 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
194 | default_value=get_default_colors(), config=True) |
|
194 | default_value=get_default_colors(), config=True) | |
195 | debug = CBool(False, config=True) |
|
195 | debug = CBool(False, config=True) | |
196 | deep_reload = CBool(False, config=True) |
|
196 | deep_reload = CBool(False, config=True) | |
197 | display_formatter = Instance(DisplayFormatter) |
|
197 | display_formatter = Instance(DisplayFormatter) | |
198 | displayhook_class = Type(DisplayHook) |
|
198 | displayhook_class = Type(DisplayHook) | |
199 | display_pub_class = Type(DisplayPublisher) |
|
199 | display_pub_class = Type(DisplayPublisher) | |
200 |
|
200 | |||
201 | exit_now = CBool(False) |
|
201 | exit_now = CBool(False) | |
202 | exiter = Instance(ExitAutocall) |
|
202 | exiter = Instance(ExitAutocall) | |
203 | def _exiter_default(self): |
|
203 | def _exiter_default(self): | |
204 | return ExitAutocall(self) |
|
204 | return ExitAutocall(self) | |
205 | # Monotonically increasing execution counter |
|
205 | # Monotonically increasing execution counter | |
206 | execution_count = Int(1) |
|
206 | execution_count = Int(1) | |
207 | filename = Unicode("<ipython console>") |
|
207 | filename = Unicode("<ipython console>") | |
208 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
208 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
209 |
|
209 | |||
210 | # Input splitter, to split entire cells of input into either individual |
|
210 | # Input splitter, to split entire cells of input into either individual | |
211 | # interactive statements or whole blocks. |
|
211 | # interactive statements or whole blocks. | |
212 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
212 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
213 | (), {}) |
|
213 | (), {}) | |
214 | logstart = CBool(False, config=True) |
|
214 | logstart = CBool(False, config=True) | |
215 | logfile = Unicode('', config=True) |
|
215 | logfile = Unicode('', config=True) | |
216 | logappend = Unicode('', config=True) |
|
216 | logappend = Unicode('', config=True) | |
217 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
217 | object_info_string_level = Enum((0,1,2), default_value=0, | |
218 | config=True) |
|
218 | config=True) | |
219 | pdb = CBool(False, config=True) |
|
219 | pdb = CBool(False, config=True) | |
220 |
|
220 | |||
221 | profile = Unicode('', config=True) |
|
221 | profile = Unicode('', config=True) | |
222 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
222 | prompt_in1 = Str('In [\\#]: ', config=True) | |
223 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
223 | prompt_in2 = Str(' .\\D.: ', config=True) | |
224 | prompt_out = Str('Out[\\#]: ', config=True) |
|
224 | prompt_out = Str('Out[\\#]: ', config=True) | |
225 | prompts_pad_left = CBool(True, config=True) |
|
225 | prompts_pad_left = CBool(True, config=True) | |
226 | quiet = CBool(False, config=True) |
|
226 | quiet = CBool(False, config=True) | |
227 |
|
227 | |||
228 | history_length = Int(10000, config=True) |
|
228 | history_length = Int(10000, config=True) | |
229 |
|
229 | |||
230 | # The readline stuff will eventually be moved to the terminal subclass |
|
230 | # The readline stuff will eventually be moved to the terminal subclass | |
231 | # but for now, we can't do that as readline is welded in everywhere. |
|
231 | # but for now, we can't do that as readline is welded in everywhere. | |
232 | readline_use = CBool(True, config=True) |
|
232 | readline_use = CBool(True, config=True) | |
233 | readline_merge_completions = CBool(True, config=True) |
|
233 | readline_merge_completions = CBool(True, config=True) | |
234 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
234 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) | |
235 | readline_remove_delims = Str('-/~', config=True) |
|
235 | readline_remove_delims = Str('-/~', config=True) | |
236 | readline_parse_and_bind = List([ |
|
236 | readline_parse_and_bind = List([ | |
237 | 'tab: complete', |
|
237 | 'tab: complete', | |
238 | '"\C-l": clear-screen', |
|
238 | '"\C-l": clear-screen', | |
239 | 'set show-all-if-ambiguous on', |
|
239 | 'set show-all-if-ambiguous on', | |
240 | '"\C-o": tab-insert', |
|
240 | '"\C-o": tab-insert', | |
241 | # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff |
|
241 | # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff | |
242 | # crash IPython. |
|
242 | # crash IPython. | |
243 | '"\M-o": "\d\d\d\d"', |
|
243 | '"\M-o": "\d\d\d\d"', | |
244 | '"\M-I": "\d\d\d\d"', |
|
244 | '"\M-I": "\d\d\d\d"', | |
245 | '"\C-r": reverse-search-history', |
|
245 | '"\C-r": reverse-search-history', | |
246 | '"\C-s": forward-search-history', |
|
246 | '"\C-s": forward-search-history', | |
247 | '"\C-p": history-search-backward', |
|
247 | '"\C-p": history-search-backward', | |
248 | '"\C-n": history-search-forward', |
|
248 | '"\C-n": history-search-forward', | |
249 | '"\e[A": history-search-backward', |
|
249 | '"\e[A": history-search-backward', | |
250 | '"\e[B": history-search-forward', |
|
250 | '"\e[B": history-search-forward', | |
251 | '"\C-k": kill-line', |
|
251 | '"\C-k": kill-line', | |
252 | '"\C-u": unix-line-discard', |
|
252 | '"\C-u": unix-line-discard', | |
253 | ], allow_none=False, config=True) |
|
253 | ], allow_none=False, config=True) | |
254 |
|
254 | |||
255 | # TODO: this part of prompt management should be moved to the frontends. |
|
255 | # TODO: this part of prompt management should be moved to the frontends. | |
256 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
256 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
257 | separate_in = SeparateStr('\n', config=True) |
|
257 | separate_in = SeparateStr('\n', config=True) | |
258 | separate_out = SeparateStr('', config=True) |
|
258 | separate_out = SeparateStr('', config=True) | |
259 | separate_out2 = SeparateStr('', config=True) |
|
259 | separate_out2 = SeparateStr('', config=True) | |
260 | wildcards_case_sensitive = CBool(True, config=True) |
|
260 | wildcards_case_sensitive = CBool(True, config=True) | |
261 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
261 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
262 | default_value='Context', config=True) |
|
262 | default_value='Context', config=True) | |
263 |
|
263 | |||
264 | # Subcomponents of InteractiveShell |
|
264 | # Subcomponents of InteractiveShell | |
265 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
265 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
266 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
266 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
267 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
267 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
268 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
268 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
269 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
269 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
270 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
270 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
271 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
271 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
272 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
272 | history_manager = Instance('IPython.core.history.HistoryManager') | |
273 |
|
273 | |||
274 | # Private interface |
|
274 | # Private interface | |
275 | _post_execute = Instance(dict) |
|
275 | _post_execute = Instance(dict) | |
276 |
|
276 | |||
277 | def __init__(self, config=None, ipython_dir=None, |
|
277 | def __init__(self, config=None, ipython_dir=None, | |
278 | user_ns=None, user_global_ns=None, |
|
278 | user_ns=None, user_global_ns=None, | |
279 | custom_exceptions=((), None)): |
|
279 | custom_exceptions=((), None)): | |
280 |
|
280 | |||
281 | # This is where traits with a config_key argument are updated |
|
281 | # This is where traits with a config_key argument are updated | |
282 | # from the values on config. |
|
282 | # from the values on config. | |
283 | super(InteractiveShell, self).__init__(config=config) |
|
283 | super(InteractiveShell, self).__init__(config=config) | |
284 |
|
284 | |||
285 | # These are relatively independent and stateless |
|
285 | # These are relatively independent and stateless | |
286 | self.init_ipython_dir(ipython_dir) |
|
286 | self.init_ipython_dir(ipython_dir) | |
287 | self.init_instance_attrs() |
|
287 | self.init_instance_attrs() | |
288 | self.init_environment() |
|
288 | self.init_environment() | |
289 |
|
289 | |||
290 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
290 | # Create namespaces (user_ns, user_global_ns, etc.) | |
291 | self.init_create_namespaces(user_ns, user_global_ns) |
|
291 | self.init_create_namespaces(user_ns, user_global_ns) | |
292 | # This has to be done after init_create_namespaces because it uses |
|
292 | # This has to be done after init_create_namespaces because it uses | |
293 | # something in self.user_ns, but before init_sys_modules, which |
|
293 | # something in self.user_ns, but before init_sys_modules, which | |
294 | # is the first thing to modify sys. |
|
294 | # is the first thing to modify sys. | |
295 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
295 | # TODO: When we override sys.stdout and sys.stderr before this class | |
296 | # is created, we are saving the overridden ones here. Not sure if this |
|
296 | # is created, we are saving the overridden ones here. Not sure if this | |
297 | # is what we want to do. |
|
297 | # is what we want to do. | |
298 | self.save_sys_module_state() |
|
298 | self.save_sys_module_state() | |
299 | self.init_sys_modules() |
|
299 | self.init_sys_modules() | |
300 |
|
300 | |||
301 | # While we're trying to have each part of the code directly access what |
|
301 | # While we're trying to have each part of the code directly access what | |
302 | # it needs without keeping redundant references to objects, we have too |
|
302 | # it needs without keeping redundant references to objects, we have too | |
303 | # much legacy code that expects ip.db to exist. |
|
303 | # much legacy code that expects ip.db to exist. | |
304 | self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db')) |
|
304 | self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db')) | |
305 |
|
305 | |||
306 | self.init_history() |
|
306 | self.init_history() | |
307 | self.init_encoding() |
|
307 | self.init_encoding() | |
308 | self.init_prefilter() |
|
308 | self.init_prefilter() | |
309 |
|
309 | |||
310 | Magic.__init__(self, self) |
|
310 | Magic.__init__(self, self) | |
311 |
|
311 | |||
312 | self.init_syntax_highlighting() |
|
312 | self.init_syntax_highlighting() | |
313 | self.init_hooks() |
|
313 | self.init_hooks() | |
314 | self.init_pushd_popd_magic() |
|
314 | self.init_pushd_popd_magic() | |
315 | # self.init_traceback_handlers use to be here, but we moved it below |
|
315 | # self.init_traceback_handlers use to be here, but we moved it below | |
316 | # because it and init_io have to come after init_readline. |
|
316 | # because it and init_io have to come after init_readline. | |
317 | self.init_user_ns() |
|
317 | self.init_user_ns() | |
318 | self.init_logger() |
|
318 | self.init_logger() | |
319 | self.init_alias() |
|
319 | self.init_alias() | |
320 | self.init_builtins() |
|
320 | self.init_builtins() | |
321 |
|
321 | |||
322 | # pre_config_initialization |
|
322 | # pre_config_initialization | |
323 |
|
323 | |||
324 | # The next section should contain everything that was in ipmaker. |
|
324 | # The next section should contain everything that was in ipmaker. | |
325 | self.init_logstart() |
|
325 | self.init_logstart() | |
326 |
|
326 | |||
327 | # The following was in post_config_initialization |
|
327 | # The following was in post_config_initialization | |
328 | self.init_inspector() |
|
328 | self.init_inspector() | |
329 | # init_readline() must come before init_io(), because init_io uses |
|
329 | # init_readline() must come before init_io(), because init_io uses | |
330 | # readline related things. |
|
330 | # readline related things. | |
331 | self.init_readline() |
|
331 | self.init_readline() | |
332 | # init_completer must come after init_readline, because it needs to |
|
332 | # init_completer must come after init_readline, because it needs to | |
333 | # know whether readline is present or not system-wide to configure the |
|
333 | # know whether readline is present or not system-wide to configure the | |
334 | # completers, since the completion machinery can now operate |
|
334 | # completers, since the completion machinery can now operate | |
335 | # independently of readline (e.g. over the network) |
|
335 | # independently of readline (e.g. over the network) | |
336 | self.init_completer() |
|
336 | self.init_completer() | |
337 | # TODO: init_io() needs to happen before init_traceback handlers |
|
337 | # TODO: init_io() needs to happen before init_traceback handlers | |
338 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
338 | # because the traceback handlers hardcode the stdout/stderr streams. | |
339 | # This logic in in debugger.Pdb and should eventually be changed. |
|
339 | # This logic in in debugger.Pdb and should eventually be changed. | |
340 | self.init_io() |
|
340 | self.init_io() | |
341 | self.init_traceback_handlers(custom_exceptions) |
|
341 | self.init_traceback_handlers(custom_exceptions) | |
342 | self.init_prompts() |
|
342 | self.init_prompts() | |
343 | self.init_display_formatter() |
|
343 | self.init_display_formatter() | |
344 | self.init_display_pub() |
|
344 | self.init_display_pub() | |
345 | self.init_displayhook() |
|
345 | self.init_displayhook() | |
346 | self.init_reload_doctest() |
|
346 | self.init_reload_doctest() | |
347 | self.init_magics() |
|
347 | self.init_magics() | |
348 | self.init_pdb() |
|
348 | self.init_pdb() | |
349 | self.init_extension_manager() |
|
349 | self.init_extension_manager() | |
350 | self.init_plugin_manager() |
|
350 | self.init_plugin_manager() | |
351 | self.init_payload() |
|
351 | self.init_payload() | |
352 | self.hooks.late_startup_hook() |
|
352 | self.hooks.late_startup_hook() | |
353 | atexit.register(self.atexit_operations) |
|
353 | atexit.register(self.atexit_operations) | |
354 |
|
354 | |||
355 | @classmethod |
|
355 | @classmethod | |
356 | def instance(cls, *args, **kwargs): |
|
356 | def instance(cls, *args, **kwargs): | |
357 | """Returns a global InteractiveShell instance.""" |
|
357 | """Returns a global InteractiveShell instance.""" | |
358 | if cls._instance is None: |
|
358 | if cls._instance is None: | |
359 | inst = cls(*args, **kwargs) |
|
359 | inst = cls(*args, **kwargs) | |
360 | # Now make sure that the instance will also be returned by |
|
360 | # Now make sure that the instance will also be returned by | |
361 | # the subclasses instance attribute. |
|
361 | # the subclasses instance attribute. | |
362 | for subclass in cls.mro(): |
|
362 | for subclass in cls.mro(): | |
363 | if issubclass(cls, subclass) and \ |
|
363 | if issubclass(cls, subclass) and \ | |
364 | issubclass(subclass, InteractiveShell): |
|
364 | issubclass(subclass, InteractiveShell): | |
365 | subclass._instance = inst |
|
365 | subclass._instance = inst | |
366 | else: |
|
366 | else: | |
367 | break |
|
367 | break | |
368 | if isinstance(cls._instance, cls): |
|
368 | if isinstance(cls._instance, cls): | |
369 | return cls._instance |
|
369 | return cls._instance | |
370 | else: |
|
370 | else: | |
371 | raise MultipleInstanceError( |
|
371 | raise MultipleInstanceError( | |
372 | 'Multiple incompatible subclass instances of ' |
|
372 | 'Multiple incompatible subclass instances of ' | |
373 | 'InteractiveShell are being created.' |
|
373 | 'InteractiveShell are being created.' | |
374 | ) |
|
374 | ) | |
375 |
|
375 | |||
376 | @classmethod |
|
376 | @classmethod | |
377 | def initialized(cls): |
|
377 | def initialized(cls): | |
378 | return hasattr(cls, "_instance") |
|
378 | return hasattr(cls, "_instance") | |
379 |
|
379 | |||
380 | def get_ipython(self): |
|
380 | def get_ipython(self): | |
381 | """Return the currently running IPython instance.""" |
|
381 | """Return the currently running IPython instance.""" | |
382 | return self |
|
382 | return self | |
383 |
|
383 | |||
384 | #------------------------------------------------------------------------- |
|
384 | #------------------------------------------------------------------------- | |
385 | # Trait changed handlers |
|
385 | # Trait changed handlers | |
386 | #------------------------------------------------------------------------- |
|
386 | #------------------------------------------------------------------------- | |
387 |
|
387 | |||
388 | def _ipython_dir_changed(self, name, new): |
|
388 | def _ipython_dir_changed(self, name, new): | |
389 | if not os.path.isdir(new): |
|
389 | if not os.path.isdir(new): | |
390 | os.makedirs(new, mode = 0777) |
|
390 | os.makedirs(new, mode = 0777) | |
391 |
|
391 | |||
392 | def set_autoindent(self,value=None): |
|
392 | def set_autoindent(self,value=None): | |
393 | """Set the autoindent flag, checking for readline support. |
|
393 | """Set the autoindent flag, checking for readline support. | |
394 |
|
394 | |||
395 | If called with no arguments, it acts as a toggle.""" |
|
395 | If called with no arguments, it acts as a toggle.""" | |
396 |
|
396 | |||
397 | if not self.has_readline: |
|
397 | if not self.has_readline: | |
398 | if os.name == 'posix': |
|
398 | if os.name == 'posix': | |
399 | warn("The auto-indent feature requires the readline library") |
|
399 | warn("The auto-indent feature requires the readline library") | |
400 | self.autoindent = 0 |
|
400 | self.autoindent = 0 | |
401 | return |
|
401 | return | |
402 | if value is None: |
|
402 | if value is None: | |
403 | self.autoindent = not self.autoindent |
|
403 | self.autoindent = not self.autoindent | |
404 | else: |
|
404 | else: | |
405 | self.autoindent = value |
|
405 | self.autoindent = value | |
406 |
|
406 | |||
407 | #------------------------------------------------------------------------- |
|
407 | #------------------------------------------------------------------------- | |
408 | # init_* methods called by __init__ |
|
408 | # init_* methods called by __init__ | |
409 | #------------------------------------------------------------------------- |
|
409 | #------------------------------------------------------------------------- | |
410 |
|
410 | |||
411 | def init_ipython_dir(self, ipython_dir): |
|
411 | def init_ipython_dir(self, ipython_dir): | |
412 | if ipython_dir is not None: |
|
412 | if ipython_dir is not None: | |
413 | self.ipython_dir = ipython_dir |
|
413 | self.ipython_dir = ipython_dir | |
414 | self.config.Global.ipython_dir = self.ipython_dir |
|
414 | self.config.Global.ipython_dir = self.ipython_dir | |
415 | return |
|
415 | return | |
416 |
|
416 | |||
417 | if hasattr(self.config.Global, 'ipython_dir'): |
|
417 | if hasattr(self.config.Global, 'ipython_dir'): | |
418 | self.ipython_dir = self.config.Global.ipython_dir |
|
418 | self.ipython_dir = self.config.Global.ipython_dir | |
419 | else: |
|
419 | else: | |
420 | self.ipython_dir = get_ipython_dir() |
|
420 | self.ipython_dir = get_ipython_dir() | |
421 |
|
421 | |||
422 | # All children can just read this |
|
422 | # All children can just read this | |
423 | self.config.Global.ipython_dir = self.ipython_dir |
|
423 | self.config.Global.ipython_dir = self.ipython_dir | |
424 |
|
424 | |||
425 | def init_instance_attrs(self): |
|
425 | def init_instance_attrs(self): | |
426 | self.more = False |
|
426 | self.more = False | |
427 |
|
427 | |||
428 | # command compiler |
|
428 | # command compiler | |
429 | self.compile = CachingCompiler() |
|
429 | self.compile = CachingCompiler() | |
430 |
|
430 | |||
431 | # User input buffers |
|
431 | # User input buffers | |
432 | # NOTE: these variables are slated for full removal, once we are 100% |
|
432 | # NOTE: these variables are slated for full removal, once we are 100% | |
433 | # sure that the new execution logic is solid. We will delte runlines, |
|
433 | # sure that the new execution logic is solid. We will delte runlines, | |
434 | # push_line and these buffers, as all input will be managed by the |
|
434 | # push_line and these buffers, as all input will be managed by the | |
435 | # frontends via an inputsplitter instance. |
|
435 | # frontends via an inputsplitter instance. | |
436 | self.buffer = [] |
|
436 | self.buffer = [] | |
437 | self.buffer_raw = [] |
|
437 | self.buffer_raw = [] | |
438 |
|
438 | |||
439 | # Make an empty namespace, which extension writers can rely on both |
|
439 | # Make an empty namespace, which extension writers can rely on both | |
440 | # existing and NEVER being used by ipython itself. This gives them a |
|
440 | # existing and NEVER being used by ipython itself. This gives them a | |
441 | # convenient location for storing additional information and state |
|
441 | # convenient location for storing additional information and state | |
442 | # their extensions may require, without fear of collisions with other |
|
442 | # their extensions may require, without fear of collisions with other | |
443 | # ipython names that may develop later. |
|
443 | # ipython names that may develop later. | |
444 | self.meta = Struct() |
|
444 | self.meta = Struct() | |
445 |
|
445 | |||
446 | # Temporary files used for various purposes. Deleted at exit. |
|
446 | # Temporary files used for various purposes. Deleted at exit. | |
447 | self.tempfiles = [] |
|
447 | self.tempfiles = [] | |
448 |
|
448 | |||
449 | # Keep track of readline usage (later set by init_readline) |
|
449 | # Keep track of readline usage (later set by init_readline) | |
450 | self.has_readline = False |
|
450 | self.has_readline = False | |
451 |
|
451 | |||
452 | # keep track of where we started running (mainly for crash post-mortem) |
|
452 | # keep track of where we started running (mainly for crash post-mortem) | |
453 | # This is not being used anywhere currently. |
|
453 | # This is not being used anywhere currently. | |
454 | self.starting_dir = os.getcwd() |
|
454 | self.starting_dir = os.getcwd() | |
455 |
|
455 | |||
456 | # Indentation management |
|
456 | # Indentation management | |
457 | self.indent_current_nsp = 0 |
|
457 | self.indent_current_nsp = 0 | |
458 |
|
458 | |||
459 | # Dict to track post-execution functions that have been registered |
|
459 | # Dict to track post-execution functions that have been registered | |
460 | self._post_execute = {} |
|
460 | self._post_execute = {} | |
461 |
|
461 | |||
462 | def init_environment(self): |
|
462 | def init_environment(self): | |
463 | """Any changes we need to make to the user's environment.""" |
|
463 | """Any changes we need to make to the user's environment.""" | |
464 | pass |
|
464 | pass | |
465 |
|
465 | |||
466 | def init_encoding(self): |
|
466 | def init_encoding(self): | |
467 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
467 | # Get system encoding at startup time. Certain terminals (like Emacs | |
468 | # under Win32 have it set to None, and we need to have a known valid |
|
468 | # under Win32 have it set to None, and we need to have a known valid | |
469 | # encoding to use in the raw_input() method |
|
469 | # encoding to use in the raw_input() method | |
470 | try: |
|
470 | try: | |
471 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
471 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
472 | except AttributeError: |
|
472 | except AttributeError: | |
473 | self.stdin_encoding = 'ascii' |
|
473 | self.stdin_encoding = 'ascii' | |
474 |
|
474 | |||
475 | def init_syntax_highlighting(self): |
|
475 | def init_syntax_highlighting(self): | |
476 | # Python source parser/formatter for syntax highlighting |
|
476 | # Python source parser/formatter for syntax highlighting | |
477 | pyformat = PyColorize.Parser().format |
|
477 | pyformat = PyColorize.Parser().format | |
478 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
478 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
479 |
|
479 | |||
480 | def init_pushd_popd_magic(self): |
|
480 | def init_pushd_popd_magic(self): | |
481 | # for pushd/popd management |
|
481 | # for pushd/popd management | |
482 | try: |
|
482 | try: | |
483 | self.home_dir = get_home_dir() |
|
483 | self.home_dir = get_home_dir() | |
484 | except HomeDirError, msg: |
|
484 | except HomeDirError, msg: | |
485 | fatal(msg) |
|
485 | fatal(msg) | |
486 |
|
486 | |||
487 | self.dir_stack = [] |
|
487 | self.dir_stack = [] | |
488 |
|
488 | |||
489 | def init_logger(self): |
|
489 | def init_logger(self): | |
490 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
490 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
491 | logmode='rotate') |
|
491 | logmode='rotate') | |
492 |
|
492 | |||
493 | def init_logstart(self): |
|
493 | def init_logstart(self): | |
494 | """Initialize logging in case it was requested at the command line. |
|
494 | """Initialize logging in case it was requested at the command line. | |
495 | """ |
|
495 | """ | |
496 | if self.logappend: |
|
496 | if self.logappend: | |
497 | self.magic_logstart(self.logappend + ' append') |
|
497 | self.magic_logstart(self.logappend + ' append') | |
498 | elif self.logfile: |
|
498 | elif self.logfile: | |
499 | self.magic_logstart(self.logfile) |
|
499 | self.magic_logstart(self.logfile) | |
500 | elif self.logstart: |
|
500 | elif self.logstart: | |
501 | self.magic_logstart() |
|
501 | self.magic_logstart() | |
502 |
|
502 | |||
503 | def init_builtins(self): |
|
503 | def init_builtins(self): | |
504 | self.builtin_trap = BuiltinTrap(shell=self) |
|
504 | self.builtin_trap = BuiltinTrap(shell=self) | |
505 |
|
505 | |||
506 | def init_inspector(self): |
|
506 | def init_inspector(self): | |
507 | # Object inspector |
|
507 | # Object inspector | |
508 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
508 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
509 | PyColorize.ANSICodeColors, |
|
509 | PyColorize.ANSICodeColors, | |
510 | 'NoColor', |
|
510 | 'NoColor', | |
511 | self.object_info_string_level) |
|
511 | self.object_info_string_level) | |
512 |
|
512 | |||
513 | def init_io(self): |
|
513 | def init_io(self): | |
514 | # This will just use sys.stdout and sys.stderr. If you want to |
|
514 | # This will just use sys.stdout and sys.stderr. If you want to | |
515 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
515 | # override sys.stdout and sys.stderr themselves, you need to do that | |
516 | # *before* instantiating this class, because Term holds onto |
|
516 | # *before* instantiating this class, because Term holds onto | |
517 | # references to the underlying streams. |
|
517 | # references to the underlying streams. | |
518 | if sys.platform == 'win32' and self.has_readline: |
|
518 | if sys.platform == 'win32' and self.has_readline: | |
519 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
519 | Term = io.IOTerm(cout=self.readline._outputfile, | |
520 | cerr=self.readline._outputfile) |
|
520 | cerr=self.readline._outputfile) | |
521 | else: |
|
521 | else: | |
522 | Term = io.IOTerm() |
|
522 | Term = io.IOTerm() | |
523 | io.Term = Term |
|
523 | io.Term = Term | |
524 |
|
524 | |||
525 | def init_prompts(self): |
|
525 | def init_prompts(self): | |
526 | # TODO: This is a pass for now because the prompts are managed inside |
|
526 | # TODO: This is a pass for now because the prompts are managed inside | |
527 | # the DisplayHook. Once there is a separate prompt manager, this |
|
527 | # the DisplayHook. Once there is a separate prompt manager, this | |
528 | # will initialize that object and all prompt related information. |
|
528 | # will initialize that object and all prompt related information. | |
529 | pass |
|
529 | pass | |
530 |
|
530 | |||
531 | def init_display_formatter(self): |
|
531 | def init_display_formatter(self): | |
532 | self.display_formatter = DisplayFormatter(config=self.config) |
|
532 | self.display_formatter = DisplayFormatter(config=self.config) | |
533 |
|
533 | |||
534 | def init_display_pub(self): |
|
534 | def init_display_pub(self): | |
535 | self.display_pub = self.display_pub_class(config=self.config) |
|
535 | self.display_pub = self.display_pub_class(config=self.config) | |
536 |
|
536 | |||
537 | def init_displayhook(self): |
|
537 | def init_displayhook(self): | |
538 | # Initialize displayhook, set in/out prompts and printing system |
|
538 | # Initialize displayhook, set in/out prompts and printing system | |
539 | self.displayhook = self.displayhook_class( |
|
539 | self.displayhook = self.displayhook_class( | |
540 | config=self.config, |
|
540 | config=self.config, | |
541 | shell=self, |
|
541 | shell=self, | |
542 | cache_size=self.cache_size, |
|
542 | cache_size=self.cache_size, | |
543 | input_sep = self.separate_in, |
|
543 | input_sep = self.separate_in, | |
544 | output_sep = self.separate_out, |
|
544 | output_sep = self.separate_out, | |
545 | output_sep2 = self.separate_out2, |
|
545 | output_sep2 = self.separate_out2, | |
546 | ps1 = self.prompt_in1, |
|
546 | ps1 = self.prompt_in1, | |
547 | ps2 = self.prompt_in2, |
|
547 | ps2 = self.prompt_in2, | |
548 | ps_out = self.prompt_out, |
|
548 | ps_out = self.prompt_out, | |
549 | pad_left = self.prompts_pad_left |
|
549 | pad_left = self.prompts_pad_left | |
550 | ) |
|
550 | ) | |
551 | # This is a context manager that installs/revmoes the displayhook at |
|
551 | # This is a context manager that installs/revmoes the displayhook at | |
552 | # the appropriate time. |
|
552 | # the appropriate time. | |
553 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
553 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
554 |
|
554 | |||
555 | def init_reload_doctest(self): |
|
555 | def init_reload_doctest(self): | |
556 | # Do a proper resetting of doctest, including the necessary displayhook |
|
556 | # Do a proper resetting of doctest, including the necessary displayhook | |
557 | # monkeypatching |
|
557 | # monkeypatching | |
558 | try: |
|
558 | try: | |
559 | doctest_reload() |
|
559 | doctest_reload() | |
560 | except ImportError: |
|
560 | except ImportError: | |
561 | warn("doctest module does not exist.") |
|
561 | warn("doctest module does not exist.") | |
562 |
|
562 | |||
563 | #------------------------------------------------------------------------- |
|
563 | #------------------------------------------------------------------------- | |
564 | # Things related to injections into the sys module |
|
564 | # Things related to injections into the sys module | |
565 | #------------------------------------------------------------------------- |
|
565 | #------------------------------------------------------------------------- | |
566 |
|
566 | |||
567 | def save_sys_module_state(self): |
|
567 | def save_sys_module_state(self): | |
568 | """Save the state of hooks in the sys module. |
|
568 | """Save the state of hooks in the sys module. | |
569 |
|
569 | |||
570 | This has to be called after self.user_ns is created. |
|
570 | This has to be called after self.user_ns is created. | |
571 | """ |
|
571 | """ | |
572 | self._orig_sys_module_state = {} |
|
572 | self._orig_sys_module_state = {} | |
573 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
573 | self._orig_sys_module_state['stdin'] = sys.stdin | |
574 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
574 | self._orig_sys_module_state['stdout'] = sys.stdout | |
575 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
575 | self._orig_sys_module_state['stderr'] = sys.stderr | |
576 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
576 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
577 | try: |
|
577 | try: | |
578 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
578 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
579 | except KeyError: |
|
579 | except KeyError: | |
580 | pass |
|
580 | pass | |
581 |
|
581 | |||
582 | def restore_sys_module_state(self): |
|
582 | def restore_sys_module_state(self): | |
583 | """Restore the state of the sys module.""" |
|
583 | """Restore the state of the sys module.""" | |
584 | try: |
|
584 | try: | |
585 | for k, v in self._orig_sys_module_state.iteritems(): |
|
585 | for k, v in self._orig_sys_module_state.iteritems(): | |
586 | setattr(sys, k, v) |
|
586 | setattr(sys, k, v) | |
587 | except AttributeError: |
|
587 | except AttributeError: | |
588 | pass |
|
588 | pass | |
589 | # Reset what what done in self.init_sys_modules |
|
589 | # Reset what what done in self.init_sys_modules | |
590 | try: |
|
590 | try: | |
591 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
591 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
592 | except (AttributeError, KeyError): |
|
592 | except (AttributeError, KeyError): | |
593 | pass |
|
593 | pass | |
594 |
|
594 | |||
595 | #------------------------------------------------------------------------- |
|
595 | #------------------------------------------------------------------------- | |
596 | # Things related to hooks |
|
596 | # Things related to hooks | |
597 | #------------------------------------------------------------------------- |
|
597 | #------------------------------------------------------------------------- | |
598 |
|
598 | |||
599 | def init_hooks(self): |
|
599 | def init_hooks(self): | |
600 | # hooks holds pointers used for user-side customizations |
|
600 | # hooks holds pointers used for user-side customizations | |
601 | self.hooks = Struct() |
|
601 | self.hooks = Struct() | |
602 |
|
602 | |||
603 | self.strdispatchers = {} |
|
603 | self.strdispatchers = {} | |
604 |
|
604 | |||
605 | # Set all default hooks, defined in the IPython.hooks module. |
|
605 | # Set all default hooks, defined in the IPython.hooks module. | |
606 | hooks = IPython.core.hooks |
|
606 | hooks = IPython.core.hooks | |
607 | for hook_name in hooks.__all__: |
|
607 | for hook_name in hooks.__all__: | |
608 | # default hooks have priority 100, i.e. low; user hooks should have |
|
608 | # default hooks have priority 100, i.e. low; user hooks should have | |
609 | # 0-100 priority |
|
609 | # 0-100 priority | |
610 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
610 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
611 |
|
611 | |||
612 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
612 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
613 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
613 | """set_hook(name,hook) -> sets an internal IPython hook. | |
614 |
|
614 | |||
615 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
615 | IPython exposes some of its internal API as user-modifiable hooks. By | |
616 | adding your function to one of these hooks, you can modify IPython's |
|
616 | adding your function to one of these hooks, you can modify IPython's | |
617 | behavior to call at runtime your own routines.""" |
|
617 | behavior to call at runtime your own routines.""" | |
618 |
|
618 | |||
619 | # At some point in the future, this should validate the hook before it |
|
619 | # At some point in the future, this should validate the hook before it | |
620 | # accepts it. Probably at least check that the hook takes the number |
|
620 | # accepts it. Probably at least check that the hook takes the number | |
621 | # of args it's supposed to. |
|
621 | # of args it's supposed to. | |
622 |
|
622 | |||
623 | f = types.MethodType(hook,self) |
|
623 | f = types.MethodType(hook,self) | |
624 |
|
624 | |||
625 | # check if the hook is for strdispatcher first |
|
625 | # check if the hook is for strdispatcher first | |
626 | if str_key is not None: |
|
626 | if str_key is not None: | |
627 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
627 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
628 | sdp.add_s(str_key, f, priority ) |
|
628 | sdp.add_s(str_key, f, priority ) | |
629 | self.strdispatchers[name] = sdp |
|
629 | self.strdispatchers[name] = sdp | |
630 | return |
|
630 | return | |
631 | if re_key is not None: |
|
631 | if re_key is not None: | |
632 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
632 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
633 | sdp.add_re(re.compile(re_key), f, priority ) |
|
633 | sdp.add_re(re.compile(re_key), f, priority ) | |
634 | self.strdispatchers[name] = sdp |
|
634 | self.strdispatchers[name] = sdp | |
635 | return |
|
635 | return | |
636 |
|
636 | |||
637 | dp = getattr(self.hooks, name, None) |
|
637 | dp = getattr(self.hooks, name, None) | |
638 | if name not in IPython.core.hooks.__all__: |
|
638 | if name not in IPython.core.hooks.__all__: | |
639 | print "Warning! Hook '%s' is not one of %s" % \ |
|
639 | print "Warning! Hook '%s' is not one of %s" % \ | |
640 | (name, IPython.core.hooks.__all__ ) |
|
640 | (name, IPython.core.hooks.__all__ ) | |
641 | if not dp: |
|
641 | if not dp: | |
642 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
642 | dp = IPython.core.hooks.CommandChainDispatcher() | |
643 |
|
643 | |||
644 | try: |
|
644 | try: | |
645 | dp.add(f,priority) |
|
645 | dp.add(f,priority) | |
646 | except AttributeError: |
|
646 | except AttributeError: | |
647 | # it was not commandchain, plain old func - replace |
|
647 | # it was not commandchain, plain old func - replace | |
648 | dp = f |
|
648 | dp = f | |
649 |
|
649 | |||
650 | setattr(self.hooks,name, dp) |
|
650 | setattr(self.hooks,name, dp) | |
651 |
|
651 | |||
652 | def register_post_execute(self, func): |
|
652 | def register_post_execute(self, func): | |
653 | """Register a function for calling after code execution. |
|
653 | """Register a function for calling after code execution. | |
654 | """ |
|
654 | """ | |
655 | if not callable(func): |
|
655 | if not callable(func): | |
656 | raise ValueError('argument %s must be callable' % func) |
|
656 | raise ValueError('argument %s must be callable' % func) | |
657 | self._post_execute[func] = True |
|
657 | self._post_execute[func] = True | |
658 |
|
658 | |||
659 | #------------------------------------------------------------------------- |
|
659 | #------------------------------------------------------------------------- | |
660 | # Things related to the "main" module |
|
660 | # Things related to the "main" module | |
661 | #------------------------------------------------------------------------- |
|
661 | #------------------------------------------------------------------------- | |
662 |
|
662 | |||
663 | def new_main_mod(self,ns=None): |
|
663 | def new_main_mod(self,ns=None): | |
664 | """Return a new 'main' module object for user code execution. |
|
664 | """Return a new 'main' module object for user code execution. | |
665 | """ |
|
665 | """ | |
666 | main_mod = self._user_main_module |
|
666 | main_mod = self._user_main_module | |
667 | init_fakemod_dict(main_mod,ns) |
|
667 | init_fakemod_dict(main_mod,ns) | |
668 | return main_mod |
|
668 | return main_mod | |
669 |
|
669 | |||
670 | def cache_main_mod(self,ns,fname): |
|
670 | def cache_main_mod(self,ns,fname): | |
671 | """Cache a main module's namespace. |
|
671 | """Cache a main module's namespace. | |
672 |
|
672 | |||
673 | When scripts are executed via %run, we must keep a reference to the |
|
673 | When scripts are executed via %run, we must keep a reference to the | |
674 | namespace of their __main__ module (a FakeModule instance) around so |
|
674 | namespace of their __main__ module (a FakeModule instance) around so | |
675 | that Python doesn't clear it, rendering objects defined therein |
|
675 | that Python doesn't clear it, rendering objects defined therein | |
676 | useless. |
|
676 | useless. | |
677 |
|
677 | |||
678 | This method keeps said reference in a private dict, keyed by the |
|
678 | This method keeps said reference in a private dict, keyed by the | |
679 | absolute path of the module object (which corresponds to the script |
|
679 | absolute path of the module object (which corresponds to the script | |
680 | path). This way, for multiple executions of the same script we only |
|
680 | path). This way, for multiple executions of the same script we only | |
681 | keep one copy of the namespace (the last one), thus preventing memory |
|
681 | keep one copy of the namespace (the last one), thus preventing memory | |
682 | leaks from old references while allowing the objects from the last |
|
682 | leaks from old references while allowing the objects from the last | |
683 | execution to be accessible. |
|
683 | execution to be accessible. | |
684 |
|
684 | |||
685 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
685 | Note: we can not allow the actual FakeModule instances to be deleted, | |
686 | because of how Python tears down modules (it hard-sets all their |
|
686 | because of how Python tears down modules (it hard-sets all their | |
687 | references to None without regard for reference counts). This method |
|
687 | references to None without regard for reference counts). This method | |
688 | must therefore make a *copy* of the given namespace, to allow the |
|
688 | must therefore make a *copy* of the given namespace, to allow the | |
689 | original module's __dict__ to be cleared and reused. |
|
689 | original module's __dict__ to be cleared and reused. | |
690 |
|
690 | |||
691 |
|
691 | |||
692 | Parameters |
|
692 | Parameters | |
693 | ---------- |
|
693 | ---------- | |
694 | ns : a namespace (a dict, typically) |
|
694 | ns : a namespace (a dict, typically) | |
695 |
|
695 | |||
696 | fname : str |
|
696 | fname : str | |
697 | Filename associated with the namespace. |
|
697 | Filename associated with the namespace. | |
698 |
|
698 | |||
699 | Examples |
|
699 | Examples | |
700 | -------- |
|
700 | -------- | |
701 |
|
701 | |||
702 | In [10]: import IPython |
|
702 | In [10]: import IPython | |
703 |
|
703 | |||
704 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
704 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
705 |
|
705 | |||
706 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
706 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
707 | Out[12]: True |
|
707 | Out[12]: True | |
708 | """ |
|
708 | """ | |
709 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
709 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
710 |
|
710 | |||
711 | def clear_main_mod_cache(self): |
|
711 | def clear_main_mod_cache(self): | |
712 | """Clear the cache of main modules. |
|
712 | """Clear the cache of main modules. | |
713 |
|
713 | |||
714 | Mainly for use by utilities like %reset. |
|
714 | Mainly for use by utilities like %reset. | |
715 |
|
715 | |||
716 | Examples |
|
716 | Examples | |
717 | -------- |
|
717 | -------- | |
718 |
|
718 | |||
719 | In [15]: import IPython |
|
719 | In [15]: import IPython | |
720 |
|
720 | |||
721 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
721 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
722 |
|
722 | |||
723 | In [17]: len(_ip._main_ns_cache) > 0 |
|
723 | In [17]: len(_ip._main_ns_cache) > 0 | |
724 | Out[17]: True |
|
724 | Out[17]: True | |
725 |
|
725 | |||
726 | In [18]: _ip.clear_main_mod_cache() |
|
726 | In [18]: _ip.clear_main_mod_cache() | |
727 |
|
727 | |||
728 | In [19]: len(_ip._main_ns_cache) == 0 |
|
728 | In [19]: len(_ip._main_ns_cache) == 0 | |
729 | Out[19]: True |
|
729 | Out[19]: True | |
730 | """ |
|
730 | """ | |
731 | self._main_ns_cache.clear() |
|
731 | self._main_ns_cache.clear() | |
732 |
|
732 | |||
733 | #------------------------------------------------------------------------- |
|
733 | #------------------------------------------------------------------------- | |
734 | # Things related to debugging |
|
734 | # Things related to debugging | |
735 | #------------------------------------------------------------------------- |
|
735 | #------------------------------------------------------------------------- | |
736 |
|
736 | |||
737 | def init_pdb(self): |
|
737 | def init_pdb(self): | |
738 | # Set calling of pdb on exceptions |
|
738 | # Set calling of pdb on exceptions | |
739 | # self.call_pdb is a property |
|
739 | # self.call_pdb is a property | |
740 | self.call_pdb = self.pdb |
|
740 | self.call_pdb = self.pdb | |
741 |
|
741 | |||
742 | def _get_call_pdb(self): |
|
742 | def _get_call_pdb(self): | |
743 | return self._call_pdb |
|
743 | return self._call_pdb | |
744 |
|
744 | |||
745 | def _set_call_pdb(self,val): |
|
745 | def _set_call_pdb(self,val): | |
746 |
|
746 | |||
747 | if val not in (0,1,False,True): |
|
747 | if val not in (0,1,False,True): | |
748 | raise ValueError,'new call_pdb value must be boolean' |
|
748 | raise ValueError,'new call_pdb value must be boolean' | |
749 |
|
749 | |||
750 | # store value in instance |
|
750 | # store value in instance | |
751 | self._call_pdb = val |
|
751 | self._call_pdb = val | |
752 |
|
752 | |||
753 | # notify the actual exception handlers |
|
753 | # notify the actual exception handlers | |
754 | self.InteractiveTB.call_pdb = val |
|
754 | self.InteractiveTB.call_pdb = val | |
755 |
|
755 | |||
756 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
756 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
757 | 'Control auto-activation of pdb at exceptions') |
|
757 | 'Control auto-activation of pdb at exceptions') | |
758 |
|
758 | |||
759 | def debugger(self,force=False): |
|
759 | def debugger(self,force=False): | |
760 | """Call the pydb/pdb debugger. |
|
760 | """Call the pydb/pdb debugger. | |
761 |
|
761 | |||
762 | Keywords: |
|
762 | Keywords: | |
763 |
|
763 | |||
764 | - force(False): by default, this routine checks the instance call_pdb |
|
764 | - force(False): by default, this routine checks the instance call_pdb | |
765 | flag and does not actually invoke the debugger if the flag is false. |
|
765 | flag and does not actually invoke the debugger if the flag is false. | |
766 | The 'force' option forces the debugger to activate even if the flag |
|
766 | The 'force' option forces the debugger to activate even if the flag | |
767 | is false. |
|
767 | is false. | |
768 | """ |
|
768 | """ | |
769 |
|
769 | |||
770 | if not (force or self.call_pdb): |
|
770 | if not (force or self.call_pdb): | |
771 | return |
|
771 | return | |
772 |
|
772 | |||
773 | if not hasattr(sys,'last_traceback'): |
|
773 | if not hasattr(sys,'last_traceback'): | |
774 | error('No traceback has been produced, nothing to debug.') |
|
774 | error('No traceback has been produced, nothing to debug.') | |
775 | return |
|
775 | return | |
776 |
|
776 | |||
777 | # use pydb if available |
|
777 | # use pydb if available | |
778 | if debugger.has_pydb: |
|
778 | if debugger.has_pydb: | |
779 | from pydb import pm |
|
779 | from pydb import pm | |
780 | else: |
|
780 | else: | |
781 | # fallback to our internal debugger |
|
781 | # fallback to our internal debugger | |
782 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
782 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
783 |
|
783 | |||
784 | with self.readline_no_record: |
|
784 | with self.readline_no_record: | |
785 | pm() |
|
785 | pm() | |
786 |
|
786 | |||
787 | #------------------------------------------------------------------------- |
|
787 | #------------------------------------------------------------------------- | |
788 | # Things related to IPython's various namespaces |
|
788 | # Things related to IPython's various namespaces | |
789 | #------------------------------------------------------------------------- |
|
789 | #------------------------------------------------------------------------- | |
790 |
|
790 | |||
791 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
791 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
792 | # Create the namespace where the user will operate. user_ns is |
|
792 | # Create the namespace where the user will operate. user_ns is | |
793 | # normally the only one used, and it is passed to the exec calls as |
|
793 | # normally the only one used, and it is passed to the exec calls as | |
794 | # the locals argument. But we do carry a user_global_ns namespace |
|
794 | # the locals argument. But we do carry a user_global_ns namespace | |
795 | # given as the exec 'globals' argument, This is useful in embedding |
|
795 | # given as the exec 'globals' argument, This is useful in embedding | |
796 | # situations where the ipython shell opens in a context where the |
|
796 | # situations where the ipython shell opens in a context where the | |
797 | # distinction between locals and globals is meaningful. For |
|
797 | # distinction between locals and globals is meaningful. For | |
798 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
798 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
799 |
|
799 | |||
800 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
800 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
801 | # level as a dict instead of a module. This is a manual fix, but I |
|
801 | # level as a dict instead of a module. This is a manual fix, but I | |
802 | # should really track down where the problem is coming from. Alex |
|
802 | # should really track down where the problem is coming from. Alex | |
803 | # Schmolck reported this problem first. |
|
803 | # Schmolck reported this problem first. | |
804 |
|
804 | |||
805 | # A useful post by Alex Martelli on this topic: |
|
805 | # A useful post by Alex Martelli on this topic: | |
806 | # Re: inconsistent value from __builtins__ |
|
806 | # Re: inconsistent value from __builtins__ | |
807 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
807 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
808 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
808 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
809 | # Gruppen: comp.lang.python |
|
809 | # Gruppen: comp.lang.python | |
810 |
|
810 | |||
811 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
811 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
812 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
812 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
813 | # > <type 'dict'> |
|
813 | # > <type 'dict'> | |
814 | # > >>> print type(__builtins__) |
|
814 | # > >>> print type(__builtins__) | |
815 | # > <type 'module'> |
|
815 | # > <type 'module'> | |
816 | # > Is this difference in return value intentional? |
|
816 | # > Is this difference in return value intentional? | |
817 |
|
817 | |||
818 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
818 | # Well, it's documented that '__builtins__' can be either a dictionary | |
819 | # or a module, and it's been that way for a long time. Whether it's |
|
819 | # or a module, and it's been that way for a long time. Whether it's | |
820 | # intentional (or sensible), I don't know. In any case, the idea is |
|
820 | # intentional (or sensible), I don't know. In any case, the idea is | |
821 | # that if you need to access the built-in namespace directly, you |
|
821 | # that if you need to access the built-in namespace directly, you | |
822 | # should start with "import __builtin__" (note, no 's') which will |
|
822 | # should start with "import __builtin__" (note, no 's') which will | |
823 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
823 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
824 |
|
824 | |||
825 | # These routines return properly built dicts as needed by the rest of |
|
825 | # These routines return properly built dicts as needed by the rest of | |
826 | # the code, and can also be used by extension writers to generate |
|
826 | # the code, and can also be used by extension writers to generate | |
827 | # properly initialized namespaces. |
|
827 | # properly initialized namespaces. | |
828 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
828 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
829 | user_global_ns) |
|
829 | user_global_ns) | |
830 |
|
830 | |||
831 | # Assign namespaces |
|
831 | # Assign namespaces | |
832 | # This is the namespace where all normal user variables live |
|
832 | # This is the namespace where all normal user variables live | |
833 | self.user_ns = user_ns |
|
833 | self.user_ns = user_ns | |
834 | self.user_global_ns = user_global_ns |
|
834 | self.user_global_ns = user_global_ns | |
835 |
|
835 | |||
836 | # An auxiliary namespace that checks what parts of the user_ns were |
|
836 | # An auxiliary namespace that checks what parts of the user_ns were | |
837 | # loaded at startup, so we can list later only variables defined in |
|
837 | # loaded at startup, so we can list later only variables defined in | |
838 | # actual interactive use. Since it is always a subset of user_ns, it |
|
838 | # actual interactive use. Since it is always a subset of user_ns, it | |
839 | # doesn't need to be separately tracked in the ns_table. |
|
839 | # doesn't need to be separately tracked in the ns_table. | |
840 | self.user_ns_hidden = {} |
|
840 | self.user_ns_hidden = {} | |
841 |
|
841 | |||
842 | # A namespace to keep track of internal data structures to prevent |
|
842 | # A namespace to keep track of internal data structures to prevent | |
843 | # them from cluttering user-visible stuff. Will be updated later |
|
843 | # them from cluttering user-visible stuff. Will be updated later | |
844 | self.internal_ns = {} |
|
844 | self.internal_ns = {} | |
845 |
|
845 | |||
846 | # Now that FakeModule produces a real module, we've run into a nasty |
|
846 | # Now that FakeModule produces a real module, we've run into a nasty | |
847 | # problem: after script execution (via %run), the module where the user |
|
847 | # problem: after script execution (via %run), the module where the user | |
848 | # code ran is deleted. Now that this object is a true module (needed |
|
848 | # code ran is deleted. Now that this object is a true module (needed | |
849 | # so docetst and other tools work correctly), the Python module |
|
849 | # so docetst and other tools work correctly), the Python module | |
850 | # teardown mechanism runs over it, and sets to None every variable |
|
850 | # teardown mechanism runs over it, and sets to None every variable | |
851 | # present in that module. Top-level references to objects from the |
|
851 | # present in that module. Top-level references to objects from the | |
852 | # script survive, because the user_ns is updated with them. However, |
|
852 | # script survive, because the user_ns is updated with them. However, | |
853 | # calling functions defined in the script that use other things from |
|
853 | # calling functions defined in the script that use other things from | |
854 | # the script will fail, because the function's closure had references |
|
854 | # the script will fail, because the function's closure had references | |
855 | # to the original objects, which are now all None. So we must protect |
|
855 | # to the original objects, which are now all None. So we must protect | |
856 | # these modules from deletion by keeping a cache. |
|
856 | # these modules from deletion by keeping a cache. | |
857 | # |
|
857 | # | |
858 | # To avoid keeping stale modules around (we only need the one from the |
|
858 | # To avoid keeping stale modules around (we only need the one from the | |
859 | # last run), we use a dict keyed with the full path to the script, so |
|
859 | # last run), we use a dict keyed with the full path to the script, so | |
860 | # only the last version of the module is held in the cache. Note, |
|
860 | # only the last version of the module is held in the cache. Note, | |
861 | # however, that we must cache the module *namespace contents* (their |
|
861 | # however, that we must cache the module *namespace contents* (their | |
862 | # __dict__). Because if we try to cache the actual modules, old ones |
|
862 | # __dict__). Because if we try to cache the actual modules, old ones | |
863 | # (uncached) could be destroyed while still holding references (such as |
|
863 | # (uncached) could be destroyed while still holding references (such as | |
864 | # those held by GUI objects that tend to be long-lived)> |
|
864 | # those held by GUI objects that tend to be long-lived)> | |
865 | # |
|
865 | # | |
866 | # The %reset command will flush this cache. See the cache_main_mod() |
|
866 | # The %reset command will flush this cache. See the cache_main_mod() | |
867 | # and clear_main_mod_cache() methods for details on use. |
|
867 | # and clear_main_mod_cache() methods for details on use. | |
868 |
|
868 | |||
869 | # This is the cache used for 'main' namespaces |
|
869 | # This is the cache used for 'main' namespaces | |
870 | self._main_ns_cache = {} |
|
870 | self._main_ns_cache = {} | |
871 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
871 | # And this is the single instance of FakeModule whose __dict__ we keep | |
872 | # copying and clearing for reuse on each %run |
|
872 | # copying and clearing for reuse on each %run | |
873 | self._user_main_module = FakeModule() |
|
873 | self._user_main_module = FakeModule() | |
874 |
|
874 | |||
875 | # A table holding all the namespaces IPython deals with, so that |
|
875 | # A table holding all the namespaces IPython deals with, so that | |
876 | # introspection facilities can search easily. |
|
876 | # introspection facilities can search easily. | |
877 | self.ns_table = {'user':user_ns, |
|
877 | self.ns_table = {'user':user_ns, | |
878 | 'user_global':user_global_ns, |
|
878 | 'user_global':user_global_ns, | |
879 | 'internal':self.internal_ns, |
|
879 | 'internal':self.internal_ns, | |
880 | 'builtin':__builtin__.__dict__ |
|
880 | 'builtin':__builtin__.__dict__ | |
881 | } |
|
881 | } | |
882 |
|
882 | |||
883 | # Similarly, track all namespaces where references can be held and that |
|
883 | # Similarly, track all namespaces where references can be held and that | |
884 | # we can safely clear (so it can NOT include builtin). This one can be |
|
884 | # we can safely clear (so it can NOT include builtin). This one can be | |
885 | # a simple list. Note that the main execution namespaces, user_ns and |
|
885 | # a simple list. Note that the main execution namespaces, user_ns and | |
886 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
886 | # user_global_ns, can NOT be listed here, as clearing them blindly | |
887 | # causes errors in object __del__ methods. Instead, the reset() method |
|
887 | # causes errors in object __del__ methods. Instead, the reset() method | |
888 | # clears them manually and carefully. |
|
888 | # clears them manually and carefully. | |
889 | self.ns_refs_table = [ self.user_ns_hidden, |
|
889 | self.ns_refs_table = [ self.user_ns_hidden, | |
890 | self.internal_ns, self._main_ns_cache ] |
|
890 | self.internal_ns, self._main_ns_cache ] | |
891 |
|
891 | |||
892 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
892 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
893 | """Return a valid local and global user interactive namespaces. |
|
893 | """Return a valid local and global user interactive namespaces. | |
894 |
|
894 | |||
895 | This builds a dict with the minimal information needed to operate as a |
|
895 | This builds a dict with the minimal information needed to operate as a | |
896 | valid IPython user namespace, which you can pass to the various |
|
896 | valid IPython user namespace, which you can pass to the various | |
897 | embedding classes in ipython. The default implementation returns the |
|
897 | embedding classes in ipython. The default implementation returns the | |
898 | same dict for both the locals and the globals to allow functions to |
|
898 | same dict for both the locals and the globals to allow functions to | |
899 | refer to variables in the namespace. Customized implementations can |
|
899 | refer to variables in the namespace. Customized implementations can | |
900 | return different dicts. The locals dictionary can actually be anything |
|
900 | return different dicts. The locals dictionary can actually be anything | |
901 | following the basic mapping protocol of a dict, but the globals dict |
|
901 | following the basic mapping protocol of a dict, but the globals dict | |
902 | must be a true dict, not even a subclass. It is recommended that any |
|
902 | must be a true dict, not even a subclass. It is recommended that any | |
903 | custom object for the locals namespace synchronize with the globals |
|
903 | custom object for the locals namespace synchronize with the globals | |
904 | dict somehow. |
|
904 | dict somehow. | |
905 |
|
905 | |||
906 | Raises TypeError if the provided globals namespace is not a true dict. |
|
906 | Raises TypeError if the provided globals namespace is not a true dict. | |
907 |
|
907 | |||
908 | Parameters |
|
908 | Parameters | |
909 | ---------- |
|
909 | ---------- | |
910 | user_ns : dict-like, optional |
|
910 | user_ns : dict-like, optional | |
911 | The current user namespace. The items in this namespace should |
|
911 | The current user namespace. The items in this namespace should | |
912 | be included in the output. If None, an appropriate blank |
|
912 | be included in the output. If None, an appropriate blank | |
913 | namespace should be created. |
|
913 | namespace should be created. | |
914 | user_global_ns : dict, optional |
|
914 | user_global_ns : dict, optional | |
915 | The current user global namespace. The items in this namespace |
|
915 | The current user global namespace. The items in this namespace | |
916 | should be included in the output. If None, an appropriate |
|
916 | should be included in the output. If None, an appropriate | |
917 | blank namespace should be created. |
|
917 | blank namespace should be created. | |
918 |
|
918 | |||
919 | Returns |
|
919 | Returns | |
920 | ------- |
|
920 | ------- | |
921 | A pair of dictionary-like object to be used as the local namespace |
|
921 | A pair of dictionary-like object to be used as the local namespace | |
922 | of the interpreter and a dict to be used as the global namespace. |
|
922 | of the interpreter and a dict to be used as the global namespace. | |
923 | """ |
|
923 | """ | |
924 |
|
924 | |||
925 |
|
925 | |||
926 | # We must ensure that __builtin__ (without the final 's') is always |
|
926 | # We must ensure that __builtin__ (without the final 's') is always | |
927 | # available and pointing to the __builtin__ *module*. For more details: |
|
927 | # available and pointing to the __builtin__ *module*. For more details: | |
928 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
928 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
929 |
|
929 | |||
930 | if user_ns is None: |
|
930 | if user_ns is None: | |
931 | # Set __name__ to __main__ to better match the behavior of the |
|
931 | # Set __name__ to __main__ to better match the behavior of the | |
932 | # normal interpreter. |
|
932 | # normal interpreter. | |
933 | user_ns = {'__name__' :'__main__', |
|
933 | user_ns = {'__name__' :'__main__', | |
934 | '__builtin__' : __builtin__, |
|
934 | '__builtin__' : __builtin__, | |
935 | '__builtins__' : __builtin__, |
|
935 | '__builtins__' : __builtin__, | |
936 | } |
|
936 | } | |
937 | else: |
|
937 | else: | |
938 | user_ns.setdefault('__name__','__main__') |
|
938 | user_ns.setdefault('__name__','__main__') | |
939 | user_ns.setdefault('__builtin__',__builtin__) |
|
939 | user_ns.setdefault('__builtin__',__builtin__) | |
940 | user_ns.setdefault('__builtins__',__builtin__) |
|
940 | user_ns.setdefault('__builtins__',__builtin__) | |
941 |
|
941 | |||
942 | if user_global_ns is None: |
|
942 | if user_global_ns is None: | |
943 | user_global_ns = user_ns |
|
943 | user_global_ns = user_ns | |
944 | if type(user_global_ns) is not dict: |
|
944 | if type(user_global_ns) is not dict: | |
945 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
945 | raise TypeError("user_global_ns must be a true dict; got %r" | |
946 | % type(user_global_ns)) |
|
946 | % type(user_global_ns)) | |
947 |
|
947 | |||
948 | return user_ns, user_global_ns |
|
948 | return user_ns, user_global_ns | |
949 |
|
949 | |||
950 | def init_sys_modules(self): |
|
950 | def init_sys_modules(self): | |
951 | # We need to insert into sys.modules something that looks like a |
|
951 | # We need to insert into sys.modules something that looks like a | |
952 | # module but which accesses the IPython namespace, for shelve and |
|
952 | # module but which accesses the IPython namespace, for shelve and | |
953 | # pickle to work interactively. Normally they rely on getting |
|
953 | # pickle to work interactively. Normally they rely on getting | |
954 | # everything out of __main__, but for embedding purposes each IPython |
|
954 | # everything out of __main__, but for embedding purposes each IPython | |
955 | # instance has its own private namespace, so we can't go shoving |
|
955 | # instance has its own private namespace, so we can't go shoving | |
956 | # everything into __main__. |
|
956 | # everything into __main__. | |
957 |
|
957 | |||
958 | # note, however, that we should only do this for non-embedded |
|
958 | # note, however, that we should only do this for non-embedded | |
959 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
959 | # ipythons, which really mimic the __main__.__dict__ with their own | |
960 | # namespace. Embedded instances, on the other hand, should not do |
|
960 | # namespace. Embedded instances, on the other hand, should not do | |
961 | # this because they need to manage the user local/global namespaces |
|
961 | # this because they need to manage the user local/global namespaces | |
962 | # only, but they live within a 'normal' __main__ (meaning, they |
|
962 | # only, but they live within a 'normal' __main__ (meaning, they | |
963 | # shouldn't overtake the execution environment of the script they're |
|
963 | # shouldn't overtake the execution environment of the script they're | |
964 | # embedded in). |
|
964 | # embedded in). | |
965 |
|
965 | |||
966 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
966 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
967 |
|
967 | |||
968 | try: |
|
968 | try: | |
969 | main_name = self.user_ns['__name__'] |
|
969 | main_name = self.user_ns['__name__'] | |
970 | except KeyError: |
|
970 | except KeyError: | |
971 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
971 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
972 | else: |
|
972 | else: | |
973 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
973 | sys.modules[main_name] = FakeModule(self.user_ns) | |
974 |
|
974 | |||
975 | def init_user_ns(self): |
|
975 | def init_user_ns(self): | |
976 | """Initialize all user-visible namespaces to their minimum defaults. |
|
976 | """Initialize all user-visible namespaces to their minimum defaults. | |
977 |
|
977 | |||
978 | Certain history lists are also initialized here, as they effectively |
|
978 | Certain history lists are also initialized here, as they effectively | |
979 | act as user namespaces. |
|
979 | act as user namespaces. | |
980 |
|
980 | |||
981 | Notes |
|
981 | Notes | |
982 | ----- |
|
982 | ----- | |
983 | All data structures here are only filled in, they are NOT reset by this |
|
983 | All data structures here are only filled in, they are NOT reset by this | |
984 | method. If they were not empty before, data will simply be added to |
|
984 | method. If they were not empty before, data will simply be added to | |
985 | therm. |
|
985 | therm. | |
986 | """ |
|
986 | """ | |
987 | # This function works in two parts: first we put a few things in |
|
987 | # This function works in two parts: first we put a few things in | |
988 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
988 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
989 | # initial variables aren't shown by %who. After the sync, we add the |
|
989 | # initial variables aren't shown by %who. After the sync, we add the | |
990 | # rest of what we *do* want the user to see with %who even on a new |
|
990 | # rest of what we *do* want the user to see with %who even on a new | |
991 | # session (probably nothing, so theye really only see their own stuff) |
|
991 | # session (probably nothing, so theye really only see their own stuff) | |
992 |
|
992 | |||
993 | # The user dict must *always* have a __builtin__ reference to the |
|
993 | # The user dict must *always* have a __builtin__ reference to the | |
994 | # Python standard __builtin__ namespace, which must be imported. |
|
994 | # Python standard __builtin__ namespace, which must be imported. | |
995 | # This is so that certain operations in prompt evaluation can be |
|
995 | # This is so that certain operations in prompt evaluation can be | |
996 | # reliably executed with builtins. Note that we can NOT use |
|
996 | # reliably executed with builtins. Note that we can NOT use | |
997 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
997 | # __builtins__ (note the 's'), because that can either be a dict or a | |
998 | # module, and can even mutate at runtime, depending on the context |
|
998 | # module, and can even mutate at runtime, depending on the context | |
999 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
999 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
1000 | # always a module object, though it must be explicitly imported. |
|
1000 | # always a module object, though it must be explicitly imported. | |
1001 |
|
1001 | |||
1002 | # For more details: |
|
1002 | # For more details: | |
1003 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1003 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1004 | ns = dict(__builtin__ = __builtin__) |
|
1004 | ns = dict(__builtin__ = __builtin__) | |
1005 |
|
1005 | |||
1006 | # Put 'help' in the user namespace |
|
1006 | # Put 'help' in the user namespace | |
1007 | try: |
|
1007 | try: | |
1008 | from site import _Helper |
|
1008 | from site import _Helper | |
1009 | ns['help'] = _Helper() |
|
1009 | ns['help'] = _Helper() | |
1010 | except ImportError: |
|
1010 | except ImportError: | |
1011 | warn('help() not available - check site.py') |
|
1011 | warn('help() not available - check site.py') | |
1012 |
|
1012 | |||
1013 | # make global variables for user access to the histories |
|
1013 | # make global variables for user access to the histories | |
1014 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1014 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1015 | ns['_oh'] = self.history_manager.output_hist |
|
1015 | ns['_oh'] = self.history_manager.output_hist | |
1016 | ns['_dh'] = self.history_manager.dir_hist |
|
1016 | ns['_dh'] = self.history_manager.dir_hist | |
1017 |
|
1017 | |||
1018 | ns['_sh'] = shadowns |
|
1018 | ns['_sh'] = shadowns | |
1019 |
|
1019 | |||
1020 | # user aliases to input and output histories. These shouldn't show up |
|
1020 | # user aliases to input and output histories. These shouldn't show up | |
1021 | # in %who, as they can have very large reprs. |
|
1021 | # in %who, as they can have very large reprs. | |
1022 | ns['In'] = self.history_manager.input_hist_parsed |
|
1022 | ns['In'] = self.history_manager.input_hist_parsed | |
1023 | ns['Out'] = self.history_manager.output_hist |
|
1023 | ns['Out'] = self.history_manager.output_hist | |
1024 |
|
1024 | |||
1025 | # Store myself as the public api!!! |
|
1025 | # Store myself as the public api!!! | |
1026 | ns['get_ipython'] = self.get_ipython |
|
1026 | ns['get_ipython'] = self.get_ipython | |
1027 |
|
1027 | |||
1028 | ns['exit'] = self.exiter |
|
1028 | ns['exit'] = self.exiter | |
1029 | ns['quit'] = self.exiter |
|
1029 | ns['quit'] = self.exiter | |
1030 |
|
1030 | |||
1031 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1031 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1032 | # by %who |
|
1032 | # by %who | |
1033 | self.user_ns_hidden.update(ns) |
|
1033 | self.user_ns_hidden.update(ns) | |
1034 |
|
1034 | |||
1035 | # Anything put into ns now would show up in %who. Think twice before |
|
1035 | # Anything put into ns now would show up in %who. Think twice before | |
1036 | # putting anything here, as we really want %who to show the user their |
|
1036 | # putting anything here, as we really want %who to show the user their | |
1037 | # stuff, not our variables. |
|
1037 | # stuff, not our variables. | |
1038 |
|
1038 | |||
1039 | # Finally, update the real user's namespace |
|
1039 | # Finally, update the real user's namespace | |
1040 | self.user_ns.update(ns) |
|
1040 | self.user_ns.update(ns) | |
1041 |
|
1041 | |||
1042 | def reset(self, new_session=True): |
|
1042 | def reset(self, new_session=True): | |
1043 | """Clear all internal namespaces. |
|
1043 | """Clear all internal namespaces. | |
1044 |
|
1044 | |||
1045 | Note that this is much more aggressive than %reset, since it clears |
|
1045 | Note that this is much more aggressive than %reset, since it clears | |
1046 | fully all namespaces, as well as all input/output lists. |
|
1046 | fully all namespaces, as well as all input/output lists. | |
1047 |
|
1047 | |||
1048 | If new_session is True, a new history session will be opened. |
|
1048 | If new_session is True, a new history session will be opened. | |
1049 | """ |
|
1049 | """ | |
1050 | # Clear histories |
|
1050 | # Clear histories | |
1051 | self.history_manager.reset(new_session) |
|
1051 | self.history_manager.reset(new_session) | |
1052 | # Reset counter used to index all histories |
|
1052 | # Reset counter used to index all histories | |
1053 | if new_session: |
|
1053 | if new_session: | |
1054 | self.execution_count = 1 |
|
1054 | self.execution_count = 1 | |
1055 |
|
1055 | |||
1056 | # Flush cached output items |
|
1056 | # Flush cached output items | |
1057 | self.displayhook.flush() |
|
1057 | self.displayhook.flush() | |
1058 |
|
1058 | |||
1059 | # Restore the user namespaces to minimal usability |
|
1059 | # Restore the user namespaces to minimal usability | |
1060 | for ns in self.ns_refs_table: |
|
1060 | for ns in self.ns_refs_table: | |
1061 | ns.clear() |
|
1061 | ns.clear() | |
1062 |
|
1062 | |||
1063 | # The main execution namespaces must be cleared very carefully, |
|
1063 | # The main execution namespaces must be cleared very carefully, | |
1064 | # skipping the deletion of the builtin-related keys, because doing so |
|
1064 | # skipping the deletion of the builtin-related keys, because doing so | |
1065 | # would cause errors in many object's __del__ methods. |
|
1065 | # would cause errors in many object's __del__ methods. | |
1066 | for ns in [self.user_ns, self.user_global_ns]: |
|
1066 | for ns in [self.user_ns, self.user_global_ns]: | |
1067 | drop_keys = set(ns.keys()) |
|
1067 | drop_keys = set(ns.keys()) | |
1068 | drop_keys.discard('__builtin__') |
|
1068 | drop_keys.discard('__builtin__') | |
1069 | drop_keys.discard('__builtins__') |
|
1069 | drop_keys.discard('__builtins__') | |
1070 | for k in drop_keys: |
|
1070 | for k in drop_keys: | |
1071 | del ns[k] |
|
1071 | del ns[k] | |
1072 |
|
1072 | |||
1073 | # Restore the user namespaces to minimal usability |
|
1073 | # Restore the user namespaces to minimal usability | |
1074 | self.init_user_ns() |
|
1074 | self.init_user_ns() | |
1075 |
|
1075 | |||
1076 | # Restore the default and user aliases |
|
1076 | # Restore the default and user aliases | |
1077 | self.alias_manager.clear_aliases() |
|
1077 | self.alias_manager.clear_aliases() | |
1078 | self.alias_manager.init_aliases() |
|
1078 | self.alias_manager.init_aliases() | |
1079 |
|
1079 | |||
1080 | # Flush the private list of module references kept for script |
|
1080 | # Flush the private list of module references kept for script | |
1081 | # execution protection |
|
1081 | # execution protection | |
1082 | self.clear_main_mod_cache() |
|
1082 | self.clear_main_mod_cache() | |
1083 |
|
1083 | |||
1084 | def reset_selective(self, regex=None): |
|
1084 | def reset_selective(self, regex=None): | |
1085 | """Clear selective variables from internal namespaces based on a |
|
1085 | """Clear selective variables from internal namespaces based on a | |
1086 | specified regular expression. |
|
1086 | specified regular expression. | |
1087 |
|
1087 | |||
1088 | Parameters |
|
1088 | Parameters | |
1089 | ---------- |
|
1089 | ---------- | |
1090 | regex : string or compiled pattern, optional |
|
1090 | regex : string or compiled pattern, optional | |
1091 | A regular expression pattern that will be used in searching |
|
1091 | A regular expression pattern that will be used in searching | |
1092 | variable names in the users namespaces. |
|
1092 | variable names in the users namespaces. | |
1093 | """ |
|
1093 | """ | |
1094 | if regex is not None: |
|
1094 | if regex is not None: | |
1095 | try: |
|
1095 | try: | |
1096 | m = re.compile(regex) |
|
1096 | m = re.compile(regex) | |
1097 | except TypeError: |
|
1097 | except TypeError: | |
1098 | raise TypeError('regex must be a string or compiled pattern') |
|
1098 | raise TypeError('regex must be a string or compiled pattern') | |
1099 | # Search for keys in each namespace that match the given regex |
|
1099 | # Search for keys in each namespace that match the given regex | |
1100 | # If a match is found, delete the key/value pair. |
|
1100 | # If a match is found, delete the key/value pair. | |
1101 | for ns in self.ns_refs_table: |
|
1101 | for ns in self.ns_refs_table: | |
1102 | for var in ns: |
|
1102 | for var in ns: | |
1103 | if m.search(var): |
|
1103 | if m.search(var): | |
1104 | del ns[var] |
|
1104 | del ns[var] | |
1105 |
|
1105 | |||
1106 | def push(self, variables, interactive=True): |
|
1106 | def push(self, variables, interactive=True): | |
1107 | """Inject a group of variables into the IPython user namespace. |
|
1107 | """Inject a group of variables into the IPython user namespace. | |
1108 |
|
1108 | |||
1109 | Parameters |
|
1109 | Parameters | |
1110 | ---------- |
|
1110 | ---------- | |
1111 | variables : dict, str or list/tuple of str |
|
1111 | variables : dict, str or list/tuple of str | |
1112 | The variables to inject into the user's namespace. If a dict, a |
|
1112 | The variables to inject into the user's namespace. If a dict, a | |
1113 | simple update is done. If a str, the string is assumed to have |
|
1113 | simple update is done. If a str, the string is assumed to have | |
1114 | variable names separated by spaces. A list/tuple of str can also |
|
1114 | variable names separated by spaces. A list/tuple of str can also | |
1115 | be used to give the variable names. If just the variable names are |
|
1115 | be used to give the variable names. If just the variable names are | |
1116 | give (list/tuple/str) then the variable values looked up in the |
|
1116 | give (list/tuple/str) then the variable values looked up in the | |
1117 | callers frame. |
|
1117 | callers frame. | |
1118 | interactive : bool |
|
1118 | interactive : bool | |
1119 | If True (default), the variables will be listed with the ``who`` |
|
1119 | If True (default), the variables will be listed with the ``who`` | |
1120 | magic. |
|
1120 | magic. | |
1121 | """ |
|
1121 | """ | |
1122 | vdict = None |
|
1122 | vdict = None | |
1123 |
|
1123 | |||
1124 | # We need a dict of name/value pairs to do namespace updates. |
|
1124 | # We need a dict of name/value pairs to do namespace updates. | |
1125 | if isinstance(variables, dict): |
|
1125 | if isinstance(variables, dict): | |
1126 | vdict = variables |
|
1126 | vdict = variables | |
1127 | elif isinstance(variables, (basestring, list, tuple)): |
|
1127 | elif isinstance(variables, (basestring, list, tuple)): | |
1128 | if isinstance(variables, basestring): |
|
1128 | if isinstance(variables, basestring): | |
1129 | vlist = variables.split() |
|
1129 | vlist = variables.split() | |
1130 | else: |
|
1130 | else: | |
1131 | vlist = variables |
|
1131 | vlist = variables | |
1132 | vdict = {} |
|
1132 | vdict = {} | |
1133 | cf = sys._getframe(1) |
|
1133 | cf = sys._getframe(1) | |
1134 | for name in vlist: |
|
1134 | for name in vlist: | |
1135 | try: |
|
1135 | try: | |
1136 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1136 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1137 | except: |
|
1137 | except: | |
1138 | print ('Could not get variable %s from %s' % |
|
1138 | print ('Could not get variable %s from %s' % | |
1139 | (name,cf.f_code.co_name)) |
|
1139 | (name,cf.f_code.co_name)) | |
1140 | else: |
|
1140 | else: | |
1141 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1141 | raise ValueError('variables must be a dict/str/list/tuple') | |
1142 |
|
1142 | |||
1143 | # Propagate variables to user namespace |
|
1143 | # Propagate variables to user namespace | |
1144 | self.user_ns.update(vdict) |
|
1144 | self.user_ns.update(vdict) | |
1145 |
|
1145 | |||
1146 | # And configure interactive visibility |
|
1146 | # And configure interactive visibility | |
1147 | config_ns = self.user_ns_hidden |
|
1147 | config_ns = self.user_ns_hidden | |
1148 | if interactive: |
|
1148 | if interactive: | |
1149 | for name, val in vdict.iteritems(): |
|
1149 | for name, val in vdict.iteritems(): | |
1150 | config_ns.pop(name, None) |
|
1150 | config_ns.pop(name, None) | |
1151 | else: |
|
1151 | else: | |
1152 | for name,val in vdict.iteritems(): |
|
1152 | for name,val in vdict.iteritems(): | |
1153 | config_ns[name] = val |
|
1153 | config_ns[name] = val | |
1154 |
|
1154 | |||
1155 | #------------------------------------------------------------------------- |
|
1155 | #------------------------------------------------------------------------- | |
1156 | # Things related to object introspection |
|
1156 | # Things related to object introspection | |
1157 | #------------------------------------------------------------------------- |
|
1157 | #------------------------------------------------------------------------- | |
1158 |
|
1158 | |||
1159 | def _ofind(self, oname, namespaces=None): |
|
1159 | def _ofind(self, oname, namespaces=None): | |
1160 | """Find an object in the available namespaces. |
|
1160 | """Find an object in the available namespaces. | |
1161 |
|
1161 | |||
1162 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1162 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1163 |
|
1163 | |||
1164 | Has special code to detect magic functions. |
|
1164 | Has special code to detect magic functions. | |
1165 | """ |
|
1165 | """ | |
1166 | #oname = oname.strip() |
|
1166 | #oname = oname.strip() | |
1167 | #print '1- oname: <%r>' % oname # dbg |
|
1167 | #print '1- oname: <%r>' % oname # dbg | |
1168 | try: |
|
1168 | try: | |
1169 | oname = oname.strip().encode('ascii') |
|
1169 | oname = oname.strip().encode('ascii') | |
1170 | #print '2- oname: <%r>' % oname # dbg |
|
1170 | #print '2- oname: <%r>' % oname # dbg | |
1171 | except UnicodeEncodeError: |
|
1171 | except UnicodeEncodeError: | |
1172 | print 'Python identifiers can only contain ascii characters.' |
|
1172 | print 'Python identifiers can only contain ascii characters.' | |
1173 | return dict(found=False) |
|
1173 | return dict(found=False) | |
1174 |
|
1174 | |||
1175 | alias_ns = None |
|
1175 | alias_ns = None | |
1176 | if namespaces is None: |
|
1176 | if namespaces is None: | |
1177 | # Namespaces to search in: |
|
1177 | # Namespaces to search in: | |
1178 | # Put them in a list. The order is important so that we |
|
1178 | # Put them in a list. The order is important so that we | |
1179 | # find things in the same order that Python finds them. |
|
1179 | # find things in the same order that Python finds them. | |
1180 | namespaces = [ ('Interactive', self.user_ns), |
|
1180 | namespaces = [ ('Interactive', self.user_ns), | |
1181 | ('IPython internal', self.internal_ns), |
|
1181 | ('IPython internal', self.internal_ns), | |
1182 | ('Python builtin', __builtin__.__dict__), |
|
1182 | ('Python builtin', __builtin__.__dict__), | |
1183 | ('Alias', self.alias_manager.alias_table), |
|
1183 | ('Alias', self.alias_manager.alias_table), | |
1184 | ] |
|
1184 | ] | |
1185 | alias_ns = self.alias_manager.alias_table |
|
1185 | alias_ns = self.alias_manager.alias_table | |
1186 |
|
1186 | |||
1187 | # initialize results to 'null' |
|
1187 | # initialize results to 'null' | |
1188 | found = False; obj = None; ospace = None; ds = None; |
|
1188 | found = False; obj = None; ospace = None; ds = None; | |
1189 | ismagic = False; isalias = False; parent = None |
|
1189 | ismagic = False; isalias = False; parent = None | |
1190 |
|
1190 | |||
1191 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1191 | # We need to special-case 'print', which as of python2.6 registers as a | |
1192 | # function but should only be treated as one if print_function was |
|
1192 | # function but should only be treated as one if print_function was | |
1193 | # loaded with a future import. In this case, just bail. |
|
1193 | # loaded with a future import. In this case, just bail. | |
1194 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1194 | if (oname == 'print' and not (self.compile.compiler_flags & | |
1195 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1195 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1196 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1196 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1197 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1197 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1198 |
|
1198 | |||
1199 | # Look for the given name by splitting it in parts. If the head is |
|
1199 | # Look for the given name by splitting it in parts. If the head is | |
1200 | # found, then we look for all the remaining parts as members, and only |
|
1200 | # found, then we look for all the remaining parts as members, and only | |
1201 | # declare success if we can find them all. |
|
1201 | # declare success if we can find them all. | |
1202 | oname_parts = oname.split('.') |
|
1202 | oname_parts = oname.split('.') | |
1203 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1203 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1204 | for nsname,ns in namespaces: |
|
1204 | for nsname,ns in namespaces: | |
1205 | try: |
|
1205 | try: | |
1206 | obj = ns[oname_head] |
|
1206 | obj = ns[oname_head] | |
1207 | except KeyError: |
|
1207 | except KeyError: | |
1208 | continue |
|
1208 | continue | |
1209 | else: |
|
1209 | else: | |
1210 | #print 'oname_rest:', oname_rest # dbg |
|
1210 | #print 'oname_rest:', oname_rest # dbg | |
1211 | for part in oname_rest: |
|
1211 | for part in oname_rest: | |
1212 | try: |
|
1212 | try: | |
1213 | parent = obj |
|
1213 | parent = obj | |
1214 | obj = getattr(obj,part) |
|
1214 | obj = getattr(obj,part) | |
1215 | except: |
|
1215 | except: | |
1216 | # Blanket except b/c some badly implemented objects |
|
1216 | # Blanket except b/c some badly implemented objects | |
1217 | # allow __getattr__ to raise exceptions other than |
|
1217 | # allow __getattr__ to raise exceptions other than | |
1218 | # AttributeError, which then crashes IPython. |
|
1218 | # AttributeError, which then crashes IPython. | |
1219 | break |
|
1219 | break | |
1220 | else: |
|
1220 | else: | |
1221 | # If we finish the for loop (no break), we got all members |
|
1221 | # If we finish the for loop (no break), we got all members | |
1222 | found = True |
|
1222 | found = True | |
1223 | ospace = nsname |
|
1223 | ospace = nsname | |
1224 | if ns == alias_ns: |
|
1224 | if ns == alias_ns: | |
1225 | isalias = True |
|
1225 | isalias = True | |
1226 | break # namespace loop |
|
1226 | break # namespace loop | |
1227 |
|
1227 | |||
1228 | # Try to see if it's magic |
|
1228 | # Try to see if it's magic | |
1229 | if not found: |
|
1229 | if not found: | |
1230 | if oname.startswith(ESC_MAGIC): |
|
1230 | if oname.startswith(ESC_MAGIC): | |
1231 | oname = oname[1:] |
|
1231 | oname = oname[1:] | |
1232 | obj = getattr(self,'magic_'+oname,None) |
|
1232 | obj = getattr(self,'magic_'+oname,None) | |
1233 | if obj is not None: |
|
1233 | if obj is not None: | |
1234 | found = True |
|
1234 | found = True | |
1235 | ospace = 'IPython internal' |
|
1235 | ospace = 'IPython internal' | |
1236 | ismagic = True |
|
1236 | ismagic = True | |
1237 |
|
1237 | |||
1238 | # Last try: special-case some literals like '', [], {}, etc: |
|
1238 | # Last try: special-case some literals like '', [], {}, etc: | |
1239 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1239 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1240 | obj = eval(oname_head) |
|
1240 | obj = eval(oname_head) | |
1241 | found = True |
|
1241 | found = True | |
1242 | ospace = 'Interactive' |
|
1242 | ospace = 'Interactive' | |
1243 |
|
1243 | |||
1244 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1244 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1245 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1245 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1246 |
|
1246 | |||
1247 | def _ofind_property(self, oname, info): |
|
1247 | def _ofind_property(self, oname, info): | |
1248 | """Second part of object finding, to look for property details.""" |
|
1248 | """Second part of object finding, to look for property details.""" | |
1249 | if info.found: |
|
1249 | if info.found: | |
1250 | # Get the docstring of the class property if it exists. |
|
1250 | # Get the docstring of the class property if it exists. | |
1251 | path = oname.split('.') |
|
1251 | path = oname.split('.') | |
1252 | root = '.'.join(path[:-1]) |
|
1252 | root = '.'.join(path[:-1]) | |
1253 | if info.parent is not None: |
|
1253 | if info.parent is not None: | |
1254 | try: |
|
1254 | try: | |
1255 | target = getattr(info.parent, '__class__') |
|
1255 | target = getattr(info.parent, '__class__') | |
1256 | # The object belongs to a class instance. |
|
1256 | # The object belongs to a class instance. | |
1257 | try: |
|
1257 | try: | |
1258 | target = getattr(target, path[-1]) |
|
1258 | target = getattr(target, path[-1]) | |
1259 | # The class defines the object. |
|
1259 | # The class defines the object. | |
1260 | if isinstance(target, property): |
|
1260 | if isinstance(target, property): | |
1261 | oname = root + '.__class__.' + path[-1] |
|
1261 | oname = root + '.__class__.' + path[-1] | |
1262 | info = Struct(self._ofind(oname)) |
|
1262 | info = Struct(self._ofind(oname)) | |
1263 | except AttributeError: pass |
|
1263 | except AttributeError: pass | |
1264 | except AttributeError: pass |
|
1264 | except AttributeError: pass | |
1265 |
|
1265 | |||
1266 | # We return either the new info or the unmodified input if the object |
|
1266 | # We return either the new info or the unmodified input if the object | |
1267 | # hadn't been found |
|
1267 | # hadn't been found | |
1268 | return info |
|
1268 | return info | |
1269 |
|
1269 | |||
1270 | def _object_find(self, oname, namespaces=None): |
|
1270 | def _object_find(self, oname, namespaces=None): | |
1271 | """Find an object and return a struct with info about it.""" |
|
1271 | """Find an object and return a struct with info about it.""" | |
1272 | inf = Struct(self._ofind(oname, namespaces)) |
|
1272 | inf = Struct(self._ofind(oname, namespaces)) | |
1273 | return Struct(self._ofind_property(oname, inf)) |
|
1273 | return Struct(self._ofind_property(oname, inf)) | |
1274 |
|
1274 | |||
1275 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1275 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1276 | """Generic interface to the inspector system. |
|
1276 | """Generic interface to the inspector system. | |
1277 |
|
1277 | |||
1278 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1278 | This function is meant to be called by pdef, pdoc & friends.""" | |
1279 | info = self._object_find(oname) |
|
1279 | info = self._object_find(oname) | |
1280 | if info.found: |
|
1280 | if info.found: | |
1281 | pmethod = getattr(self.inspector, meth) |
|
1281 | pmethod = getattr(self.inspector, meth) | |
1282 | formatter = format_screen if info.ismagic else None |
|
1282 | formatter = format_screen if info.ismagic else None | |
1283 | if meth == 'pdoc': |
|
1283 | if meth == 'pdoc': | |
1284 | pmethod(info.obj, oname, formatter) |
|
1284 | pmethod(info.obj, oname, formatter) | |
1285 | elif meth == 'pinfo': |
|
1285 | elif meth == 'pinfo': | |
1286 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1286 | pmethod(info.obj, oname, formatter, info, **kw) | |
1287 | else: |
|
1287 | else: | |
1288 | pmethod(info.obj, oname) |
|
1288 | pmethod(info.obj, oname) | |
1289 | else: |
|
1289 | else: | |
1290 | print 'Object `%s` not found.' % oname |
|
1290 | print 'Object `%s` not found.' % oname | |
1291 | return 'not found' # so callers can take other action |
|
1291 | return 'not found' # so callers can take other action | |
1292 |
|
1292 | |||
1293 | def object_inspect(self, oname): |
|
1293 | def object_inspect(self, oname): | |
1294 | with self.builtin_trap: |
|
1294 | with self.builtin_trap: | |
1295 | info = self._object_find(oname) |
|
1295 | info = self._object_find(oname) | |
1296 | if info.found: |
|
1296 | if info.found: | |
1297 | return self.inspector.info(info.obj, oname, info=info) |
|
1297 | return self.inspector.info(info.obj, oname, info=info) | |
1298 | else: |
|
1298 | else: | |
1299 | return oinspect.object_info(name=oname, found=False) |
|
1299 | return oinspect.object_info(name=oname, found=False) | |
1300 |
|
1300 | |||
1301 | #------------------------------------------------------------------------- |
|
1301 | #------------------------------------------------------------------------- | |
1302 | # Things related to history management |
|
1302 | # Things related to history management | |
1303 | #------------------------------------------------------------------------- |
|
1303 | #------------------------------------------------------------------------- | |
1304 |
|
1304 | |||
1305 | def init_history(self): |
|
1305 | def init_history(self): | |
1306 | """Sets up the command history, and starts regular autosaves.""" |
|
1306 | """Sets up the command history, and starts regular autosaves.""" | |
1307 | self.history_manager = HistoryManager(shell=self, config=self.config) |
|
1307 | self.history_manager = HistoryManager(shell=self, config=self.config) | |
1308 |
|
1308 | |||
1309 | #------------------------------------------------------------------------- |
|
1309 | #------------------------------------------------------------------------- | |
1310 | # Things related to exception handling and tracebacks (not debugging) |
|
1310 | # Things related to exception handling and tracebacks (not debugging) | |
1311 | #------------------------------------------------------------------------- |
|
1311 | #------------------------------------------------------------------------- | |
1312 |
|
1312 | |||
1313 | def init_traceback_handlers(self, custom_exceptions): |
|
1313 | def init_traceback_handlers(self, custom_exceptions): | |
1314 | # Syntax error handler. |
|
1314 | # Syntax error handler. | |
1315 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1315 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1316 |
|
1316 | |||
1317 | # The interactive one is initialized with an offset, meaning we always |
|
1317 | # The interactive one is initialized with an offset, meaning we always | |
1318 | # want to remove the topmost item in the traceback, which is our own |
|
1318 | # want to remove the topmost item in the traceback, which is our own | |
1319 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1319 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1320 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1320 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1321 | color_scheme='NoColor', |
|
1321 | color_scheme='NoColor', | |
1322 | tb_offset = 1, |
|
1322 | tb_offset = 1, | |
1323 | check_cache=self.compile.check_cache) |
|
1323 | check_cache=self.compile.check_cache) | |
1324 |
|
1324 | |||
1325 | # The instance will store a pointer to the system-wide exception hook, |
|
1325 | # The instance will store a pointer to the system-wide exception hook, | |
1326 | # so that runtime code (such as magics) can access it. This is because |
|
1326 | # so that runtime code (such as magics) can access it. This is because | |
1327 | # during the read-eval loop, it may get temporarily overwritten. |
|
1327 | # during the read-eval loop, it may get temporarily overwritten. | |
1328 | self.sys_excepthook = sys.excepthook |
|
1328 | self.sys_excepthook = sys.excepthook | |
1329 |
|
1329 | |||
1330 | # and add any custom exception handlers the user may have specified |
|
1330 | # and add any custom exception handlers the user may have specified | |
1331 | self.set_custom_exc(*custom_exceptions) |
|
1331 | self.set_custom_exc(*custom_exceptions) | |
1332 |
|
1332 | |||
1333 | # Set the exception mode |
|
1333 | # Set the exception mode | |
1334 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1334 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1335 |
|
1335 | |||
1336 | def set_custom_exc(self, exc_tuple, handler): |
|
1336 | def set_custom_exc(self, exc_tuple, handler): | |
1337 | """set_custom_exc(exc_tuple,handler) |
|
1337 | """set_custom_exc(exc_tuple,handler) | |
1338 |
|
1338 | |||
1339 | Set a custom exception handler, which will be called if any of the |
|
1339 | Set a custom exception handler, which will be called if any of the | |
1340 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1340 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1341 | run_code() method. |
|
1341 | run_code() method. | |
1342 |
|
1342 | |||
1343 | Inputs: |
|
1343 | Inputs: | |
1344 |
|
1344 | |||
1345 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1345 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1346 | handler for. It is very important that you use a tuple, and NOT A |
|
1346 | handler for. It is very important that you use a tuple, and NOT A | |
1347 | LIST here, because of the way Python's except statement works. If |
|
1347 | LIST here, because of the way Python's except statement works. If | |
1348 | you only want to trap a single exception, use a singleton tuple: |
|
1348 | you only want to trap a single exception, use a singleton tuple: | |
1349 |
|
1349 | |||
1350 | exc_tuple == (MyCustomException,) |
|
1350 | exc_tuple == (MyCustomException,) | |
1351 |
|
1351 | |||
1352 | - handler: this must be defined as a function with the following |
|
1352 | - handler: this must be defined as a function with the following | |
1353 | basic interface:: |
|
1353 | basic interface:: | |
1354 |
|
1354 | |||
1355 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1355 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1356 | ... |
|
1356 | ... | |
1357 | # The return value must be |
|
1357 | # The return value must be | |
1358 | return structured_traceback |
|
1358 | return structured_traceback | |
1359 |
|
1359 | |||
1360 | This will be made into an instance method (via types.MethodType) |
|
1360 | This will be made into an instance method (via types.MethodType) | |
1361 | of IPython itself, and it will be called if any of the exceptions |
|
1361 | of IPython itself, and it will be called if any of the exceptions | |
1362 | listed in the exc_tuple are caught. If the handler is None, an |
|
1362 | listed in the exc_tuple are caught. If the handler is None, an | |
1363 | internal basic one is used, which just prints basic info. |
|
1363 | internal basic one is used, which just prints basic info. | |
1364 |
|
1364 | |||
1365 | WARNING: by putting in your own exception handler into IPython's main |
|
1365 | WARNING: by putting in your own exception handler into IPython's main | |
1366 | execution loop, you run a very good chance of nasty crashes. This |
|
1366 | execution loop, you run a very good chance of nasty crashes. This | |
1367 | facility should only be used if you really know what you are doing.""" |
|
1367 | facility should only be used if you really know what you are doing.""" | |
1368 |
|
1368 | |||
1369 | assert type(exc_tuple)==type(()) , \ |
|
1369 | assert type(exc_tuple)==type(()) , \ | |
1370 | "The custom exceptions must be given AS A TUPLE." |
|
1370 | "The custom exceptions must be given AS A TUPLE." | |
1371 |
|
1371 | |||
1372 | def dummy_handler(self,etype,value,tb): |
|
1372 | def dummy_handler(self,etype,value,tb): | |
1373 | print '*** Simple custom exception handler ***' |
|
1373 | print '*** Simple custom exception handler ***' | |
1374 | print 'Exception type :',etype |
|
1374 | print 'Exception type :',etype | |
1375 | print 'Exception value:',value |
|
1375 | print 'Exception value:',value | |
1376 | print 'Traceback :',tb |
|
1376 | print 'Traceback :',tb | |
1377 | print 'Source code :','\n'.join(self.buffer) |
|
1377 | print 'Source code :','\n'.join(self.buffer) | |
1378 |
|
1378 | |||
1379 | if handler is None: handler = dummy_handler |
|
1379 | if handler is None: handler = dummy_handler | |
1380 |
|
1380 | |||
1381 | self.CustomTB = types.MethodType(handler,self) |
|
1381 | self.CustomTB = types.MethodType(handler,self) | |
1382 | self.custom_exceptions = exc_tuple |
|
1382 | self.custom_exceptions = exc_tuple | |
1383 |
|
1383 | |||
1384 | def excepthook(self, etype, value, tb): |
|
1384 | def excepthook(self, etype, value, tb): | |
1385 | """One more defense for GUI apps that call sys.excepthook. |
|
1385 | """One more defense for GUI apps that call sys.excepthook. | |
1386 |
|
1386 | |||
1387 | GUI frameworks like wxPython trap exceptions and call |
|
1387 | GUI frameworks like wxPython trap exceptions and call | |
1388 | sys.excepthook themselves. I guess this is a feature that |
|
1388 | sys.excepthook themselves. I guess this is a feature that | |
1389 | enables them to keep running after exceptions that would |
|
1389 | enables them to keep running after exceptions that would | |
1390 | otherwise kill their mainloop. This is a bother for IPython |
|
1390 | otherwise kill their mainloop. This is a bother for IPython | |
1391 | which excepts to catch all of the program exceptions with a try: |
|
1391 | which excepts to catch all of the program exceptions with a try: | |
1392 | except: statement. |
|
1392 | except: statement. | |
1393 |
|
1393 | |||
1394 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1394 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1395 | any app directly invokes sys.excepthook, it will look to the user like |
|
1395 | any app directly invokes sys.excepthook, it will look to the user like | |
1396 | IPython crashed. In order to work around this, we can disable the |
|
1396 | IPython crashed. In order to work around this, we can disable the | |
1397 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1397 | CrashHandler and replace it with this excepthook instead, which prints a | |
1398 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1398 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1399 | call sys.excepthook will generate a regular-looking exception from |
|
1399 | call sys.excepthook will generate a regular-looking exception from | |
1400 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1400 | IPython, and the CrashHandler will only be triggered by real IPython | |
1401 | crashes. |
|
1401 | crashes. | |
1402 |
|
1402 | |||
1403 | This hook should be used sparingly, only in places which are not likely |
|
1403 | This hook should be used sparingly, only in places which are not likely | |
1404 | to be true IPython errors. |
|
1404 | to be true IPython errors. | |
1405 | """ |
|
1405 | """ | |
1406 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1406 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1407 |
|
1407 | |||
1408 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1408 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1409 | exception_only=False): |
|
1409 | exception_only=False): | |
1410 | """Display the exception that just occurred. |
|
1410 | """Display the exception that just occurred. | |
1411 |
|
1411 | |||
1412 | If nothing is known about the exception, this is the method which |
|
1412 | If nothing is known about the exception, this is the method which | |
1413 | should be used throughout the code for presenting user tracebacks, |
|
1413 | should be used throughout the code for presenting user tracebacks, | |
1414 | rather than directly invoking the InteractiveTB object. |
|
1414 | rather than directly invoking the InteractiveTB object. | |
1415 |
|
1415 | |||
1416 | A specific showsyntaxerror() also exists, but this method can take |
|
1416 | A specific showsyntaxerror() also exists, but this method can take | |
1417 | care of calling it if needed, so unless you are explicitly catching a |
|
1417 | care of calling it if needed, so unless you are explicitly catching a | |
1418 | SyntaxError exception, don't try to analyze the stack manually and |
|
1418 | SyntaxError exception, don't try to analyze the stack manually and | |
1419 | simply call this method.""" |
|
1419 | simply call this method.""" | |
1420 |
|
1420 | |||
1421 | try: |
|
1421 | try: | |
1422 | if exc_tuple is None: |
|
1422 | if exc_tuple is None: | |
1423 | etype, value, tb = sys.exc_info() |
|
1423 | etype, value, tb = sys.exc_info() | |
1424 | else: |
|
1424 | else: | |
1425 | etype, value, tb = exc_tuple |
|
1425 | etype, value, tb = exc_tuple | |
1426 |
|
1426 | |||
1427 | if etype is None: |
|
1427 | if etype is None: | |
1428 | if hasattr(sys, 'last_type'): |
|
1428 | if hasattr(sys, 'last_type'): | |
1429 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1429 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1430 | sys.last_traceback |
|
1430 | sys.last_traceback | |
1431 | else: |
|
1431 | else: | |
1432 | self.write_err('No traceback available to show.\n') |
|
1432 | self.write_err('No traceback available to show.\n') | |
1433 | return |
|
1433 | return | |
1434 |
|
1434 | |||
1435 | if etype is SyntaxError: |
|
1435 | if etype is SyntaxError: | |
1436 | # Though this won't be called by syntax errors in the input |
|
1436 | # Though this won't be called by syntax errors in the input | |
1437 | # line, there may be SyntaxError cases whith imported code. |
|
1437 | # line, there may be SyntaxError cases whith imported code. | |
1438 | self.showsyntaxerror(filename) |
|
1438 | self.showsyntaxerror(filename) | |
1439 | elif etype is UsageError: |
|
1439 | elif etype is UsageError: | |
1440 | print "UsageError:", value |
|
1440 | print "UsageError:", value | |
1441 | else: |
|
1441 | else: | |
1442 | # WARNING: these variables are somewhat deprecated and not |
|
1442 | # WARNING: these variables are somewhat deprecated and not | |
1443 | # necessarily safe to use in a threaded environment, but tools |
|
1443 | # necessarily safe to use in a threaded environment, but tools | |
1444 | # like pdb depend on their existence, so let's set them. If we |
|
1444 | # like pdb depend on their existence, so let's set them. If we | |
1445 | # find problems in the field, we'll need to revisit their use. |
|
1445 | # find problems in the field, we'll need to revisit their use. | |
1446 | sys.last_type = etype |
|
1446 | sys.last_type = etype | |
1447 | sys.last_value = value |
|
1447 | sys.last_value = value | |
1448 | sys.last_traceback = tb |
|
1448 | sys.last_traceback = tb | |
1449 | if etype in self.custom_exceptions: |
|
1449 | if etype in self.custom_exceptions: | |
1450 | # FIXME: Old custom traceback objects may just return a |
|
1450 | # FIXME: Old custom traceback objects may just return a | |
1451 | # string, in that case we just put it into a list |
|
1451 | # string, in that case we just put it into a list | |
1452 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1452 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1453 | if isinstance(ctb, basestring): |
|
1453 | if isinstance(ctb, basestring): | |
1454 | stb = [stb] |
|
1454 | stb = [stb] | |
1455 | else: |
|
1455 | else: | |
1456 | if exception_only: |
|
1456 | if exception_only: | |
1457 | stb = ['An exception has occurred, use %tb to see ' |
|
1457 | stb = ['An exception has occurred, use %tb to see ' | |
1458 | 'the full traceback.\n'] |
|
1458 | 'the full traceback.\n'] | |
1459 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1459 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1460 | value)) |
|
1460 | value)) | |
1461 | else: |
|
1461 | else: | |
1462 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1462 | stb = self.InteractiveTB.structured_traceback(etype, | |
1463 | value, tb, tb_offset=tb_offset) |
|
1463 | value, tb, tb_offset=tb_offset) | |
1464 |
|
1464 | |||
1465 | if self.call_pdb: |
|
1465 | if self.call_pdb: | |
1466 | # drop into debugger |
|
1466 | # drop into debugger | |
1467 | self.debugger(force=True) |
|
1467 | self.debugger(force=True) | |
1468 |
|
1468 | |||
1469 | # Actually show the traceback |
|
1469 | # Actually show the traceback | |
1470 | self._showtraceback(etype, value, stb) |
|
1470 | self._showtraceback(etype, value, stb) | |
1471 |
|
1471 | |||
1472 | except KeyboardInterrupt: |
|
1472 | except KeyboardInterrupt: | |
1473 | self.write_err("\nKeyboardInterrupt\n") |
|
1473 | self.write_err("\nKeyboardInterrupt\n") | |
1474 |
|
1474 | |||
1475 | def _showtraceback(self, etype, evalue, stb): |
|
1475 | def _showtraceback(self, etype, evalue, stb): | |
1476 | """Actually show a traceback. |
|
1476 | """Actually show a traceback. | |
1477 |
|
1477 | |||
1478 | Subclasses may override this method to put the traceback on a different |
|
1478 | Subclasses may override this method to put the traceback on a different | |
1479 | place, like a side channel. |
|
1479 | place, like a side channel. | |
1480 | """ |
|
1480 | """ | |
1481 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1481 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) | |
1482 |
|
1482 | |||
1483 | def showsyntaxerror(self, filename=None): |
|
1483 | def showsyntaxerror(self, filename=None): | |
1484 | """Display the syntax error that just occurred. |
|
1484 | """Display the syntax error that just occurred. | |
1485 |
|
1485 | |||
1486 | This doesn't display a stack trace because there isn't one. |
|
1486 | This doesn't display a stack trace because there isn't one. | |
1487 |
|
1487 | |||
1488 | If a filename is given, it is stuffed in the exception instead |
|
1488 | If a filename is given, it is stuffed in the exception instead | |
1489 | of what was there before (because Python's parser always uses |
|
1489 | of what was there before (because Python's parser always uses | |
1490 | "<string>" when reading from a string). |
|
1490 | "<string>" when reading from a string). | |
1491 | """ |
|
1491 | """ | |
1492 | etype, value, last_traceback = sys.exc_info() |
|
1492 | etype, value, last_traceback = sys.exc_info() | |
1493 |
|
1493 | |||
1494 | # See note about these variables in showtraceback() above |
|
1494 | # See note about these variables in showtraceback() above | |
1495 | sys.last_type = etype |
|
1495 | sys.last_type = etype | |
1496 | sys.last_value = value |
|
1496 | sys.last_value = value | |
1497 | sys.last_traceback = last_traceback |
|
1497 | sys.last_traceback = last_traceback | |
1498 |
|
1498 | |||
1499 | if filename and etype is SyntaxError: |
|
1499 | if filename and etype is SyntaxError: | |
1500 | # Work hard to stuff the correct filename in the exception |
|
1500 | # Work hard to stuff the correct filename in the exception | |
1501 | try: |
|
1501 | try: | |
1502 | msg, (dummy_filename, lineno, offset, line) = value |
|
1502 | msg, (dummy_filename, lineno, offset, line) = value | |
1503 | except: |
|
1503 | except: | |
1504 | # Not the format we expect; leave it alone |
|
1504 | # Not the format we expect; leave it alone | |
1505 | pass |
|
1505 | pass | |
1506 | else: |
|
1506 | else: | |
1507 | # Stuff in the right filename |
|
1507 | # Stuff in the right filename | |
1508 | try: |
|
1508 | try: | |
1509 | # Assume SyntaxError is a class exception |
|
1509 | # Assume SyntaxError is a class exception | |
1510 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1510 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1511 | except: |
|
1511 | except: | |
1512 | # If that failed, assume SyntaxError is a string |
|
1512 | # If that failed, assume SyntaxError is a string | |
1513 | value = msg, (filename, lineno, offset, line) |
|
1513 | value = msg, (filename, lineno, offset, line) | |
1514 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1514 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1515 | self._showtraceback(etype, value, stb) |
|
1515 | self._showtraceback(etype, value, stb) | |
1516 |
|
1516 | |||
1517 | #------------------------------------------------------------------------- |
|
1517 | #------------------------------------------------------------------------- | |
1518 | # Things related to readline |
|
1518 | # Things related to readline | |
1519 | #------------------------------------------------------------------------- |
|
1519 | #------------------------------------------------------------------------- | |
1520 |
|
1520 | |||
1521 | def init_readline(self): |
|
1521 | def init_readline(self): | |
1522 | """Command history completion/saving/reloading.""" |
|
1522 | """Command history completion/saving/reloading.""" | |
1523 |
|
1523 | |||
1524 | if self.readline_use: |
|
1524 | if self.readline_use: | |
1525 | import IPython.utils.rlineimpl as readline |
|
1525 | import IPython.utils.rlineimpl as readline | |
1526 |
|
1526 | |||
1527 | self.rl_next_input = None |
|
1527 | self.rl_next_input = None | |
1528 | self.rl_do_indent = False |
|
1528 | self.rl_do_indent = False | |
1529 |
|
1529 | |||
1530 | if not self.readline_use or not readline.have_readline: |
|
1530 | if not self.readline_use or not readline.have_readline: | |
1531 | self.has_readline = False |
|
1531 | self.has_readline = False | |
1532 | self.readline = None |
|
1532 | self.readline = None | |
1533 | # Set a number of methods that depend on readline to be no-op |
|
1533 | # Set a number of methods that depend on readline to be no-op | |
1534 | self.set_readline_completer = no_op |
|
1534 | self.set_readline_completer = no_op | |
1535 | self.set_custom_completer = no_op |
|
1535 | self.set_custom_completer = no_op | |
1536 | self.set_completer_frame = no_op |
|
1536 | self.set_completer_frame = no_op | |
1537 | warn('Readline services not available or not loaded.') |
|
1537 | warn('Readline services not available or not loaded.') | |
1538 | else: |
|
1538 | else: | |
1539 | self.has_readline = True |
|
1539 | self.has_readline = True | |
1540 | self.readline = readline |
|
1540 | self.readline = readline | |
1541 | sys.modules['readline'] = readline |
|
1541 | sys.modules['readline'] = readline | |
1542 |
|
1542 | |||
1543 | # Platform-specific configuration |
|
1543 | # Platform-specific configuration | |
1544 | if os.name == 'nt': |
|
1544 | if os.name == 'nt': | |
1545 | # FIXME - check with Frederick to see if we can harmonize |
|
1545 | # FIXME - check with Frederick to see if we can harmonize | |
1546 | # naming conventions with pyreadline to avoid this |
|
1546 | # naming conventions with pyreadline to avoid this | |
1547 | # platform-dependent check |
|
1547 | # platform-dependent check | |
1548 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1548 | self.readline_startup_hook = readline.set_pre_input_hook | |
1549 | else: |
|
1549 | else: | |
1550 | self.readline_startup_hook = readline.set_startup_hook |
|
1550 | self.readline_startup_hook = readline.set_startup_hook | |
1551 |
|
1551 | |||
1552 | # Load user's initrc file (readline config) |
|
1552 | # Load user's initrc file (readline config) | |
1553 | # Or if libedit is used, load editrc. |
|
1553 | # Or if libedit is used, load editrc. | |
1554 | inputrc_name = os.environ.get('INPUTRC') |
|
1554 | inputrc_name = os.environ.get('INPUTRC') | |
1555 | if inputrc_name is None: |
|
1555 | if inputrc_name is None: | |
1556 | home_dir = get_home_dir() |
|
1556 | home_dir = get_home_dir() | |
1557 | if home_dir is not None: |
|
1557 | if home_dir is not None: | |
1558 | inputrc_name = '.inputrc' |
|
1558 | inputrc_name = '.inputrc' | |
1559 | if readline.uses_libedit: |
|
1559 | if readline.uses_libedit: | |
1560 | inputrc_name = '.editrc' |
|
1560 | inputrc_name = '.editrc' | |
1561 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1561 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1562 | if os.path.isfile(inputrc_name): |
|
1562 | if os.path.isfile(inputrc_name): | |
1563 | try: |
|
1563 | try: | |
1564 | readline.read_init_file(inputrc_name) |
|
1564 | readline.read_init_file(inputrc_name) | |
1565 | except: |
|
1565 | except: | |
1566 | warn('Problems reading readline initialization file <%s>' |
|
1566 | warn('Problems reading readline initialization file <%s>' | |
1567 | % inputrc_name) |
|
1567 | % inputrc_name) | |
1568 |
|
1568 | |||
1569 | # Configure readline according to user's prefs |
|
1569 | # Configure readline according to user's prefs | |
1570 | # This is only done if GNU readline is being used. If libedit |
|
1570 | # This is only done if GNU readline is being used. If libedit | |
1571 | # is being used (as on Leopard) the readline config is |
|
1571 | # is being used (as on Leopard) the readline config is | |
1572 | # not run as the syntax for libedit is different. |
|
1572 | # not run as the syntax for libedit is different. | |
1573 | if not readline.uses_libedit: |
|
1573 | if not readline.uses_libedit: | |
1574 | for rlcommand in self.readline_parse_and_bind: |
|
1574 | for rlcommand in self.readline_parse_and_bind: | |
1575 | #print "loading rl:",rlcommand # dbg |
|
1575 | #print "loading rl:",rlcommand # dbg | |
1576 | readline.parse_and_bind(rlcommand) |
|
1576 | readline.parse_and_bind(rlcommand) | |
1577 |
|
1577 | |||
1578 | # Remove some chars from the delimiters list. If we encounter |
|
1578 | # Remove some chars from the delimiters list. If we encounter | |
1579 | # unicode chars, discard them. |
|
1579 | # unicode chars, discard them. | |
1580 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1580 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1581 | delims = delims.translate(None, self.readline_remove_delims) |
|
1581 | delims = delims.translate(None, self.readline_remove_delims) | |
1582 | delims = delims.replace(ESC_MAGIC, '') |
|
1582 | delims = delims.replace(ESC_MAGIC, '') | |
1583 | readline.set_completer_delims(delims) |
|
1583 | readline.set_completer_delims(delims) | |
1584 | # otherwise we end up with a monster history after a while: |
|
1584 | # otherwise we end up with a monster history after a while: | |
1585 | readline.set_history_length(self.history_length) |
|
1585 | readline.set_history_length(self.history_length) | |
1586 |
|
1586 | |||
1587 | self.refill_readline_hist() |
|
1587 | self.refill_readline_hist() | |
1588 | self.readline_no_record = ReadlineNoRecord(self) |
|
1588 | self.readline_no_record = ReadlineNoRecord(self) | |
1589 |
|
1589 | |||
1590 | # Configure auto-indent for all platforms |
|
1590 | # Configure auto-indent for all platforms | |
1591 | self.set_autoindent(self.autoindent) |
|
1591 | self.set_autoindent(self.autoindent) | |
1592 |
|
1592 | |||
1593 | def refill_readline_hist(self): |
|
1593 | def refill_readline_hist(self): | |
1594 | # Load the last 1000 lines from history |
|
1594 | # Load the last 1000 lines from history | |
1595 | self.readline.clear_history() |
|
1595 | self.readline.clear_history() | |
1596 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1596 | stdin_encoding = sys.stdin.encoding or "utf-8" | |
1597 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1597 | for _, _, cell in self.history_manager.get_tail(1000, | |
1598 | include_latest=True): |
|
1598 | include_latest=True): | |
1599 | if cell.strip(): # Ignore blank lines |
|
1599 | if cell.strip(): # Ignore blank lines | |
1600 | for line in cell.splitlines(): |
|
1600 | for line in cell.splitlines(): | |
1601 | self.readline.add_history(line.encode(stdin_encoding)) |
|
1601 | self.readline.add_history(line.encode(stdin_encoding)) | |
1602 |
|
1602 | |||
1603 | def set_next_input(self, s): |
|
1603 | def set_next_input(self, s): | |
1604 | """ Sets the 'default' input string for the next command line. |
|
1604 | """ Sets the 'default' input string for the next command line. | |
1605 |
|
1605 | |||
1606 | Requires readline. |
|
1606 | Requires readline. | |
1607 |
|
1607 | |||
1608 | Example: |
|
1608 | Example: | |
1609 |
|
1609 | |||
1610 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1610 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1611 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1611 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1612 | """ |
|
1612 | """ | |
1613 |
|
1613 | |||
1614 | self.rl_next_input = s |
|
1614 | self.rl_next_input = s | |
1615 |
|
1615 | |||
1616 | # Maybe move this to the terminal subclass? |
|
1616 | # Maybe move this to the terminal subclass? | |
1617 | def pre_readline(self): |
|
1617 | def pre_readline(self): | |
1618 | """readline hook to be used at the start of each line. |
|
1618 | """readline hook to be used at the start of each line. | |
1619 |
|
1619 | |||
1620 | Currently it handles auto-indent only.""" |
|
1620 | Currently it handles auto-indent only.""" | |
1621 |
|
1621 | |||
1622 | if self.rl_do_indent: |
|
1622 | if self.rl_do_indent: | |
1623 | self.readline.insert_text(self._indent_current_str()) |
|
1623 | self.readline.insert_text(self._indent_current_str()) | |
1624 | if self.rl_next_input is not None: |
|
1624 | if self.rl_next_input is not None: | |
1625 | self.readline.insert_text(self.rl_next_input) |
|
1625 | self.readline.insert_text(self.rl_next_input) | |
1626 | self.rl_next_input = None |
|
1626 | self.rl_next_input = None | |
1627 |
|
1627 | |||
1628 | def _indent_current_str(self): |
|
1628 | def _indent_current_str(self): | |
1629 | """return the current level of indentation as a string""" |
|
1629 | """return the current level of indentation as a string""" | |
1630 | return self.input_splitter.indent_spaces * ' ' |
|
1630 | return self.input_splitter.indent_spaces * ' ' | |
1631 |
|
1631 | |||
1632 | #------------------------------------------------------------------------- |
|
1632 | #------------------------------------------------------------------------- | |
1633 | # Things related to text completion |
|
1633 | # Things related to text completion | |
1634 | #------------------------------------------------------------------------- |
|
1634 | #------------------------------------------------------------------------- | |
1635 |
|
1635 | |||
1636 | def init_completer(self): |
|
1636 | def init_completer(self): | |
1637 | """Initialize the completion machinery. |
|
1637 | """Initialize the completion machinery. | |
1638 |
|
1638 | |||
1639 | This creates completion machinery that can be used by client code, |
|
1639 | This creates completion machinery that can be used by client code, | |
1640 | either interactively in-process (typically triggered by the readline |
|
1640 | either interactively in-process (typically triggered by the readline | |
1641 | library), programatically (such as in test suites) or out-of-prcess |
|
1641 | library), programatically (such as in test suites) or out-of-prcess | |
1642 | (typically over the network by remote frontends). |
|
1642 | (typically over the network by remote frontends). | |
1643 | """ |
|
1643 | """ | |
1644 | from IPython.core.completer import IPCompleter |
|
1644 | from IPython.core.completer import IPCompleter | |
1645 | from IPython.core.completerlib import (module_completer, |
|
1645 | from IPython.core.completerlib import (module_completer, | |
1646 | magic_run_completer, cd_completer) |
|
1646 | magic_run_completer, cd_completer) | |
1647 |
|
1647 | |||
1648 | self.Completer = IPCompleter(self, |
|
1648 | self.Completer = IPCompleter(self, | |
1649 | self.user_ns, |
|
1649 | self.user_ns, | |
1650 | self.user_global_ns, |
|
1650 | self.user_global_ns, | |
1651 | self.readline_omit__names, |
|
1651 | self.readline_omit__names, | |
1652 | self.alias_manager.alias_table, |
|
1652 | self.alias_manager.alias_table, | |
1653 | self.has_readline) |
|
1653 | self.has_readline) | |
1654 |
|
1654 | |||
1655 | # Add custom completers to the basic ones built into IPCompleter |
|
1655 | # Add custom completers to the basic ones built into IPCompleter | |
1656 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1656 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1657 | self.strdispatchers['complete_command'] = sdisp |
|
1657 | self.strdispatchers['complete_command'] = sdisp | |
1658 | self.Completer.custom_completers = sdisp |
|
1658 | self.Completer.custom_completers = sdisp | |
1659 |
|
1659 | |||
1660 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1660 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1661 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1661 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1662 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1662 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1663 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1663 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1664 |
|
1664 | |||
1665 | # Only configure readline if we truly are using readline. IPython can |
|
1665 | # Only configure readline if we truly are using readline. IPython can | |
1666 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1666 | # do tab-completion over the network, in GUIs, etc, where readline | |
1667 | # itself may be absent |
|
1667 | # itself may be absent | |
1668 | if self.has_readline: |
|
1668 | if self.has_readline: | |
1669 | self.set_readline_completer() |
|
1669 | self.set_readline_completer() | |
1670 |
|
1670 | |||
1671 | def complete(self, text, line=None, cursor_pos=None): |
|
1671 | def complete(self, text, line=None, cursor_pos=None): | |
1672 | """Return the completed text and a list of completions. |
|
1672 | """Return the completed text and a list of completions. | |
1673 |
|
1673 | |||
1674 | Parameters |
|
1674 | Parameters | |
1675 | ---------- |
|
1675 | ---------- | |
1676 |
|
1676 | |||
1677 | text : string |
|
1677 | text : string | |
1678 | A string of text to be completed on. It can be given as empty and |
|
1678 | A string of text to be completed on. It can be given as empty and | |
1679 | instead a line/position pair are given. In this case, the |
|
1679 | instead a line/position pair are given. In this case, the | |
1680 | completer itself will split the line like readline does. |
|
1680 | completer itself will split the line like readline does. | |
1681 |
|
1681 | |||
1682 | line : string, optional |
|
1682 | line : string, optional | |
1683 | The complete line that text is part of. |
|
1683 | The complete line that text is part of. | |
1684 |
|
1684 | |||
1685 | cursor_pos : int, optional |
|
1685 | cursor_pos : int, optional | |
1686 | The position of the cursor on the input line. |
|
1686 | The position of the cursor on the input line. | |
1687 |
|
1687 | |||
1688 | Returns |
|
1688 | Returns | |
1689 | ------- |
|
1689 | ------- | |
1690 | text : string |
|
1690 | text : string | |
1691 | The actual text that was completed. |
|
1691 | The actual text that was completed. | |
1692 |
|
1692 | |||
1693 | matches : list |
|
1693 | matches : list | |
1694 | A sorted list with all possible completions. |
|
1694 | A sorted list with all possible completions. | |
1695 |
|
1695 | |||
1696 | The optional arguments allow the completion to take more context into |
|
1696 | The optional arguments allow the completion to take more context into | |
1697 | account, and are part of the low-level completion API. |
|
1697 | account, and are part of the low-level completion API. | |
1698 |
|
1698 | |||
1699 | This is a wrapper around the completion mechanism, similar to what |
|
1699 | This is a wrapper around the completion mechanism, similar to what | |
1700 | readline does at the command line when the TAB key is hit. By |
|
1700 | readline does at the command line when the TAB key is hit. By | |
1701 | exposing it as a method, it can be used by other non-readline |
|
1701 | exposing it as a method, it can be used by other non-readline | |
1702 | environments (such as GUIs) for text completion. |
|
1702 | environments (such as GUIs) for text completion. | |
1703 |
|
1703 | |||
1704 | Simple usage example: |
|
1704 | Simple usage example: | |
1705 |
|
1705 | |||
1706 | In [1]: x = 'hello' |
|
1706 | In [1]: x = 'hello' | |
1707 |
|
1707 | |||
1708 | In [2]: _ip.complete('x.l') |
|
1708 | In [2]: _ip.complete('x.l') | |
1709 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1709 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1710 | """ |
|
1710 | """ | |
1711 |
|
1711 | |||
1712 | # Inject names into __builtin__ so we can complete on the added names. |
|
1712 | # Inject names into __builtin__ so we can complete on the added names. | |
1713 | with self.builtin_trap: |
|
1713 | with self.builtin_trap: | |
1714 | return self.Completer.complete(text, line, cursor_pos) |
|
1714 | return self.Completer.complete(text, line, cursor_pos) | |
1715 |
|
1715 | |||
1716 | def set_custom_completer(self, completer, pos=0): |
|
1716 | def set_custom_completer(self, completer, pos=0): | |
1717 | """Adds a new custom completer function. |
|
1717 | """Adds a new custom completer function. | |
1718 |
|
1718 | |||
1719 | The position argument (defaults to 0) is the index in the completers |
|
1719 | The position argument (defaults to 0) is the index in the completers | |
1720 | list where you want the completer to be inserted.""" |
|
1720 | list where you want the completer to be inserted.""" | |
1721 |
|
1721 | |||
1722 | newcomp = types.MethodType(completer,self.Completer) |
|
1722 | newcomp = types.MethodType(completer,self.Completer) | |
1723 | self.Completer.matchers.insert(pos,newcomp) |
|
1723 | self.Completer.matchers.insert(pos,newcomp) | |
1724 |
|
1724 | |||
1725 | def set_readline_completer(self): |
|
1725 | def set_readline_completer(self): | |
1726 | """Reset readline's completer to be our own.""" |
|
1726 | """Reset readline's completer to be our own.""" | |
1727 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1727 | self.readline.set_completer(self.Completer.rlcomplete) | |
1728 |
|
1728 | |||
1729 | def set_completer_frame(self, frame=None): |
|
1729 | def set_completer_frame(self, frame=None): | |
1730 | """Set the frame of the completer.""" |
|
1730 | """Set the frame of the completer.""" | |
1731 | if frame: |
|
1731 | if frame: | |
1732 | self.Completer.namespace = frame.f_locals |
|
1732 | self.Completer.namespace = frame.f_locals | |
1733 | self.Completer.global_namespace = frame.f_globals |
|
1733 | self.Completer.global_namespace = frame.f_globals | |
1734 | else: |
|
1734 | else: | |
1735 | self.Completer.namespace = self.user_ns |
|
1735 | self.Completer.namespace = self.user_ns | |
1736 | self.Completer.global_namespace = self.user_global_ns |
|
1736 | self.Completer.global_namespace = self.user_global_ns | |
1737 |
|
1737 | |||
1738 | #------------------------------------------------------------------------- |
|
1738 | #------------------------------------------------------------------------- | |
1739 | # Things related to magics |
|
1739 | # Things related to magics | |
1740 | #------------------------------------------------------------------------- |
|
1740 | #------------------------------------------------------------------------- | |
1741 |
|
1741 | |||
1742 | def init_magics(self): |
|
1742 | def init_magics(self): | |
1743 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1743 | # FIXME: Move the color initialization to the DisplayHook, which | |
1744 | # should be split into a prompt manager and displayhook. We probably |
|
1744 | # should be split into a prompt manager and displayhook. We probably | |
1745 | # even need a centralize colors management object. |
|
1745 | # even need a centralize colors management object. | |
1746 | self.magic_colors(self.colors) |
|
1746 | self.magic_colors(self.colors) | |
1747 | # History was moved to a separate module |
|
1747 | # History was moved to a separate module | |
1748 | from . import history |
|
1748 | from . import history | |
1749 | history.init_ipython(self) |
|
1749 | history.init_ipython(self) | |
1750 |
|
1750 | |||
1751 | def magic(self,arg_s): |
|
1751 | def magic(self,arg_s): | |
1752 | """Call a magic function by name. |
|
1752 | """Call a magic function by name. | |
1753 |
|
1753 | |||
1754 | Input: a string containing the name of the magic function to call and |
|
1754 | Input: a string containing the name of the magic function to call and | |
1755 | any additional arguments to be passed to the magic. |
|
1755 | any additional arguments to be passed to the magic. | |
1756 |
|
1756 | |||
1757 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1757 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1758 | prompt: |
|
1758 | prompt: | |
1759 |
|
1759 | |||
1760 | In[1]: %name -opt foo bar |
|
1760 | In[1]: %name -opt foo bar | |
1761 |
|
1761 | |||
1762 | To call a magic without arguments, simply use magic('name'). |
|
1762 | To call a magic without arguments, simply use magic('name'). | |
1763 |
|
1763 | |||
1764 | This provides a proper Python function to call IPython's magics in any |
|
1764 | This provides a proper Python function to call IPython's magics in any | |
1765 | valid Python code you can type at the interpreter, including loops and |
|
1765 | valid Python code you can type at the interpreter, including loops and | |
1766 | compound statements. |
|
1766 | compound statements. | |
1767 | """ |
|
1767 | """ | |
1768 | args = arg_s.split(' ',1) |
|
1768 | args = arg_s.split(' ',1) | |
1769 | magic_name = args[0] |
|
1769 | magic_name = args[0] | |
1770 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1770 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1771 |
|
1771 | |||
1772 | try: |
|
1772 | try: | |
1773 | magic_args = args[1] |
|
1773 | magic_args = args[1] | |
1774 | except IndexError: |
|
1774 | except IndexError: | |
1775 | magic_args = '' |
|
1775 | magic_args = '' | |
1776 | fn = getattr(self,'magic_'+magic_name,None) |
|
1776 | fn = getattr(self,'magic_'+magic_name,None) | |
1777 | if fn is None: |
|
1777 | if fn is None: | |
1778 | error("Magic function `%s` not found." % magic_name) |
|
1778 | error("Magic function `%s` not found." % magic_name) | |
1779 | else: |
|
1779 | else: | |
1780 | magic_args = self.var_expand(magic_args,1) |
|
1780 | magic_args = self.var_expand(magic_args,1) | |
1781 | # Grab local namespace if we need it: |
|
1781 | # Grab local namespace if we need it: | |
1782 | if getattr(fn, "needs_local_scope", False): |
|
1782 | if getattr(fn, "needs_local_scope", False): | |
1783 | self._magic_locals = sys._getframe(1).f_locals |
|
1783 | self._magic_locals = sys._getframe(1).f_locals | |
1784 | with self.builtin_trap: |
|
1784 | with self.builtin_trap: | |
1785 | result = fn(magic_args) |
|
1785 | result = fn(magic_args) | |
1786 | # Ensure we're not keeping object references around: |
|
1786 | # Ensure we're not keeping object references around: | |
1787 | self._magic_locals = {} |
|
1787 | self._magic_locals = {} | |
1788 | return result |
|
1788 | return result | |
1789 |
|
1789 | |||
1790 | def define_magic(self, magicname, func): |
|
1790 | def define_magic(self, magicname, func): | |
1791 | """Expose own function as magic function for ipython |
|
1791 | """Expose own function as magic function for ipython | |
1792 |
|
1792 | |||
1793 | def foo_impl(self,parameter_s=''): |
|
1793 | def foo_impl(self,parameter_s=''): | |
1794 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1794 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1795 | print 'Magic function. Passed parameter is between < >:' |
|
1795 | print 'Magic function. Passed parameter is between < >:' | |
1796 | print '<%s>' % parameter_s |
|
1796 | print '<%s>' % parameter_s | |
1797 | print 'The self object is:',self |
|
1797 | print 'The self object is:',self | |
1798 |
|
1798 | |||
1799 | self.define_magic('foo',foo_impl) |
|
1799 | self.define_magic('foo',foo_impl) | |
1800 | """ |
|
1800 | """ | |
1801 |
|
1801 | |||
1802 | import new |
|
1802 | import new | |
1803 | im = types.MethodType(func,self) |
|
1803 | im = types.MethodType(func,self) | |
1804 | old = getattr(self, "magic_" + magicname, None) |
|
1804 | old = getattr(self, "magic_" + magicname, None) | |
1805 | setattr(self, "magic_" + magicname, im) |
|
1805 | setattr(self, "magic_" + magicname, im) | |
1806 | return old |
|
1806 | return old | |
1807 |
|
1807 | |||
1808 | #------------------------------------------------------------------------- |
|
1808 | #------------------------------------------------------------------------- | |
1809 | # Things related to macros |
|
1809 | # Things related to macros | |
1810 | #------------------------------------------------------------------------- |
|
1810 | #------------------------------------------------------------------------- | |
1811 |
|
1811 | |||
1812 | def define_macro(self, name, themacro): |
|
1812 | def define_macro(self, name, themacro): | |
1813 | """Define a new macro |
|
1813 | """Define a new macro | |
1814 |
|
1814 | |||
1815 | Parameters |
|
1815 | Parameters | |
1816 | ---------- |
|
1816 | ---------- | |
1817 | name : str |
|
1817 | name : str | |
1818 | The name of the macro. |
|
1818 | The name of the macro. | |
1819 | themacro : str or Macro |
|
1819 | themacro : str or Macro | |
1820 | The action to do upon invoking the macro. If a string, a new |
|
1820 | The action to do upon invoking the macro. If a string, a new | |
1821 | Macro object is created by passing the string to it. |
|
1821 | Macro object is created by passing the string to it. | |
1822 | """ |
|
1822 | """ | |
1823 |
|
1823 | |||
1824 | from IPython.core import macro |
|
1824 | from IPython.core import macro | |
1825 |
|
1825 | |||
1826 | if isinstance(themacro, basestring): |
|
1826 | if isinstance(themacro, basestring): | |
1827 | themacro = macro.Macro(themacro) |
|
1827 | themacro = macro.Macro(themacro) | |
1828 | if not isinstance(themacro, macro.Macro): |
|
1828 | if not isinstance(themacro, macro.Macro): | |
1829 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1829 | raise ValueError('A macro must be a string or a Macro instance.') | |
1830 | self.user_ns[name] = themacro |
|
1830 | self.user_ns[name] = themacro | |
1831 |
|
1831 | |||
1832 | #------------------------------------------------------------------------- |
|
1832 | #------------------------------------------------------------------------- | |
1833 | # Things related to the running of system commands |
|
1833 | # Things related to the running of system commands | |
1834 | #------------------------------------------------------------------------- |
|
1834 | #------------------------------------------------------------------------- | |
1835 |
|
1835 | |||
1836 | def system(self, cmd): |
|
1836 | def system(self, cmd): | |
1837 | """Call the given cmd in a subprocess. |
|
1837 | """Call the given cmd in a subprocess. | |
1838 |
|
1838 | |||
1839 | Parameters |
|
1839 | Parameters | |
1840 | ---------- |
|
1840 | ---------- | |
1841 | cmd : str |
|
1841 | cmd : str | |
1842 | Command to execute (can not end in '&', as bacground processes are |
|
1842 | Command to execute (can not end in '&', as bacground processes are | |
1843 | not supported. |
|
1843 | not supported. | |
1844 | """ |
|
1844 | """ | |
1845 | # We do not support backgrounding processes because we either use |
|
1845 | # We do not support backgrounding processes because we either use | |
1846 | # pexpect or pipes to read from. Users can always just call |
|
1846 | # pexpect or pipes to read from. Users can always just call | |
1847 | # os.system() if they really want a background process. |
|
1847 | # os.system() if they really want a background process. | |
1848 | if cmd.endswith('&'): |
|
1848 | if cmd.endswith('&'): | |
1849 | raise OSError("Background processes not supported.") |
|
1849 | raise OSError("Background processes not supported.") | |
1850 |
|
1850 | |||
1851 | return system(self.var_expand(cmd, depth=2)) |
|
1851 | return system(self.var_expand(cmd, depth=2)) | |
1852 |
|
1852 | |||
1853 | def getoutput(self, cmd, split=True): |
|
1853 | def getoutput(self, cmd, split=True): | |
1854 | """Get output (possibly including stderr) from a subprocess. |
|
1854 | """Get output (possibly including stderr) from a subprocess. | |
1855 |
|
1855 | |||
1856 | Parameters |
|
1856 | Parameters | |
1857 | ---------- |
|
1857 | ---------- | |
1858 | cmd : str |
|
1858 | cmd : str | |
1859 | Command to execute (can not end in '&', as background processes are |
|
1859 | Command to execute (can not end in '&', as background processes are | |
1860 | not supported. |
|
1860 | not supported. | |
1861 | split : bool, optional |
|
1861 | split : bool, optional | |
1862 |
|
1862 | |||
1863 | If True, split the output into an IPython SList. Otherwise, an |
|
1863 | If True, split the output into an IPython SList. Otherwise, an | |
1864 | IPython LSString is returned. These are objects similar to normal |
|
1864 | IPython LSString is returned. These are objects similar to normal | |
1865 | lists and strings, with a few convenience attributes for easier |
|
1865 | lists and strings, with a few convenience attributes for easier | |
1866 | manipulation of line-based output. You can use '?' on them for |
|
1866 | manipulation of line-based output. You can use '?' on them for | |
1867 | details. |
|
1867 | details. | |
1868 | """ |
|
1868 | """ | |
1869 | if cmd.endswith('&'): |
|
1869 | if cmd.endswith('&'): | |
1870 | raise OSError("Background processes not supported.") |
|
1870 | raise OSError("Background processes not supported.") | |
1871 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1871 | out = getoutput(self.var_expand(cmd, depth=2)) | |
1872 | if split: |
|
1872 | if split: | |
1873 | out = SList(out.splitlines()) |
|
1873 | out = SList(out.splitlines()) | |
1874 | else: |
|
1874 | else: | |
1875 | out = LSString(out) |
|
1875 | out = LSString(out) | |
1876 | return out |
|
1876 | return out | |
1877 |
|
1877 | |||
1878 | #------------------------------------------------------------------------- |
|
1878 | #------------------------------------------------------------------------- | |
1879 | # Things related to aliases |
|
1879 | # Things related to aliases | |
1880 | #------------------------------------------------------------------------- |
|
1880 | #------------------------------------------------------------------------- | |
1881 |
|
1881 | |||
1882 | def init_alias(self): |
|
1882 | def init_alias(self): | |
1883 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1883 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1884 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1884 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1885 |
|
1885 | |||
1886 | #------------------------------------------------------------------------- |
|
1886 | #------------------------------------------------------------------------- | |
1887 | # Things related to extensions and plugins |
|
1887 | # Things related to extensions and plugins | |
1888 | #------------------------------------------------------------------------- |
|
1888 | #------------------------------------------------------------------------- | |
1889 |
|
1889 | |||
1890 | def init_extension_manager(self): |
|
1890 | def init_extension_manager(self): | |
1891 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1891 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1892 |
|
1892 | |||
1893 | def init_plugin_manager(self): |
|
1893 | def init_plugin_manager(self): | |
1894 | self.plugin_manager = PluginManager(config=self.config) |
|
1894 | self.plugin_manager = PluginManager(config=self.config) | |
1895 |
|
1895 | |||
1896 | #------------------------------------------------------------------------- |
|
1896 | #------------------------------------------------------------------------- | |
1897 | # Things related to payloads |
|
1897 | # Things related to payloads | |
1898 | #------------------------------------------------------------------------- |
|
1898 | #------------------------------------------------------------------------- | |
1899 |
|
1899 | |||
1900 | def init_payload(self): |
|
1900 | def init_payload(self): | |
1901 | self.payload_manager = PayloadManager(config=self.config) |
|
1901 | self.payload_manager = PayloadManager(config=self.config) | |
1902 |
|
1902 | |||
1903 | #------------------------------------------------------------------------- |
|
1903 | #------------------------------------------------------------------------- | |
1904 | # Things related to the prefilter |
|
1904 | # Things related to the prefilter | |
1905 | #------------------------------------------------------------------------- |
|
1905 | #------------------------------------------------------------------------- | |
1906 |
|
1906 | |||
1907 | def init_prefilter(self): |
|
1907 | def init_prefilter(self): | |
1908 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1908 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1909 | # Ultimately this will be refactored in the new interpreter code, but |
|
1909 | # Ultimately this will be refactored in the new interpreter code, but | |
1910 | # for now, we should expose the main prefilter method (there's legacy |
|
1910 | # for now, we should expose the main prefilter method (there's legacy | |
1911 | # code out there that may rely on this). |
|
1911 | # code out there that may rely on this). | |
1912 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1912 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1913 |
|
1913 | |||
1914 | def auto_rewrite_input(self, cmd): |
|
1914 | def auto_rewrite_input(self, cmd): | |
1915 | """Print to the screen the rewritten form of the user's command. |
|
1915 | """Print to the screen the rewritten form of the user's command. | |
1916 |
|
1916 | |||
1917 | This shows visual feedback by rewriting input lines that cause |
|
1917 | This shows visual feedback by rewriting input lines that cause | |
1918 | automatic calling to kick in, like:: |
|
1918 | automatic calling to kick in, like:: | |
1919 |
|
1919 | |||
1920 | /f x |
|
1920 | /f x | |
1921 |
|
1921 | |||
1922 | into:: |
|
1922 | into:: | |
1923 |
|
1923 | |||
1924 | ------> f(x) |
|
1924 | ------> f(x) | |
1925 |
|
1925 | |||
1926 | after the user's input prompt. This helps the user understand that the |
|
1926 | after the user's input prompt. This helps the user understand that the | |
1927 | input line was transformed automatically by IPython. |
|
1927 | input line was transformed automatically by IPython. | |
1928 | """ |
|
1928 | """ | |
1929 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1929 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
1930 |
|
1930 | |||
1931 | try: |
|
1931 | try: | |
1932 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1932 | # plain ascii works better w/ pyreadline, on some machines, so | |
1933 | # we use it and only print uncolored rewrite if we have unicode |
|
1933 | # we use it and only print uncolored rewrite if we have unicode | |
1934 | rw = str(rw) |
|
1934 | rw = str(rw) | |
1935 | print >> IPython.utils.io.Term.cout, rw |
|
1935 | print >> IPython.utils.io.Term.cout, rw | |
1936 | except UnicodeEncodeError: |
|
1936 | except UnicodeEncodeError: | |
1937 | print "------> " + cmd |
|
1937 | print "------> " + cmd | |
1938 |
|
1938 | |||
1939 | #------------------------------------------------------------------------- |
|
1939 | #------------------------------------------------------------------------- | |
1940 | # Things related to extracting values/expressions from kernel and user_ns |
|
1940 | # Things related to extracting values/expressions from kernel and user_ns | |
1941 | #------------------------------------------------------------------------- |
|
1941 | #------------------------------------------------------------------------- | |
1942 |
|
1942 | |||
1943 | def _simple_error(self): |
|
1943 | def _simple_error(self): | |
1944 | etype, value = sys.exc_info()[:2] |
|
1944 | etype, value = sys.exc_info()[:2] | |
1945 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1945 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1946 |
|
1946 | |||
1947 | def user_variables(self, names): |
|
1947 | def user_variables(self, names): | |
1948 | """Get a list of variable names from the user's namespace. |
|
1948 | """Get a list of variable names from the user's namespace. | |
1949 |
|
1949 | |||
1950 | Parameters |
|
1950 | Parameters | |
1951 | ---------- |
|
1951 | ---------- | |
1952 | names : list of strings |
|
1952 | names : list of strings | |
1953 | A list of names of variables to be read from the user namespace. |
|
1953 | A list of names of variables to be read from the user namespace. | |
1954 |
|
1954 | |||
1955 | Returns |
|
1955 | Returns | |
1956 | ------- |
|
1956 | ------- | |
1957 | A dict, keyed by the input names and with the repr() of each value. |
|
1957 | A dict, keyed by the input names and with the repr() of each value. | |
1958 | """ |
|
1958 | """ | |
1959 | out = {} |
|
1959 | out = {} | |
1960 | user_ns = self.user_ns |
|
1960 | user_ns = self.user_ns | |
1961 | for varname in names: |
|
1961 | for varname in names: | |
1962 | try: |
|
1962 | try: | |
1963 | value = repr(user_ns[varname]) |
|
1963 | value = repr(user_ns[varname]) | |
1964 | except: |
|
1964 | except: | |
1965 | value = self._simple_error() |
|
1965 | value = self._simple_error() | |
1966 | out[varname] = value |
|
1966 | out[varname] = value | |
1967 | return out |
|
1967 | return out | |
1968 |
|
1968 | |||
1969 | def user_expressions(self, expressions): |
|
1969 | def user_expressions(self, expressions): | |
1970 | """Evaluate a dict of expressions in the user's namespace. |
|
1970 | """Evaluate a dict of expressions in the user's namespace. | |
1971 |
|
1971 | |||
1972 | Parameters |
|
1972 | Parameters | |
1973 | ---------- |
|
1973 | ---------- | |
1974 | expressions : dict |
|
1974 | expressions : dict | |
1975 | A dict with string keys and string values. The expression values |
|
1975 | A dict with string keys and string values. The expression values | |
1976 | should be valid Python expressions, each of which will be evaluated |
|
1976 | should be valid Python expressions, each of which will be evaluated | |
1977 | in the user namespace. |
|
1977 | in the user namespace. | |
1978 |
|
1978 | |||
1979 | Returns |
|
1979 | Returns | |
1980 | ------- |
|
1980 | ------- | |
1981 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1981 | A dict, keyed like the input expressions dict, with the repr() of each | |
1982 | value. |
|
1982 | value. | |
1983 | """ |
|
1983 | """ | |
1984 | out = {} |
|
1984 | out = {} | |
1985 | user_ns = self.user_ns |
|
1985 | user_ns = self.user_ns | |
1986 | global_ns = self.user_global_ns |
|
1986 | global_ns = self.user_global_ns | |
1987 | for key, expr in expressions.iteritems(): |
|
1987 | for key, expr in expressions.iteritems(): | |
1988 | try: |
|
1988 | try: | |
1989 | value = repr(eval(expr, global_ns, user_ns)) |
|
1989 | value = repr(eval(expr, global_ns, user_ns)) | |
1990 | except: |
|
1990 | except: | |
1991 | value = self._simple_error() |
|
1991 | value = self._simple_error() | |
1992 | out[key] = value |
|
1992 | out[key] = value | |
1993 | return out |
|
1993 | return out | |
1994 |
|
1994 | |||
1995 | #------------------------------------------------------------------------- |
|
1995 | #------------------------------------------------------------------------- | |
1996 | # Things related to the running of code |
|
1996 | # Things related to the running of code | |
1997 | #------------------------------------------------------------------------- |
|
1997 | #------------------------------------------------------------------------- | |
1998 |
|
1998 | |||
1999 | def ex(self, cmd): |
|
1999 | def ex(self, cmd): | |
2000 | """Execute a normal python statement in user namespace.""" |
|
2000 | """Execute a normal python statement in user namespace.""" | |
2001 | with self.builtin_trap: |
|
2001 | with self.builtin_trap: | |
2002 | exec cmd in self.user_global_ns, self.user_ns |
|
2002 | exec cmd in self.user_global_ns, self.user_ns | |
2003 |
|
2003 | |||
2004 | def ev(self, expr): |
|
2004 | def ev(self, expr): | |
2005 | """Evaluate python expression expr in user namespace. |
|
2005 | """Evaluate python expression expr in user namespace. | |
2006 |
|
2006 | |||
2007 | Returns the result of evaluation |
|
2007 | Returns the result of evaluation | |
2008 | """ |
|
2008 | """ | |
2009 | with self.builtin_trap: |
|
2009 | with self.builtin_trap: | |
2010 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2010 | return eval(expr, self.user_global_ns, self.user_ns) | |
2011 |
|
2011 | |||
2012 | def safe_execfile(self, fname, *where, **kw): |
|
2012 | def safe_execfile(self, fname, *where, **kw): | |
2013 | """A safe version of the builtin execfile(). |
|
2013 | """A safe version of the builtin execfile(). | |
2014 |
|
2014 | |||
2015 | This version will never throw an exception, but instead print |
|
2015 | This version will never throw an exception, but instead print | |
2016 | helpful error messages to the screen. This only works on pure |
|
2016 | helpful error messages to the screen. This only works on pure | |
2017 | Python files with the .py extension. |
|
2017 | Python files with the .py extension. | |
2018 |
|
2018 | |||
2019 | Parameters |
|
2019 | Parameters | |
2020 | ---------- |
|
2020 | ---------- | |
2021 | fname : string |
|
2021 | fname : string | |
2022 | The name of the file to be executed. |
|
2022 | The name of the file to be executed. | |
2023 | where : tuple |
|
2023 | where : tuple | |
2024 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2024 | One or two namespaces, passed to execfile() as (globals,locals). | |
2025 | If only one is given, it is passed as both. |
|
2025 | If only one is given, it is passed as both. | |
2026 | exit_ignore : bool (False) |
|
2026 | exit_ignore : bool (False) | |
2027 | If True, then silence SystemExit for non-zero status (it is always |
|
2027 | If True, then silence SystemExit for non-zero status (it is always | |
2028 | silenced for zero status, as it is so common). |
|
2028 | silenced for zero status, as it is so common). | |
2029 | """ |
|
2029 | """ | |
2030 | kw.setdefault('exit_ignore', False) |
|
2030 | kw.setdefault('exit_ignore', False) | |
2031 |
|
2031 | |||
2032 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2032 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2033 | # Make sure we have a .py file |
|
2033 | # Make sure we have a .py file | |
2034 | if not fname.endswith('.py'): |
|
2034 | if not fname.endswith('.py'): | |
2035 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2035 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2036 |
|
2036 | |||
2037 | # Make sure we can open the file |
|
2037 | # Make sure we can open the file | |
2038 | try: |
|
2038 | try: | |
2039 | with open(fname) as thefile: |
|
2039 | with open(fname) as thefile: | |
2040 | pass |
|
2040 | pass | |
2041 | except: |
|
2041 | except: | |
2042 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2042 | warn('Could not open file <%s> for safe execution.' % fname) | |
2043 | return |
|
2043 | return | |
2044 |
|
2044 | |||
2045 | # Find things also in current directory. This is needed to mimic the |
|
2045 | # Find things also in current directory. This is needed to mimic the | |
2046 | # behavior of running a script from the system command line, where |
|
2046 | # behavior of running a script from the system command line, where | |
2047 | # Python inserts the script's directory into sys.path |
|
2047 | # Python inserts the script's directory into sys.path | |
2048 | dname = os.path.dirname(fname) |
|
2048 | dname = os.path.dirname(fname) | |
2049 |
|
2049 | |||
2050 | if isinstance(fname, unicode): |
|
2050 | if isinstance(fname, unicode): | |
2051 | # execfile uses default encoding instead of filesystem encoding |
|
2051 | # execfile uses default encoding instead of filesystem encoding | |
2052 | # so unicode filenames will fail |
|
2052 | # so unicode filenames will fail | |
2053 | fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding()) |
|
2053 | fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding()) | |
2054 |
|
2054 | |||
2055 | with prepended_to_syspath(dname): |
|
2055 | with prepended_to_syspath(dname): | |
2056 | try: |
|
2056 | try: | |
2057 | execfile(fname,*where) |
|
2057 | execfile(fname,*where) | |
2058 | except SystemExit, status: |
|
2058 | except SystemExit, status: | |
2059 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2059 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2060 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2060 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2061 | # these are considered normal by the OS: |
|
2061 | # these are considered normal by the OS: | |
2062 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2062 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2063 | # 0 |
|
2063 | # 0 | |
2064 | # > python -c'import sys;sys.exit()'; echo $? |
|
2064 | # > python -c'import sys;sys.exit()'; echo $? | |
2065 | # 0 |
|
2065 | # 0 | |
2066 | # For other exit status, we show the exception unless |
|
2066 | # For other exit status, we show the exception unless | |
2067 | # explicitly silenced, but only in short form. |
|
2067 | # explicitly silenced, but only in short form. | |
2068 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2068 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2069 | self.showtraceback(exception_only=True) |
|
2069 | self.showtraceback(exception_only=True) | |
2070 | except: |
|
2070 | except: | |
2071 | self.showtraceback() |
|
2071 | self.showtraceback() | |
2072 |
|
2072 | |||
2073 | def safe_execfile_ipy(self, fname): |
|
2073 | def safe_execfile_ipy(self, fname): | |
2074 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2074 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2075 |
|
2075 | |||
2076 | Parameters |
|
2076 | Parameters | |
2077 | ---------- |
|
2077 | ---------- | |
2078 | fname : str |
|
2078 | fname : str | |
2079 | The name of the file to execute. The filename must have a |
|
2079 | The name of the file to execute. The filename must have a | |
2080 | .ipy extension. |
|
2080 | .ipy extension. | |
2081 | """ |
|
2081 | """ | |
2082 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2082 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2083 |
|
2083 | |||
2084 | # Make sure we have a .py file |
|
2084 | # Make sure we have a .py file | |
2085 | if not fname.endswith('.ipy'): |
|
2085 | if not fname.endswith('.ipy'): | |
2086 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2086 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2087 |
|
2087 | |||
2088 | # Make sure we can open the file |
|
2088 | # Make sure we can open the file | |
2089 | try: |
|
2089 | try: | |
2090 | with open(fname) as thefile: |
|
2090 | with open(fname) as thefile: | |
2091 | pass |
|
2091 | pass | |
2092 | except: |
|
2092 | except: | |
2093 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2093 | warn('Could not open file <%s> for safe execution.' % fname) | |
2094 | return |
|
2094 | return | |
2095 |
|
2095 | |||
2096 | # Find things also in current directory. This is needed to mimic the |
|
2096 | # Find things also in current directory. This is needed to mimic the | |
2097 | # behavior of running a script from the system command line, where |
|
2097 | # behavior of running a script from the system command line, where | |
2098 | # Python inserts the script's directory into sys.path |
|
2098 | # Python inserts the script's directory into sys.path | |
2099 | dname = os.path.dirname(fname) |
|
2099 | dname = os.path.dirname(fname) | |
2100 |
|
2100 | |||
2101 | with prepended_to_syspath(dname): |
|
2101 | with prepended_to_syspath(dname): | |
2102 | try: |
|
2102 | try: | |
2103 | with open(fname) as thefile: |
|
2103 | with open(fname) as thefile: | |
2104 | # self.run_cell currently captures all exceptions |
|
2104 | # self.run_cell currently captures all exceptions | |
2105 | # raised in user code. It would be nice if there were |
|
2105 | # raised in user code. It would be nice if there were | |
2106 | # versions of runlines, execfile that did raise, so |
|
2106 | # versions of runlines, execfile that did raise, so | |
2107 | # we could catch the errors. |
|
2107 | # we could catch the errors. | |
2108 | self.run_cell(thefile.read(), store_history=False) |
|
2108 | self.run_cell(thefile.read(), store_history=False) | |
2109 | except: |
|
2109 | except: | |
2110 | self.showtraceback() |
|
2110 | self.showtraceback() | |
2111 | warn('Unknown failure executing file: <%s>' % fname) |
|
2111 | warn('Unknown failure executing file: <%s>' % fname) | |
2112 |
|
2112 | |||
2113 | def run_cell(self, raw_cell, store_history=True): |
|
2113 | def run_cell(self, raw_cell, store_history=True): | |
2114 | """Run a complete IPython cell. |
|
2114 | """Run a complete IPython cell. | |
2115 |
|
2115 | |||
2116 | Parameters |
|
2116 | Parameters | |
2117 | ---------- |
|
2117 | ---------- | |
2118 | raw_cell : str |
|
2118 | raw_cell : str | |
2119 | The code (including IPython code such as %magic functions) to run. |
|
2119 | The code (including IPython code such as %magic functions) to run. | |
2120 | store_history : bool |
|
2120 | store_history : bool | |
2121 | If True, the raw and translated cell will be stored in IPython's |
|
2121 | If True, the raw and translated cell will be stored in IPython's | |
2122 | history. For user code calling back into IPython's machinery, this |
|
2122 | history. For user code calling back into IPython's machinery, this | |
2123 | should be set to False. |
|
2123 | should be set to False. | |
2124 | """ |
|
2124 | """ | |
2125 | if (not raw_cell) or raw_cell.isspace(): |
|
2125 | if (not raw_cell) or raw_cell.isspace(): | |
2126 | return |
|
2126 | return | |
2127 |
|
2127 | |||
2128 | for line in raw_cell.splitlines(): |
|
2128 | for line in raw_cell.splitlines(): | |
2129 | self.input_splitter.push(line) |
|
2129 | self.input_splitter.push(line) | |
2130 | cell = self.input_splitter.source_reset() |
|
2130 | cell = self.input_splitter.source_reset() | |
2131 |
|
2131 | |||
2132 | with self.builtin_trap: |
|
2132 | with self.builtin_trap: | |
2133 | if len(cell.splitlines()) == 1: |
|
2133 | if len(cell.splitlines()) == 1: | |
2134 | cell = self.prefilter_manager.prefilter_lines(cell) |
|
2134 | cell = self.prefilter_manager.prefilter_lines(cell) | |
2135 |
|
2135 | |||
2136 | # Store raw and processed history |
|
2136 | # Store raw and processed history | |
2137 | if store_history: |
|
2137 | if store_history: | |
2138 | self.history_manager.store_inputs(self.execution_count, |
|
2138 | self.history_manager.store_inputs(self.execution_count, | |
2139 | cell, raw_cell) |
|
2139 | cell, raw_cell) | |
2140 |
|
2140 | |||
2141 | self.logger.log(cell, raw_cell) |
|
2141 | self.logger.log(cell, raw_cell) | |
2142 |
|
2142 | |||
2143 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2143 | cell_name = self.compile.cache(cell, self.execution_count) | |
2144 |
|
2144 | |||
2145 | with self.display_trap: |
|
2145 | with self.display_trap: | |
2146 | try: |
|
2146 | try: | |
2147 | code_ast = ast.parse(cell, filename=cell_name) |
|
2147 | code_ast = ast.parse(cell, filename=cell_name) | |
2148 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2148 | except (OverflowError, SyntaxError, ValueError, TypeError, | |
2149 | MemoryError): |
|
2149 | MemoryError): | |
2150 | self.showsyntaxerror() |
|
2150 | self.showsyntaxerror() | |
2151 | self.execution_count += 1 |
|
2151 | self.execution_count += 1 | |
2152 | return None |
|
2152 | return None | |
2153 |
|
||||
2154 | interactivity = 'last' # Last node to be run interactive |
|
|||
2155 | if len(cell.splitlines()) == 1: |
|
|||
2156 | interactivity = 'all' # Single line; run fully interactive |
|
|||
2157 |
|
2153 | |||
2158 |
self.run_ast_nodes(code_ast.body, cell_name, |
|
2154 | self.run_ast_nodes(code_ast.body, cell_name, | |
|
2155 | interactivity="last_expr") | |||
2159 |
|
2156 | |||
2160 | # Execute any registered post-execution functions. |
|
2157 | # Execute any registered post-execution functions. | |
2161 | for func, status in self._post_execute.iteritems(): |
|
2158 | for func, status in self._post_execute.iteritems(): | |
2162 | if not status: |
|
2159 | if not status: | |
2163 | continue |
|
2160 | continue | |
2164 | try: |
|
2161 | try: | |
2165 | func() |
|
2162 | func() | |
2166 | except: |
|
2163 | except: | |
2167 | self.showtraceback() |
|
2164 | self.showtraceback() | |
2168 | # Deactivate failing function |
|
2165 | # Deactivate failing function | |
2169 | self._post_execute[func] = False |
|
2166 | self._post_execute[func] = False | |
2170 |
|
2167 | |||
2171 | if store_history: |
|
2168 | if store_history: | |
2172 | # Write output to the database. Does nothing unless |
|
2169 | # Write output to the database. Does nothing unless | |
2173 | # history output logging is enabled. |
|
2170 | # history output logging is enabled. | |
2174 | self.history_manager.store_output(self.execution_count) |
|
2171 | self.history_manager.store_output(self.execution_count) | |
2175 | # Each cell is a *single* input, regardless of how many lines it has |
|
2172 | # Each cell is a *single* input, regardless of how many lines it has | |
2176 | self.execution_count += 1 |
|
2173 | self.execution_count += 1 | |
2177 |
|
2174 | |||
2178 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last'): |
|
2175 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): | |
2179 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2176 | """Run a sequence of AST nodes. The execution mode depends on the | |
2180 | interactivity parameter. |
|
2177 | interactivity parameter. | |
2181 |
|
2178 | |||
2182 | Parameters |
|
2179 | Parameters | |
2183 | ---------- |
|
2180 | ---------- | |
2184 | nodelist : list |
|
2181 | nodelist : list | |
2185 | A sequence of AST nodes to run. |
|
2182 | A sequence of AST nodes to run. | |
2186 | cell_name : str |
|
2183 | cell_name : str | |
2187 | Will be passed to the compiler as the filename of the cell. Typically |
|
2184 | Will be passed to the compiler as the filename of the cell. Typically | |
2188 | the value returned by ip.compile.cache(cell). |
|
2185 | the value returned by ip.compile.cache(cell). | |
2189 | interactivity : str |
|
2186 | interactivity : str | |
2190 |
'all', 'last' or 'none', specifying which nodes should be |
|
2187 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
2191 |
interactively (displaying output from expressions). |
|
2188 | run interactively (displaying output from expressions). 'last_expr' | |
2192 | this parameter will raise a ValueError. |
|
2189 | will run the last node interactively only if it is an expression (i.e. | |
|
2190 | expressions in loops or other blocks are not displayed. Other values | |||
|
2191 | for this parameter will raise a ValueError. | |||
2193 | """ |
|
2192 | """ | |
2194 | if not nodelist: |
|
2193 | if not nodelist: | |
2195 | return |
|
2194 | return | |
2196 |
|
2195 | |||
|
2196 | if interactivity == 'last_expr': | |||
|
2197 | if isinstance(nodelist[-1], ast.Expr): | |||
|
2198 | interactivity = "last" | |||
|
2199 | else: | |||
|
2200 | interactivity = "none" | |||
|
2201 | ||||
2197 | if interactivity == 'none': |
|
2202 | if interactivity == 'none': | |
2198 | to_run_exec, to_run_interactive = nodelist, [] |
|
2203 | to_run_exec, to_run_interactive = nodelist, [] | |
2199 | elif interactivity == 'last': |
|
2204 | elif interactivity == 'last': | |
2200 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2205 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2201 | elif interactivity == 'all': |
|
2206 | elif interactivity == 'all': | |
2202 | to_run_exec, to_run_interactive = [], nodelist |
|
2207 | to_run_exec, to_run_interactive = [], nodelist | |
2203 | else: |
|
2208 | else: | |
2204 | raise ValueError("Interactivity was %r" % interactivity) |
|
2209 | raise ValueError("Interactivity was %r" % interactivity) | |
2205 |
|
2210 | |||
2206 | exec_count = self.execution_count |
|
2211 | exec_count = self.execution_count | |
2207 |
|
2212 | |||
2208 | for i, node in enumerate(to_run_exec): |
|
2213 | for i, node in enumerate(to_run_exec): | |
2209 | mod = ast.Module([node]) |
|
2214 | mod = ast.Module([node]) | |
2210 | code = self.compile(mod, cell_name, "exec") |
|
2215 | code = self.compile(mod, cell_name, "exec") | |
2211 | if self.run_code(code): |
|
2216 | if self.run_code(code): | |
2212 | return True |
|
2217 | return True | |
2213 |
|
2218 | |||
2214 | for i, node in enumerate(to_run_interactive): |
|
2219 | for i, node in enumerate(to_run_interactive): | |
2215 | mod = ast.Interactive([node]) |
|
2220 | mod = ast.Interactive([node]) | |
2216 | code = self.compile(mod, cell_name, "single") |
|
2221 | code = self.compile(mod, cell_name, "single") | |
2217 | if self.run_code(code): |
|
2222 | if self.run_code(code): | |
2218 | return True |
|
2223 | return True | |
2219 |
|
2224 | |||
2220 | return False |
|
2225 | return False | |
2221 |
|
2226 | |||
2222 |
|
2227 | |||
2223 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2228 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2224 | # input logic has been 100% moved to frontends and is stable. |
|
2229 | # input logic has been 100% moved to frontends and is stable. | |
2225 | def runlines(self, lines, clean=False): |
|
2230 | def runlines(self, lines, clean=False): | |
2226 | """Run a string of one or more lines of source. |
|
2231 | """Run a string of one or more lines of source. | |
2227 |
|
2232 | |||
2228 | This method is capable of running a string containing multiple source |
|
2233 | This method is capable of running a string containing multiple source | |
2229 | lines, as if they had been entered at the IPython prompt. Since it |
|
2234 | lines, as if they had been entered at the IPython prompt. Since it | |
2230 | exposes IPython's processing machinery, the given strings can contain |
|
2235 | exposes IPython's processing machinery, the given strings can contain | |
2231 | magic calls (%magic), special shell access (!cmd), etc. |
|
2236 | magic calls (%magic), special shell access (!cmd), etc. | |
2232 | """ |
|
2237 | """ | |
2233 |
|
2238 | |||
2234 | if not isinstance(lines, (list, tuple)): |
|
2239 | if not isinstance(lines, (list, tuple)): | |
2235 | lines = lines.splitlines() |
|
2240 | lines = lines.splitlines() | |
2236 |
|
2241 | |||
2237 | if clean: |
|
2242 | if clean: | |
2238 | lines = self._cleanup_ipy_script(lines) |
|
2243 | lines = self._cleanup_ipy_script(lines) | |
2239 |
|
2244 | |||
2240 | # We must start with a clean buffer, in case this is run from an |
|
2245 | # We must start with a clean buffer, in case this is run from an | |
2241 | # interactive IPython session (via a magic, for example). |
|
2246 | # interactive IPython session (via a magic, for example). | |
2242 | self.reset_buffer() |
|
2247 | self.reset_buffer() | |
2243 |
|
2248 | |||
2244 | # Since we will prefilter all lines, store the user's raw input too |
|
2249 | # Since we will prefilter all lines, store the user's raw input too | |
2245 | # before we apply any transformations |
|
2250 | # before we apply any transformations | |
2246 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2251 | self.buffer_raw[:] = [ l+'\n' for l in lines] | |
2247 |
|
2252 | |||
2248 | more = False |
|
2253 | more = False | |
2249 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2254 | prefilter_lines = self.prefilter_manager.prefilter_lines | |
2250 | with nested(self.builtin_trap, self.display_trap): |
|
2255 | with nested(self.builtin_trap, self.display_trap): | |
2251 | for line in lines: |
|
2256 | for line in lines: | |
2252 | # skip blank lines so we don't mess up the prompt counter, but |
|
2257 | # skip blank lines so we don't mess up the prompt counter, but | |
2253 | # do NOT skip even a blank line if we are in a code block (more |
|
2258 | # do NOT skip even a blank line if we are in a code block (more | |
2254 | # is true) |
|
2259 | # is true) | |
2255 |
|
2260 | |||
2256 | if line or more: |
|
2261 | if line or more: | |
2257 | more = self.push_line(prefilter_lines(line, more)) |
|
2262 | more = self.push_line(prefilter_lines(line, more)) | |
2258 | # IPython's run_source returns None if there was an error |
|
2263 | # IPython's run_source returns None if there was an error | |
2259 | # compiling the code. This allows us to stop processing |
|
2264 | # compiling the code. This allows us to stop processing | |
2260 | # right away, so the user gets the error message at the |
|
2265 | # right away, so the user gets the error message at the | |
2261 | # right place. |
|
2266 | # right place. | |
2262 | if more is None: |
|
2267 | if more is None: | |
2263 | break |
|
2268 | break | |
2264 | # final newline in case the input didn't have it, so that the code |
|
2269 | # final newline in case the input didn't have it, so that the code | |
2265 | # actually does get executed |
|
2270 | # actually does get executed | |
2266 | if more: |
|
2271 | if more: | |
2267 | self.push_line('\n') |
|
2272 | self.push_line('\n') | |
2268 |
|
2273 | |||
2269 | def run_source(self, source, filename=None, symbol='single'): |
|
2274 | def run_source(self, source, filename=None, symbol='single'): | |
2270 | """Compile and run some source in the interpreter. |
|
2275 | """Compile and run some source in the interpreter. | |
2271 |
|
2276 | |||
2272 | Arguments are as for compile_command(). |
|
2277 | Arguments are as for compile_command(). | |
2273 |
|
2278 | |||
2274 | One several things can happen: |
|
2279 | One several things can happen: | |
2275 |
|
2280 | |||
2276 | 1) The input is incorrect; compile_command() raised an |
|
2281 | 1) The input is incorrect; compile_command() raised an | |
2277 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2282 | exception (SyntaxError or OverflowError). A syntax traceback | |
2278 | will be printed by calling the showsyntaxerror() method. |
|
2283 | will be printed by calling the showsyntaxerror() method. | |
2279 |
|
2284 | |||
2280 | 2) The input is incomplete, and more input is required; |
|
2285 | 2) The input is incomplete, and more input is required; | |
2281 | compile_command() returned None. Nothing happens. |
|
2286 | compile_command() returned None. Nothing happens. | |
2282 |
|
2287 | |||
2283 | 3) The input is complete; compile_command() returned a code |
|
2288 | 3) The input is complete; compile_command() returned a code | |
2284 | object. The code is executed by calling self.run_code() (which |
|
2289 | object. The code is executed by calling self.run_code() (which | |
2285 | also handles run-time exceptions, except for SystemExit). |
|
2290 | also handles run-time exceptions, except for SystemExit). | |
2286 |
|
2291 | |||
2287 | The return value is: |
|
2292 | The return value is: | |
2288 |
|
2293 | |||
2289 | - True in case 2 |
|
2294 | - True in case 2 | |
2290 |
|
2295 | |||
2291 | - False in the other cases, unless an exception is raised, where |
|
2296 | - False in the other cases, unless an exception is raised, where | |
2292 | None is returned instead. This can be used by external callers to |
|
2297 | None is returned instead. This can be used by external callers to | |
2293 | know whether to continue feeding input or not. |
|
2298 | know whether to continue feeding input or not. | |
2294 |
|
2299 | |||
2295 | The return value can be used to decide whether to use sys.ps1 or |
|
2300 | The return value can be used to decide whether to use sys.ps1 or | |
2296 | sys.ps2 to prompt the next line.""" |
|
2301 | sys.ps2 to prompt the next line.""" | |
2297 |
|
2302 | |||
2298 | # We need to ensure that the source is unicode from here on. |
|
2303 | # We need to ensure that the source is unicode from here on. | |
2299 | if type(source)==str: |
|
2304 | if type(source)==str: | |
2300 | usource = source.decode(self.stdin_encoding) |
|
2305 | usource = source.decode(self.stdin_encoding) | |
2301 | else: |
|
2306 | else: | |
2302 | usource = source |
|
2307 | usource = source | |
2303 |
|
2308 | |||
2304 | try: |
|
2309 | try: | |
2305 | code_name = self.compile.cache(usource, self.execution_count) |
|
2310 | code_name = self.compile.cache(usource, self.execution_count) | |
2306 | code = self.compile(usource, code_name, symbol) |
|
2311 | code = self.compile(usource, code_name, symbol) | |
2307 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2312 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2308 | # Case 1 |
|
2313 | # Case 1 | |
2309 | self.showsyntaxerror(filename) |
|
2314 | self.showsyntaxerror(filename) | |
2310 | return None |
|
2315 | return None | |
2311 |
|
2316 | |||
2312 | if code is None: |
|
2317 | if code is None: | |
2313 | # Case 2 |
|
2318 | # Case 2 | |
2314 | return True |
|
2319 | return True | |
2315 |
|
2320 | |||
2316 | # Case 3 |
|
2321 | # Case 3 | |
2317 | # now actually execute the code object |
|
2322 | # now actually execute the code object | |
2318 | if not self.run_code(code): |
|
2323 | if not self.run_code(code): | |
2319 | return False |
|
2324 | return False | |
2320 | else: |
|
2325 | else: | |
2321 | return None |
|
2326 | return None | |
2322 |
|
2327 | |||
2323 | # For backwards compatibility |
|
2328 | # For backwards compatibility | |
2324 | runsource = run_source |
|
2329 | runsource = run_source | |
2325 |
|
2330 | |||
2326 | def run_code(self, code_obj): |
|
2331 | def run_code(self, code_obj): | |
2327 | """Execute a code object. |
|
2332 | """Execute a code object. | |
2328 |
|
2333 | |||
2329 | When an exception occurs, self.showtraceback() is called to display a |
|
2334 | When an exception occurs, self.showtraceback() is called to display a | |
2330 | traceback. |
|
2335 | traceback. | |
2331 |
|
2336 | |||
2332 | Parameters |
|
2337 | Parameters | |
2333 | ---------- |
|
2338 | ---------- | |
2334 | code_obj : code object |
|
2339 | code_obj : code object | |
2335 | A compiled code object, to be executed |
|
2340 | A compiled code object, to be executed | |
2336 | post_execute : bool [default: True] |
|
2341 | post_execute : bool [default: True] | |
2337 | whether to call post_execute hooks after this particular execution. |
|
2342 | whether to call post_execute hooks after this particular execution. | |
2338 |
|
2343 | |||
2339 | Returns |
|
2344 | Returns | |
2340 | ------- |
|
2345 | ------- | |
2341 | False : successful execution. |
|
2346 | False : successful execution. | |
2342 | True : an error occurred. |
|
2347 | True : an error occurred. | |
2343 | """ |
|
2348 | """ | |
2344 |
|
2349 | |||
2345 | # Set our own excepthook in case the user code tries to call it |
|
2350 | # Set our own excepthook in case the user code tries to call it | |
2346 | # directly, so that the IPython crash handler doesn't get triggered |
|
2351 | # directly, so that the IPython crash handler doesn't get triggered | |
2347 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2352 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2348 |
|
2353 | |||
2349 | # we save the original sys.excepthook in the instance, in case config |
|
2354 | # we save the original sys.excepthook in the instance, in case config | |
2350 | # code (such as magics) needs access to it. |
|
2355 | # code (such as magics) needs access to it. | |
2351 | self.sys_excepthook = old_excepthook |
|
2356 | self.sys_excepthook = old_excepthook | |
2352 | outflag = 1 # happens in more places, so it's easier as default |
|
2357 | outflag = 1 # happens in more places, so it's easier as default | |
2353 | try: |
|
2358 | try: | |
2354 | try: |
|
2359 | try: | |
2355 | self.hooks.pre_run_code_hook() |
|
2360 | self.hooks.pre_run_code_hook() | |
2356 | #rprint('Running code', repr(code_obj)) # dbg |
|
2361 | #rprint('Running code', repr(code_obj)) # dbg | |
2357 | exec code_obj in self.user_global_ns, self.user_ns |
|
2362 | exec code_obj in self.user_global_ns, self.user_ns | |
2358 | finally: |
|
2363 | finally: | |
2359 | # Reset our crash handler in place |
|
2364 | # Reset our crash handler in place | |
2360 | sys.excepthook = old_excepthook |
|
2365 | sys.excepthook = old_excepthook | |
2361 | except SystemExit: |
|
2366 | except SystemExit: | |
2362 | self.reset_buffer() |
|
2367 | self.reset_buffer() | |
2363 | self.showtraceback(exception_only=True) |
|
2368 | self.showtraceback(exception_only=True) | |
2364 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2369 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2365 | except self.custom_exceptions: |
|
2370 | except self.custom_exceptions: | |
2366 | etype,value,tb = sys.exc_info() |
|
2371 | etype,value,tb = sys.exc_info() | |
2367 | self.CustomTB(etype,value,tb) |
|
2372 | self.CustomTB(etype,value,tb) | |
2368 | except: |
|
2373 | except: | |
2369 | self.showtraceback() |
|
2374 | self.showtraceback() | |
2370 | else: |
|
2375 | else: | |
2371 | outflag = 0 |
|
2376 | outflag = 0 | |
2372 | if softspace(sys.stdout, 0): |
|
2377 | if softspace(sys.stdout, 0): | |
2373 |
|
2378 | |||
2374 |
|
2379 | |||
2375 | return outflag |
|
2380 | return outflag | |
2376 |
|
2381 | |||
2377 | # For backwards compatibility |
|
2382 | # For backwards compatibility | |
2378 | runcode = run_code |
|
2383 | runcode = run_code | |
2379 |
|
2384 | |||
2380 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2385 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2381 | # input logic has been 100% moved to frontends and is stable. |
|
2386 | # input logic has been 100% moved to frontends and is stable. | |
2382 | def push_line(self, line): |
|
2387 | def push_line(self, line): | |
2383 | """Push a line to the interpreter. |
|
2388 | """Push a line to the interpreter. | |
2384 |
|
2389 | |||
2385 | The line should not have a trailing newline; it may have |
|
2390 | The line should not have a trailing newline; it may have | |
2386 | internal newlines. The line is appended to a buffer and the |
|
2391 | internal newlines. The line is appended to a buffer and the | |
2387 | interpreter's run_source() method is called with the |
|
2392 | interpreter's run_source() method is called with the | |
2388 | concatenated contents of the buffer as source. If this |
|
2393 | concatenated contents of the buffer as source. If this | |
2389 | indicates that the command was executed or invalid, the buffer |
|
2394 | indicates that the command was executed or invalid, the buffer | |
2390 | is reset; otherwise, the command is incomplete, and the buffer |
|
2395 | is reset; otherwise, the command is incomplete, and the buffer | |
2391 | is left as it was after the line was appended. The return |
|
2396 | is left as it was after the line was appended. The return | |
2392 | value is 1 if more input is required, 0 if the line was dealt |
|
2397 | value is 1 if more input is required, 0 if the line was dealt | |
2393 | with in some way (this is the same as run_source()). |
|
2398 | with in some way (this is the same as run_source()). | |
2394 | """ |
|
2399 | """ | |
2395 |
|
2400 | |||
2396 | # autoindent management should be done here, and not in the |
|
2401 | # autoindent management should be done here, and not in the | |
2397 | # interactive loop, since that one is only seen by keyboard input. We |
|
2402 | # interactive loop, since that one is only seen by keyboard input. We | |
2398 | # need this done correctly even for code run via runlines (which uses |
|
2403 | # need this done correctly even for code run via runlines (which uses | |
2399 | # push). |
|
2404 | # push). | |
2400 |
|
2405 | |||
2401 | #print 'push line: <%s>' % line # dbg |
|
2406 | #print 'push line: <%s>' % line # dbg | |
2402 | self.buffer.append(line) |
|
2407 | self.buffer.append(line) | |
2403 | full_source = '\n'.join(self.buffer) |
|
2408 | full_source = '\n'.join(self.buffer) | |
2404 | more = self.run_source(full_source, self.filename) |
|
2409 | more = self.run_source(full_source, self.filename) | |
2405 | if not more: |
|
2410 | if not more: | |
2406 | self.history_manager.store_inputs(self.execution_count, |
|
2411 | self.history_manager.store_inputs(self.execution_count, | |
2407 | '\n'.join(self.buffer_raw), full_source) |
|
2412 | '\n'.join(self.buffer_raw), full_source) | |
2408 | self.reset_buffer() |
|
2413 | self.reset_buffer() | |
2409 | self.execution_count += 1 |
|
2414 | self.execution_count += 1 | |
2410 | return more |
|
2415 | return more | |
2411 |
|
2416 | |||
2412 | def reset_buffer(self): |
|
2417 | def reset_buffer(self): | |
2413 | """Reset the input buffer.""" |
|
2418 | """Reset the input buffer.""" | |
2414 | self.buffer[:] = [] |
|
2419 | self.buffer[:] = [] | |
2415 | self.buffer_raw[:] = [] |
|
2420 | self.buffer_raw[:] = [] | |
2416 | self.input_splitter.reset() |
|
2421 | self.input_splitter.reset() | |
2417 |
|
2422 | |||
2418 | # For backwards compatibility |
|
2423 | # For backwards compatibility | |
2419 | resetbuffer = reset_buffer |
|
2424 | resetbuffer = reset_buffer | |
2420 |
|
2425 | |||
2421 | def _is_secondary_block_start(self, s): |
|
2426 | def _is_secondary_block_start(self, s): | |
2422 | if not s.endswith(':'): |
|
2427 | if not s.endswith(':'): | |
2423 | return False |
|
2428 | return False | |
2424 | if (s.startswith('elif') or |
|
2429 | if (s.startswith('elif') or | |
2425 | s.startswith('else') or |
|
2430 | s.startswith('else') or | |
2426 | s.startswith('except') or |
|
2431 | s.startswith('except') or | |
2427 | s.startswith('finally')): |
|
2432 | s.startswith('finally')): | |
2428 | return True |
|
2433 | return True | |
2429 |
|
2434 | |||
2430 | def _cleanup_ipy_script(self, script): |
|
2435 | def _cleanup_ipy_script(self, script): | |
2431 | """Make a script safe for self.runlines() |
|
2436 | """Make a script safe for self.runlines() | |
2432 |
|
2437 | |||
2433 | Currently, IPython is lines based, with blocks being detected by |
|
2438 | Currently, IPython is lines based, with blocks being detected by | |
2434 | empty lines. This is a problem for block based scripts that may |
|
2439 | empty lines. This is a problem for block based scripts that may | |
2435 | not have empty lines after blocks. This script adds those empty |
|
2440 | not have empty lines after blocks. This script adds those empty | |
2436 | lines to make scripts safe for running in the current line based |
|
2441 | lines to make scripts safe for running in the current line based | |
2437 | IPython. |
|
2442 | IPython. | |
2438 | """ |
|
2443 | """ | |
2439 | res = [] |
|
2444 | res = [] | |
2440 | lines = script.splitlines() |
|
2445 | lines = script.splitlines() | |
2441 | level = 0 |
|
2446 | level = 0 | |
2442 |
|
2447 | |||
2443 | for l in lines: |
|
2448 | for l in lines: | |
2444 | lstripped = l.lstrip() |
|
2449 | lstripped = l.lstrip() | |
2445 | stripped = l.strip() |
|
2450 | stripped = l.strip() | |
2446 | if not stripped: |
|
2451 | if not stripped: | |
2447 | continue |
|
2452 | continue | |
2448 | newlevel = len(l) - len(lstripped) |
|
2453 | newlevel = len(l) - len(lstripped) | |
2449 | if level > 0 and newlevel == 0 and \ |
|
2454 | if level > 0 and newlevel == 0 and \ | |
2450 | not self._is_secondary_block_start(stripped): |
|
2455 | not self._is_secondary_block_start(stripped): | |
2451 | # add empty line |
|
2456 | # add empty line | |
2452 | res.append('') |
|
2457 | res.append('') | |
2453 | res.append(l) |
|
2458 | res.append(l) | |
2454 | level = newlevel |
|
2459 | level = newlevel | |
2455 |
|
2460 | |||
2456 | return '\n'.join(res) + '\n' |
|
2461 | return '\n'.join(res) + '\n' | |
2457 |
|
2462 | |||
2458 | #------------------------------------------------------------------------- |
|
2463 | #------------------------------------------------------------------------- | |
2459 | # Things related to GUI support and pylab |
|
2464 | # Things related to GUI support and pylab | |
2460 | #------------------------------------------------------------------------- |
|
2465 | #------------------------------------------------------------------------- | |
2461 |
|
2466 | |||
2462 | def enable_pylab(self, gui=None): |
|
2467 | def enable_pylab(self, gui=None): | |
2463 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2468 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2464 |
|
2469 | |||
2465 | #------------------------------------------------------------------------- |
|
2470 | #------------------------------------------------------------------------- | |
2466 | # Utilities |
|
2471 | # Utilities | |
2467 | #------------------------------------------------------------------------- |
|
2472 | #------------------------------------------------------------------------- | |
2468 |
|
2473 | |||
2469 | def var_expand(self,cmd,depth=0): |
|
2474 | def var_expand(self,cmd,depth=0): | |
2470 | """Expand python variables in a string. |
|
2475 | """Expand python variables in a string. | |
2471 |
|
2476 | |||
2472 | The depth argument indicates how many frames above the caller should |
|
2477 | The depth argument indicates how many frames above the caller should | |
2473 | be walked to look for the local namespace where to expand variables. |
|
2478 | be walked to look for the local namespace where to expand variables. | |
2474 |
|
2479 | |||
2475 | The global namespace for expansion is always the user's interactive |
|
2480 | The global namespace for expansion is always the user's interactive | |
2476 | namespace. |
|
2481 | namespace. | |
2477 | """ |
|
2482 | """ | |
2478 | res = ItplNS(cmd, self.user_ns, # globals |
|
2483 | res = ItplNS(cmd, self.user_ns, # globals | |
2479 | # Skip our own frame in searching for locals: |
|
2484 | # Skip our own frame in searching for locals: | |
2480 | sys._getframe(depth+1).f_locals # locals |
|
2485 | sys._getframe(depth+1).f_locals # locals | |
2481 | ) |
|
2486 | ) | |
2482 | return str(res).decode(res.codec) |
|
2487 | return str(res).decode(res.codec) | |
2483 |
|
2488 | |||
2484 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2489 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2485 | """Make a new tempfile and return its filename. |
|
2490 | """Make a new tempfile and return its filename. | |
2486 |
|
2491 | |||
2487 | This makes a call to tempfile.mktemp, but it registers the created |
|
2492 | This makes a call to tempfile.mktemp, but it registers the created | |
2488 | filename internally so ipython cleans it up at exit time. |
|
2493 | filename internally so ipython cleans it up at exit time. | |
2489 |
|
2494 | |||
2490 | Optional inputs: |
|
2495 | Optional inputs: | |
2491 |
|
2496 | |||
2492 | - data(None): if data is given, it gets written out to the temp file |
|
2497 | - data(None): if data is given, it gets written out to the temp file | |
2493 | immediately, and the file is closed again.""" |
|
2498 | immediately, and the file is closed again.""" | |
2494 |
|
2499 | |||
2495 | filename = tempfile.mktemp('.py', prefix) |
|
2500 | filename = tempfile.mktemp('.py', prefix) | |
2496 | self.tempfiles.append(filename) |
|
2501 | self.tempfiles.append(filename) | |
2497 |
|
2502 | |||
2498 | if data: |
|
2503 | if data: | |
2499 | tmp_file = open(filename,'w') |
|
2504 | tmp_file = open(filename,'w') | |
2500 | tmp_file.write(data) |
|
2505 | tmp_file.write(data) | |
2501 | tmp_file.close() |
|
2506 | tmp_file.close() | |
2502 | return filename |
|
2507 | return filename | |
2503 |
|
2508 | |||
2504 | # TODO: This should be removed when Term is refactored. |
|
2509 | # TODO: This should be removed when Term is refactored. | |
2505 | def write(self,data): |
|
2510 | def write(self,data): | |
2506 | """Write a string to the default output""" |
|
2511 | """Write a string to the default output""" | |
2507 | io.Term.cout.write(data) |
|
2512 | io.Term.cout.write(data) | |
2508 |
|
2513 | |||
2509 | # TODO: This should be removed when Term is refactored. |
|
2514 | # TODO: This should be removed when Term is refactored. | |
2510 | def write_err(self,data): |
|
2515 | def write_err(self,data): | |
2511 | """Write a string to the default error output""" |
|
2516 | """Write a string to the default error output""" | |
2512 | io.Term.cerr.write(data) |
|
2517 | io.Term.cerr.write(data) | |
2513 |
|
2518 | |||
2514 | def ask_yes_no(self,prompt,default=True): |
|
2519 | def ask_yes_no(self,prompt,default=True): | |
2515 | if self.quiet: |
|
2520 | if self.quiet: | |
2516 | return True |
|
2521 | return True | |
2517 | return ask_yes_no(prompt,default) |
|
2522 | return ask_yes_no(prompt,default) | |
2518 |
|
2523 | |||
2519 | def show_usage(self): |
|
2524 | def show_usage(self): | |
2520 | """Show a usage message""" |
|
2525 | """Show a usage message""" | |
2521 | page.page(IPython.core.usage.interactive_usage) |
|
2526 | page.page(IPython.core.usage.interactive_usage) | |
2522 |
|
2527 | |||
2523 | def find_user_code(self, target, raw=True): |
|
2528 | def find_user_code(self, target, raw=True): | |
2524 | """Get a code string from history, file, or a string or macro. |
|
2529 | """Get a code string from history, file, or a string or macro. | |
2525 |
|
2530 | |||
2526 | This is mainly used by magic functions. |
|
2531 | This is mainly used by magic functions. | |
2527 |
|
2532 | |||
2528 | Parameters |
|
2533 | Parameters | |
2529 | ---------- |
|
2534 | ---------- | |
2530 | target : str |
|
2535 | target : str | |
2531 | A string specifying code to retrieve. This will be tried respectively |
|
2536 | A string specifying code to retrieve. This will be tried respectively | |
2532 | as: ranges of input history (see %history for syntax), a filename, or |
|
2537 | as: ranges of input history (see %history for syntax), a filename, or | |
2533 | an expression evaluating to a string or Macro in the user namespace. |
|
2538 | an expression evaluating to a string or Macro in the user namespace. | |
2534 | raw : bool |
|
2539 | raw : bool | |
2535 | If true (default), retrieve raw history. Has no effect on the other |
|
2540 | If true (default), retrieve raw history. Has no effect on the other | |
2536 | retrieval mechanisms. |
|
2541 | retrieval mechanisms. | |
2537 |
|
2542 | |||
2538 | Returns |
|
2543 | Returns | |
2539 | ------- |
|
2544 | ------- | |
2540 | A string of code. |
|
2545 | A string of code. | |
2541 |
|
2546 | |||
2542 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2547 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
2543 | to an object of another type. In each case, .args[0] is a printable |
|
2548 | to an object of another type. In each case, .args[0] is a printable | |
2544 | message. |
|
2549 | message. | |
2545 | """ |
|
2550 | """ | |
2546 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2551 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
2547 | if code: |
|
2552 | if code: | |
2548 | return code |
|
2553 | return code | |
2549 | if os.path.isfile(target): # Read file |
|
2554 | if os.path.isfile(target): # Read file | |
2550 | return open(target, "r").read() |
|
2555 | return open(target, "r").read() | |
2551 |
|
2556 | |||
2552 | try: # User namespace |
|
2557 | try: # User namespace | |
2553 | codeobj = eval(target, self.user_ns) |
|
2558 | codeobj = eval(target, self.user_ns) | |
2554 | except Exception: |
|
2559 | except Exception: | |
2555 | raise ValueError(("'%s' was not found in history, as a file, nor in" |
|
2560 | raise ValueError(("'%s' was not found in history, as a file, nor in" | |
2556 | " the user namespace.") % target) |
|
2561 | " the user namespace.") % target) | |
2557 | if isinstance(codeobj, basestring): |
|
2562 | if isinstance(codeobj, basestring): | |
2558 | return codeobj |
|
2563 | return codeobj | |
2559 | elif isinstance(codeobj, Macro): |
|
2564 | elif isinstance(codeobj, Macro): | |
2560 | return codeobj.value |
|
2565 | return codeobj.value | |
2561 |
|
2566 | |||
2562 | raise TypeError("%s is neither a string nor a macro." % target, |
|
2567 | raise TypeError("%s is neither a string nor a macro." % target, | |
2563 | codeobj) |
|
2568 | codeobj) | |
2564 |
|
2569 | |||
2565 | #------------------------------------------------------------------------- |
|
2570 | #------------------------------------------------------------------------- | |
2566 | # Things related to IPython exiting |
|
2571 | # Things related to IPython exiting | |
2567 | #------------------------------------------------------------------------- |
|
2572 | #------------------------------------------------------------------------- | |
2568 | def atexit_operations(self): |
|
2573 | def atexit_operations(self): | |
2569 | """This will be executed at the time of exit. |
|
2574 | """This will be executed at the time of exit. | |
2570 |
|
2575 | |||
2571 | Cleanup operations and saving of persistent data that is done |
|
2576 | Cleanup operations and saving of persistent data that is done | |
2572 | unconditionally by IPython should be performed here. |
|
2577 | unconditionally by IPython should be performed here. | |
2573 |
|
2578 | |||
2574 | For things that may depend on startup flags or platform specifics (such |
|
2579 | For things that may depend on startup flags or platform specifics (such | |
2575 | as having readline or not), register a separate atexit function in the |
|
2580 | as having readline or not), register a separate atexit function in the | |
2576 | code that has the appropriate information, rather than trying to |
|
2581 | code that has the appropriate information, rather than trying to | |
2577 | clutter |
|
2582 | clutter | |
2578 | """ |
|
2583 | """ | |
2579 | # Cleanup all tempfiles left around |
|
2584 | # Cleanup all tempfiles left around | |
2580 | for tfile in self.tempfiles: |
|
2585 | for tfile in self.tempfiles: | |
2581 | try: |
|
2586 | try: | |
2582 | os.unlink(tfile) |
|
2587 | os.unlink(tfile) | |
2583 | except OSError: |
|
2588 | except OSError: | |
2584 | pass |
|
2589 | pass | |
2585 |
|
2590 | |||
2586 | # Close the history session (this stores the end time and line count) |
|
2591 | # Close the history session (this stores the end time and line count) | |
2587 | self.history_manager.end_session() |
|
2592 | self.history_manager.end_session() | |
2588 |
|
2593 | |||
2589 | # Clear all user namespaces to release all references cleanly. |
|
2594 | # Clear all user namespaces to release all references cleanly. | |
2590 | self.reset(new_session=False) |
|
2595 | self.reset(new_session=False) | |
2591 |
|
2596 | |||
2592 | # Run user hooks |
|
2597 | # Run user hooks | |
2593 | self.hooks.shutdown_hook() |
|
2598 | self.hooks.shutdown_hook() | |
2594 |
|
2599 | |||
2595 | def cleanup(self): |
|
2600 | def cleanup(self): | |
2596 | self.restore_sys_module_state() |
|
2601 | self.restore_sys_module_state() | |
2597 |
|
2602 | |||
2598 |
|
2603 | |||
2599 | class InteractiveShellABC(object): |
|
2604 | class InteractiveShellABC(object): | |
2600 | """An abstract base class for InteractiveShell.""" |
|
2605 | """An abstract base class for InteractiveShell.""" | |
2601 | __metaclass__ = abc.ABCMeta |
|
2606 | __metaclass__ = abc.ABCMeta | |
2602 |
|
2607 | |||
2603 | InteractiveShellABC.register(InteractiveShell) |
|
2608 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,109 +1,109 b'' | |||||
1 | # coding: utf-8 |
|
1 | # coding: utf-8 | |
2 | """Tests for the IPython tab-completion machinery. |
|
2 | """Tests for the IPython tab-completion machinery. | |
3 | """ |
|
3 | """ | |
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Module imports |
|
5 | # Module imports | |
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 |
|
7 | |||
8 | # stdlib |
|
8 | # stdlib | |
9 | import os |
|
9 | import os | |
10 | import sys |
|
10 | import sys | |
11 | import unittest |
|
11 | import unittest | |
12 |
|
12 | |||
13 | # third party |
|
13 | # third party | |
14 | import nose.tools as nt |
|
14 | import nose.tools as nt | |
15 |
|
15 | |||
16 | # our own packages |
|
16 | # our own packages | |
17 | from IPython.utils.tempdir import TemporaryDirectory |
|
17 | from IPython.utils.tempdir import TemporaryDirectory | |
18 | from IPython.core.history import HistoryManager, extract_hist_ranges |
|
18 | from IPython.core.history import HistoryManager, extract_hist_ranges | |
19 |
|
19 | |||
20 | def setUp(): |
|
20 | def setUp(): | |
21 | nt.assert_equal(sys.getdefaultencoding(), "ascii") |
|
21 | nt.assert_equal(sys.getdefaultencoding(), "ascii") | |
22 |
|
22 | |||
23 | def test_history(): |
|
23 | def test_history(): | |
24 | ip = get_ipython() |
|
24 | ip = get_ipython() | |
25 | with TemporaryDirectory() as tmpdir: |
|
25 | with TemporaryDirectory() as tmpdir: | |
26 | hist_manager_ori = ip.history_manager |
|
26 | hist_manager_ori = ip.history_manager | |
27 | hist_file = os.path.join(tmpdir, 'history.sqlite') |
|
27 | hist_file = os.path.join(tmpdir, 'history.sqlite') | |
28 | try: |
|
28 | try: | |
29 | ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file) |
|
29 | ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file) | |
30 | hist = ['a=1', 'def f():\n test = 1\n return test', u"b='β¬ΓΒΎΓ·Γ'"] |
|
30 | hist = ['a=1', 'def f():\n test = 1\n return test', u"b='β¬ΓΒΎΓ·Γ'"] | |
31 | for i, h in enumerate(hist, start=1): |
|
31 | for i, h in enumerate(hist, start=1): | |
32 | ip.history_manager.store_inputs(i, h) |
|
32 | ip.history_manager.store_inputs(i, h) | |
33 |
|
33 | |||
34 | ip.history_manager.db_log_output = True |
|
34 | ip.history_manager.db_log_output = True | |
35 | # Doesn't match the input, but we'll just check it's stored. |
|
35 | # Doesn't match the input, but we'll just check it's stored. | |
36 |
ip.history_manager.output_hist_reprs[3] |
|
36 | ip.history_manager.output_hist_reprs[3] = "spam" | |
37 | ip.history_manager.store_output(3) |
|
37 | ip.history_manager.store_output(3) | |
38 |
|
38 | |||
39 | nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist) |
|
39 | nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist) | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | # New session |
|
42 | # New session | |
43 | ip.history_manager.reset() |
|
43 | ip.history_manager.reset() | |
44 | newcmds = ["z=5","class X(object):\n pass", "k='p'"] |
|
44 | newcmds = ["z=5","class X(object):\n pass", "k='p'"] | |
45 | for i, cmd in enumerate(newcmds, start=1): |
|
45 | for i, cmd in enumerate(newcmds, start=1): | |
46 | ip.history_manager.store_inputs(i, cmd) |
|
46 | ip.history_manager.store_inputs(i, cmd) | |
47 | gothist = ip.history_manager.get_range(start=1, stop=4) |
|
47 | gothist = ip.history_manager.get_range(start=1, stop=4) | |
48 | nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds)) |
|
48 | nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds)) | |
49 | # Previous session: |
|
49 | # Previous session: | |
50 | gothist = ip.history_manager.get_range(-1, 1, 4) |
|
50 | gothist = ip.history_manager.get_range(-1, 1, 4) | |
51 | nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist)) |
|
51 | nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist)) | |
52 |
|
52 | |||
53 | # Check get_hist_tail |
|
53 | # Check get_hist_tail | |
54 | gothist = ip.history_manager.get_tail(4, output=True, |
|
54 | gothist = ip.history_manager.get_tail(4, output=True, | |
55 | include_latest=True) |
|
55 | include_latest=True) | |
56 |
expected = [(1, 3, (hist[-1], |
|
56 | expected = [(1, 3, (hist[-1], "spam")), | |
57 | (2, 1, (newcmds[0], None)), |
|
57 | (2, 1, (newcmds[0], None)), | |
58 | (2, 2, (newcmds[1], None)), |
|
58 | (2, 2, (newcmds[1], None)), | |
59 | (2, 3, (newcmds[2], None)),] |
|
59 | (2, 3, (newcmds[2], None)),] | |
60 | nt.assert_equal(list(gothist), expected) |
|
60 | nt.assert_equal(list(gothist), expected) | |
61 |
|
61 | |||
62 | gothist = ip.history_manager.get_tail(2) |
|
62 | gothist = ip.history_manager.get_tail(2) | |
63 | expected = [(2, 1, newcmds[0]), |
|
63 | expected = [(2, 1, newcmds[0]), | |
64 | (2, 2, newcmds[1])] |
|
64 | (2, 2, newcmds[1])] | |
65 | nt.assert_equal(list(gothist), expected) |
|
65 | nt.assert_equal(list(gothist), expected) | |
66 |
|
66 | |||
67 | # Check get_hist_search |
|
67 | # Check get_hist_search | |
68 | gothist = ip.history_manager.search("*test*") |
|
68 | gothist = ip.history_manager.search("*test*") | |
69 | nt.assert_equal(list(gothist), [(1,2,hist[1])] ) |
|
69 | nt.assert_equal(list(gothist), [(1,2,hist[1])] ) | |
70 | gothist = ip.history_manager.search("b*", output=True) |
|
70 | gothist = ip.history_manager.search("b*", output=True) | |
71 |
nt.assert_equal(list(gothist), [(1,3,(hist[2], |
|
71 | nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] ) | |
72 |
|
72 | |||
73 | # Cross testing: check that magic %save can get previous session. |
|
73 | # Cross testing: check that magic %save can get previous session. | |
74 | testfilename = os.path.realpath(os.path.join(tmpdir, "test.py")) |
|
74 | testfilename = os.path.realpath(os.path.join(tmpdir, "test.py")) | |
75 | ip.magic_save(testfilename + " ~1/1-3") |
|
75 | ip.magic_save(testfilename + " ~1/1-3") | |
76 | testfile = open(testfilename, "r") |
|
76 | testfile = open(testfilename, "r") | |
77 | nt.assert_equal(testfile.read().decode("utf-8"), |
|
77 | nt.assert_equal(testfile.read().decode("utf-8"), | |
78 | "# coding: utf-8\n" + "\n".join(hist)) |
|
78 | "# coding: utf-8\n" + "\n".join(hist)) | |
79 |
|
79 | |||
80 | # Duplicate line numbers - check that it doesn't crash, and |
|
80 | # Duplicate line numbers - check that it doesn't crash, and | |
81 | # gets a new session |
|
81 | # gets a new session | |
82 | ip.history_manager.store_inputs(1, "rogue") |
|
82 | ip.history_manager.store_inputs(1, "rogue") | |
83 | ip.history_manager.writeout_cache() |
|
83 | ip.history_manager.writeout_cache() | |
84 | nt.assert_equal(ip.history_manager.session_number, 3) |
|
84 | nt.assert_equal(ip.history_manager.session_number, 3) | |
85 | finally: |
|
85 | finally: | |
86 | # Restore history manager |
|
86 | # Restore history manager | |
87 | ip.history_manager = hist_manager_ori |
|
87 | ip.history_manager = hist_manager_ori | |
88 |
|
88 | |||
89 |
|
89 | |||
90 | def test_extract_hist_ranges(): |
|
90 | def test_extract_hist_ranges(): | |
91 | instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5" |
|
91 | instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5" | |
92 | expected = [(0, 1, 2), # 0 == current session |
|
92 | expected = [(0, 1, 2), # 0 == current session | |
93 | (2, 3, 4), |
|
93 | (2, 3, 4), | |
94 | (-4, 5, 7), |
|
94 | (-4, 5, 7), | |
95 | (-4, 7, 10), |
|
95 | (-4, 7, 10), | |
96 | (-9, 2, None), # None == to end |
|
96 | (-9, 2, None), # None == to end | |
97 | (-8, 1, None), |
|
97 | (-8, 1, None), | |
98 | (-7, 1, 6)] |
|
98 | (-7, 1, 6)] | |
99 | actual = list(extract_hist_ranges(instr)) |
|
99 | actual = list(extract_hist_ranges(instr)) | |
100 | nt.assert_equal(actual, expected) |
|
100 | nt.assert_equal(actual, expected) | |
101 |
|
101 | |||
102 | def test_magic_rerun(): |
|
102 | def test_magic_rerun(): | |
103 | """Simple test for %rerun (no args -> rerun last line)""" |
|
103 | """Simple test for %rerun (no args -> rerun last line)""" | |
104 | ip = get_ipython() |
|
104 | ip = get_ipython() | |
105 | ip.run_cell("a = 10") |
|
105 | ip.run_cell("a = 10") | |
106 | ip.run_cell("a += 1") |
|
106 | ip.run_cell("a += 1") | |
107 | nt.assert_equal(ip.user_ns["a"], 11) |
|
107 | nt.assert_equal(ip.user_ns["a"], 11) | |
108 | ip.run_cell("%rerun") |
|
108 | ip.run_cell("%rerun") | |
109 | nt.assert_equal(ip.user_ns["a"], 12) |
|
109 | nt.assert_equal(ip.user_ns["a"], 12) |
General Comments 0
You need to be logged in to leave comments.
Login now